-
Notifications
You must be signed in to change notification settings - Fork 0
/
back.js
335 lines (270 loc) · 7.85 KB
/
back.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
'use strict'
const assert = require('assert')
const recorder = require('./recorder')
const {
activate,
disableNetConnect,
enableNetConnect,
removeAll: cleanAll,
} = require('./intercept')
const { loadDefs, define } = require('./scope')
const { format } = require('util')
const path = require('path')
const debug = require('debug')('nock.back')
let _mode = null
let fs
try {
fs = require('fs')
} catch (err) {
// do nothing, probably in browser
}
/**
* nock the current function with the fixture given
*
* @param {string} fixtureName - the name of the fixture, e.x. 'foo.json'
* @param {object} options - [optional] extra options for nock with, e.x. `{ assert: true }`
* @param {function} nockedFn - [optional] callback function to be executed with the given fixture being loaded;
* if defined the function will be called with context `{ scopes: loaded_nocks || [] }`
* set as `this` and `nockDone` callback function as first and only parameter;
* if not defined a promise resolving to `{nockDone, context}` where `context` is
* aforementioned `{ scopes: loaded_nocks || [] }`
*
* List of options:
*
* @param {function} before - a preprocessing function, gets called before nock.define
* @param {function} after - a postprocessing function, gets called after nock.define
* @param {function} afterRecord - a postprocessing function, gets called after recording. Is passed the array
* of scopes recorded and should return the array scopes to save to the fixture
* @param {function} recorder - custom options to pass to the recorder
*
*/
function Back(fixtureName, options, nockedFn) {
if (!Back.fixtures) {
throw new Error(
'Back requires nock.back.fixtures to be set\n' +
'Ex:\n' +
"\trequire(nock).back.fixtures = '/path/to/fixtures/'"
)
}
if (typeof fixtureName !== 'string') {
throw new Error('Parameter fixtureName must be a string')
}
if (arguments.length === 1) {
options = {}
} else if (arguments.length === 2) {
// If 2nd parameter is a function then `options` has been omitted
// otherwise `options` haven't been omitted but `nockedFn` was.
if (typeof options === 'function') {
nockedFn = options
options = {}
}
}
_mode.setup()
const fixture = path.join(Back.fixtures, fixtureName)
const context = _mode.start(fixture, options)
const nockDone = function () {
_mode.finish(fixture, options, context)
}
debug('context:', context)
// If nockedFn is a function then invoke it, otherwise return a promise resolving to nockDone.
if (typeof nockedFn === 'function') {
nockedFn.call(context, nockDone)
} else {
return Promise.resolve({ nockDone, context })
}
}
/*******************************************************************************
* Modes *
*******************************************************************************/
const wild = {
setup: function () {
cleanAll()
recorder.restore()
activate()
enableNetConnect()
},
start: function () {
return load() // don't load anything but get correct context
},
finish: function () {
// nothing to do
},
}
const dryrun = {
setup: function () {
recorder.restore()
cleanAll()
activate()
// We have to explicitly enable net connectivity as by default it's off.
enableNetConnect()
},
start: function (fixture, options) {
const contexts = load(fixture, options)
enableNetConnect()
return contexts
},
finish: function () {
// nothing to do
},
}
const record = {
setup: function () {
recorder.restore()
recorder.clear()
cleanAll()
activate()
disableNetConnect()
},
start: function (fixture, options) {
if (!fs) {
throw new Error('no fs')
}
const context = load(fixture, options)
if (!context.isLoaded) {
recorder.record({
dont_print: true,
output_objects: true,
...options.recorder,
})
context.isRecording = true
}
return context
},
finish: function (fixture, options, context) {
if (context.isRecording) {
let outputs = recorder.outputs()
if (typeof options.afterRecord === 'function') {
outputs = options.afterRecord(outputs)
}
outputs =
typeof outputs === 'string' ? outputs : JSON.stringify(outputs, null, 4)
debug('recorder outputs:', outputs)
fs.mkdirSync(path.dirname(fixture), { recursive: true })
fs.writeFileSync(fixture, outputs)
}
},
}
const update = {
setup: function () {
recorder.restore()
recorder.clear()
cleanAll()
activate()
disableNetConnect()
},
start: function (fixture, options) {
if (!fs) {
throw new Error('no fs')
}
const context = removeFixture(fixture)
recorder.record({
dont_print: true,
output_objects: true,
...options.recorder,
})
context.isRecording = true
return context
},
finish: function (fixture, options, context) {
let outputs = recorder.outputs()
if (typeof options.afterRecord === 'function') {
outputs = options.afterRecord(outputs)
}
outputs =
typeof outputs === 'string' ? outputs : JSON.stringify(outputs, null, 4)
debug('recorder outputs:', outputs)
fs.mkdirSync(path.dirname(fixture), { recursive: true })
fs.writeFileSync(fixture, outputs)
},
}
const lockdown = {
setup: function () {
recorder.restore()
recorder.clear()
cleanAll()
activate()
disableNetConnect()
},
start: function (fixture, options) {
return load(fixture, options)
},
finish: function () {
// nothing to do
},
}
function load(fixture, options) {
const context = {
scopes: [],
assertScopesFinished: function () {
assertScopes(this.scopes, fixture)
},
}
if (fixture && fixtureExists(fixture)) {
let scopes = loadDefs(fixture)
applyHook(scopes, options.before)
scopes = define(scopes)
applyHook(scopes, options.after)
context.scopes = scopes
context.isLoaded = true
}
return context
}
function removeFixture(fixture, options) {
const context = {
scopes: [],
assertScopesFinished: function () {},
}
if (fixture && fixtureExists(fixture)) {
fs.rmSync ? fs.rmSync(fixture) : fs.unlinkSync(fixture)
}
context.isLoaded = false
return context
}
function applyHook(scopes, fn) {
if (!fn) {
return
}
if (typeof fn !== 'function') {
throw new Error('processing hooks must be a function')
}
scopes.forEach(fn)
}
function fixtureExists(fixture) {
if (!fs) {
throw new Error('no fs')
}
return fs.existsSync(fixture)
}
function assertScopes(scopes, fixture) {
const pending = scopes
.filter(scope => !scope.isDone())
.map(scope => scope.pendingMocks())
if (pending.length) {
assert.fail(
format(
'%j was not used, consider removing %s to rerecord fixture',
[].concat(...pending),
fixture
)
)
}
}
const Modes = {
wild, // all requests go out to the internet, dont replay anything, doesnt record anything
dryrun, // use recorded nocks, allow http calls, doesnt record anything, useful for writing new tests (default)
record, // use recorded nocks, record new nocks
update, // allow http calls, record all nocks, don't use recorded nocks
lockdown, // use recorded nocks, disables all http calls even when not nocked, doesnt record
}
Back.setMode = function (mode) {
if (!(mode in Modes)) {
throw new Error(`Unknown mode: ${mode}`)
}
Back.currentMode = mode
debug('New nock back mode:', Back.currentMode)
_mode = Modes[mode]
_mode.setup()
}
Back.fixtures = null
Back.currentMode = null
module.exports = Back