1 /* eslint-disable @typescript-eslint/no-floating-promises */
3 import { decode } from 'querystring'
4 import request from 'supertest'
5 import { URL } from 'url'
6 import { buildAbsoluteFixturePath, pick } from '@shared/core-utils'
7 import { HttpStatusCode } from '@shared/models'
9 export type CommonRequestParams = {
18 headers?: { [ name: string ]: string }
20 xForwardedFor?: string
21 expectedStatus?: HttpStatusCode
24 function makeRawRequest (options: {
27 expectedStatus?: HttpStatusCode
29 query?: { [ id: string ]: string }
31 const { host, protocol, pathname } = new URL(options.url)
33 return makeGetRequest({
34 url: `${protocol}//${host}`,
36 contentType: undefined,
38 ...pick(options, [ 'expectedStatus', 'range', 'token', 'query' ])
42 function makeGetRequest (options: CommonRequestParams & {
46 const req = request(options.url).get(options.path)
48 if (options.query) req.query(options.query)
49 if (options.rawQuery) req.query(options.rawQuery)
51 return buildRequest(req, { contentType: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
54 function makeHTMLRequest (url: string, path: string) {
55 return makeGetRequest({
59 expectedStatus: HttpStatusCode.OK_200
63 function makeActivityPubGetRequest (url: string, path: string, expectedStatus = HttpStatusCode.OK_200) {
64 return makeGetRequest({
68 accept: 'application/activity+json,text/html;q=0.9,\\*/\\*;q=0.8'
72 function makeDeleteRequest (options: CommonRequestParams & {
76 const req = request(options.url).delete(options.path)
78 if (options.query) req.query(options.query)
79 if (options.rawQuery) req.query(options.rawQuery)
81 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
84 function makeUploadRequest (options: CommonRequestParams & {
85 method?: 'POST' | 'PUT'
87 fields: { [ fieldName: string ]: any }
88 attaches?: { [ attachName: string ]: any | any[] }
90 let req = options.method === 'PUT'
91 ? request(options.url).put(options.path)
92 : request(options.url).post(options.path)
94 req = buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
96 buildFields(req, options.fields)
98 Object.keys(options.attaches || {}).forEach(attach => {
99 const value = options.attaches[attach]
102 if (Array.isArray(value)) {
103 req.attach(attach, buildAbsoluteFixturePath(value[0]), value[1])
105 req.attach(attach, buildAbsoluteFixturePath(value))
112 function makePostBodyRequest (options: CommonRequestParams & {
113 fields?: { [ fieldName: string ]: any }
115 const req = request(options.url).post(options.path)
116 .send(options.fields)
118 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
121 function makePutBodyRequest (options: {
125 fields: { [ fieldName: string ]: any }
126 expectedStatus?: HttpStatusCode
128 const req = request(options.url).put(options.path)
129 .send(options.fields)
131 return buildRequest(req, { accept: 'application/json', expectedStatus: HttpStatusCode.BAD_REQUEST_400, ...options })
134 function decodeQueryString (path: string) {
135 return decode(path.split('?')[1])
138 function unwrapBody <T> (test: request.Test): Promise<T> {
139 return test.then(res => res.body)
142 function unwrapText (test: request.Test): Promise<string> {
143 return test.then(res => res.text)
146 function unwrapBodyOrDecodeToJSON <T> (test: request.Test): Promise<T> {
147 return test.then(res => {
148 if (res.body instanceof Buffer) {
150 return JSON.parse(new TextDecoder().decode(res.body))
152 console.error('Cannot decode JSON.', res.body)
161 function unwrapTextOrDecode (test: request.Test): Promise<string> {
162 return test.then(res => res.text || new TextDecoder().decode(res.body))
165 // ---------------------------------------------------------------------------
176 makeActivityPubGetRequest,
179 unwrapBodyOrDecodeToJSON,
183 // ---------------------------------------------------------------------------
185 function buildRequest (req: request.Test, options: CommonRequestParams) {
186 if (options.contentType) req.set('Accept', options.contentType)
187 if (options.token) req.set('Authorization', 'Bearer ' + options.token)
188 if (options.range) req.set('Range', options.range)
189 if (options.accept) req.set('Accept', options.accept)
190 if (options.host) req.set('Host', options.host)
191 if (options.redirects) req.redirects(options.redirects)
192 if (options.xForwardedFor) req.set('X-Forwarded-For', options.xForwardedFor)
193 if (options.type) req.type(options.type)
195 Object.keys(options.headers || {}).forEach(name => {
196 req.set(name, options.headers[name])
199 return req.expect((res) => {
200 if (options.expectedStatus && res.status !== options.expectedStatus) {
201 throw new Error(`Expected status ${options.expectedStatus}, got ${res.status}. ` +
202 `\nThe server responded: "${res.body?.error ?? res.text}".\n` +
203 'You may take a closer look at the logs. To see how to do so, check out this page: ' +
204 'https://github.com/Chocobozzz/PeerTube/blob/develop/support/doc/development/tests.md#debug-server-logs')
210 function buildFields (req: request.Test, fields: { [ fieldName: string ]: any }, namespace?: string) {
215 for (const key of Object.keys(fields)) {
216 if (namespace) formKey = `${namespace}[${key}]`
219 if (fields[key] === undefined) continue
221 if (Array.isArray(fields[key]) && fields[key].length === 0) {
226 if (fields[key] !== null && typeof fields[key] === 'object') {
227 buildFields(req, fields[key], formKey)
229 req.field(formKey, fields[key])