mock-utils.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. 'use strict'
  2. const { MockNotMatchedError } = require('./mock-errors')
  3. const {
  4. kDispatches,
  5. kMockAgent,
  6. kOriginalDispatch,
  7. kOrigin,
  8. kGetNetConnect
  9. } = require('./mock-symbols')
  10. const { buildURL, nop } = require('../core/util')
  11. const { STATUS_CODES } = require('http')
  12. const {
  13. types: {
  14. isPromise
  15. }
  16. } = require('util')
  17. function matchValue (match, value) {
  18. if (typeof match === 'string') {
  19. return match === value
  20. }
  21. if (match instanceof RegExp) {
  22. return match.test(value)
  23. }
  24. if (typeof match === 'function') {
  25. return match(value) === true
  26. }
  27. return false
  28. }
  29. function lowerCaseEntries (headers) {
  30. return Object.fromEntries(
  31. Object.entries(headers).map(([headerName, headerValue]) => {
  32. return [headerName.toLocaleLowerCase(), headerValue]
  33. })
  34. )
  35. }
  36. /**
  37. * @param {import('../../index').Headers|string[]|Record<string, string>} headers
  38. * @param {string} key
  39. */
  40. function getHeaderByName (headers, key) {
  41. if (Array.isArray(headers)) {
  42. for (let i = 0; i < headers.length; i += 2) {
  43. if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
  44. return headers[i + 1]
  45. }
  46. }
  47. return undefined
  48. } else if (typeof headers.get === 'function') {
  49. return headers.get(key)
  50. } else {
  51. return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
  52. }
  53. }
  54. /** @param {string[]} headers */
  55. function buildHeadersFromArray (headers) { // fetch HeadersList
  56. const clone = headers.slice()
  57. const entries = []
  58. for (let index = 0; index < clone.length; index += 2) {
  59. entries.push([clone[index], clone[index + 1]])
  60. }
  61. return Object.fromEntries(entries)
  62. }
  63. function matchHeaders (mockDispatch, headers) {
  64. if (typeof mockDispatch.headers === 'function') {
  65. if (Array.isArray(headers)) { // fetch HeadersList
  66. headers = buildHeadersFromArray(headers)
  67. }
  68. return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
  69. }
  70. if (typeof mockDispatch.headers === 'undefined') {
  71. return true
  72. }
  73. if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
  74. return false
  75. }
  76. for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
  77. const headerValue = getHeaderByName(headers, matchHeaderName)
  78. if (!matchValue(matchHeaderValue, headerValue)) {
  79. return false
  80. }
  81. }
  82. return true
  83. }
  84. function safeUrl (path) {
  85. if (typeof path !== 'string') {
  86. return path
  87. }
  88. const pathSegments = path.split('?')
  89. if (pathSegments.length !== 2) {
  90. return path
  91. }
  92. const qp = new URLSearchParams(pathSegments.pop())
  93. qp.sort()
  94. return [...pathSegments, qp.toString()].join('?')
  95. }
  96. function matchKey (mockDispatch, { path, method, body, headers }) {
  97. const pathMatch = matchValue(mockDispatch.path, path)
  98. const methodMatch = matchValue(mockDispatch.method, method)
  99. const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
  100. const headersMatch = matchHeaders(mockDispatch, headers)
  101. return pathMatch && methodMatch && bodyMatch && headersMatch
  102. }
  103. function getResponseData (data) {
  104. if (Buffer.isBuffer(data)) {
  105. return data
  106. } else if (typeof data === 'object') {
  107. return JSON.stringify(data)
  108. } else {
  109. return data.toString()
  110. }
  111. }
  112. function getMockDispatch (mockDispatches, key) {
  113. const basePath = key.query ? buildURL(key.path, key.query) : key.path
  114. const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
  115. // Match path
  116. let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
  117. if (matchedMockDispatches.length === 0) {
  118. throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
  119. }
  120. // Match method
  121. matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
  122. if (matchedMockDispatches.length === 0) {
  123. throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)
  124. }
  125. // Match body
  126. matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
  127. if (matchedMockDispatches.length === 0) {
  128. throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)
  129. }
  130. // Match headers
  131. matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
  132. if (matchedMockDispatches.length === 0) {
  133. throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
  134. }
  135. return matchedMockDispatches[0]
  136. }
  137. function addMockDispatch (mockDispatches, key, data) {
  138. const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
  139. const replyData = typeof data === 'function' ? { callback: data } : { ...data }
  140. const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
  141. mockDispatches.push(newMockDispatch)
  142. return newMockDispatch
  143. }
  144. function deleteMockDispatch (mockDispatches, key) {
  145. const index = mockDispatches.findIndex(dispatch => {
  146. if (!dispatch.consumed) {
  147. return false
  148. }
  149. return matchKey(dispatch, key)
  150. })
  151. if (index !== -1) {
  152. mockDispatches.splice(index, 1)
  153. }
  154. }
  155. function buildKey (opts) {
  156. const { path, method, body, headers, query } = opts
  157. return {
  158. path,
  159. method,
  160. body,
  161. headers,
  162. query
  163. }
  164. }
  165. function generateKeyValues (data) {
  166. return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
  167. ...keyValuePairs,
  168. Buffer.from(`${key}`),
  169. Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
  170. ], [])
  171. }
  172. /**
  173. * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
  174. * @param {number} statusCode
  175. */
  176. function getStatusText (statusCode) {
  177. return STATUS_CODES[statusCode] || 'unknown'
  178. }
  179. async function getResponse (body) {
  180. const buffers = []
  181. for await (const data of body) {
  182. buffers.push(data)
  183. }
  184. return Buffer.concat(buffers).toString('utf8')
  185. }
  186. /**
  187. * Mock dispatch function used to simulate undici dispatches
  188. */
  189. function mockDispatch (opts, handler) {
  190. // Get mock dispatch from built key
  191. const key = buildKey(opts)
  192. const mockDispatch = getMockDispatch(this[kDispatches], key)
  193. mockDispatch.timesInvoked++
  194. // Here's where we resolve a callback if a callback is present for the dispatch data.
  195. if (mockDispatch.data.callback) {
  196. mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
  197. }
  198. // Parse mockDispatch data
  199. const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
  200. const { timesInvoked, times } = mockDispatch
  201. // If it's used up and not persistent, mark as consumed
  202. mockDispatch.consumed = !persist && timesInvoked >= times
  203. mockDispatch.pending = timesInvoked < times
  204. // If specified, trigger dispatch error
  205. if (error !== null) {
  206. deleteMockDispatch(this[kDispatches], key)
  207. handler.onError(error)
  208. return true
  209. }
  210. // Handle the request with a delay if necessary
  211. if (typeof delay === 'number' && delay > 0) {
  212. setTimeout(() => {
  213. handleReply(this[kDispatches])
  214. }, delay)
  215. } else {
  216. handleReply(this[kDispatches])
  217. }
  218. function handleReply (mockDispatches, _data = data) {
  219. // fetch's HeadersList is a 1D string array
  220. const optsHeaders = Array.isArray(opts.headers)
  221. ? buildHeadersFromArray(opts.headers)
  222. : opts.headers
  223. const body = typeof _data === 'function'
  224. ? _data({ ...opts, headers: optsHeaders })
  225. : _data
  226. // util.types.isPromise is likely needed for jest.
  227. if (isPromise(body)) {
  228. // If handleReply is asynchronous, throwing an error
  229. // in the callback will reject the promise, rather than
  230. // synchronously throw the error, which breaks some tests.
  231. // Rather, we wait for the callback to resolve if it is a
  232. // promise, and then re-run handleReply with the new body.
  233. body.then((newData) => handleReply(mockDispatches, newData))
  234. return
  235. }
  236. const responseData = getResponseData(body)
  237. const responseHeaders = generateKeyValues(headers)
  238. const responseTrailers = generateKeyValues(trailers)
  239. handler.abort = nop
  240. handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
  241. handler.onData(Buffer.from(responseData))
  242. handler.onComplete(responseTrailers)
  243. deleteMockDispatch(mockDispatches, key)
  244. }
  245. function resume () {}
  246. return true
  247. }
  248. function buildMockDispatch () {
  249. const agent = this[kMockAgent]
  250. const origin = this[kOrigin]
  251. const originalDispatch = this[kOriginalDispatch]
  252. return function dispatch (opts, handler) {
  253. if (agent.isMockActive) {
  254. try {
  255. mockDispatch.call(this, opts, handler)
  256. } catch (error) {
  257. if (error instanceof MockNotMatchedError) {
  258. const netConnect = agent[kGetNetConnect]()
  259. if (netConnect === false) {
  260. throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
  261. }
  262. if (checkNetConnect(netConnect, origin)) {
  263. originalDispatch.call(this, opts, handler)
  264. } else {
  265. throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
  266. }
  267. } else {
  268. throw error
  269. }
  270. }
  271. } else {
  272. originalDispatch.call(this, opts, handler)
  273. }
  274. }
  275. }
  276. function checkNetConnect (netConnect, origin) {
  277. const url = new URL(origin)
  278. if (netConnect === true) {
  279. return true
  280. } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
  281. return true
  282. }
  283. return false
  284. }
  285. function buildMockOptions (opts) {
  286. if (opts) {
  287. const { agent, ...mockOptions } = opts
  288. return mockOptions
  289. }
  290. }
  291. module.exports = {
  292. getResponseData,
  293. getMockDispatch,
  294. addMockDispatch,
  295. deleteMockDispatch,
  296. buildKey,
  297. generateKeyValues,
  298. matchValue,
  299. getResponse,
  300. getStatusText,
  301. mockDispatch,
  302. buildMockDispatch,
  303. checkNetConnect,
  304. buildMockOptions,
  305. getHeaderByName
  306. }