-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
97 lines (78 loc) · 2.1 KB
/
index.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
var axios = require('axios');
var fs = require('fs');
var _ = require('lodash');
var stringify = require('json-stable-stringify');
module.exports = {
testUpstreamChanges: testUpstreamChanges
};
function toString(x) {
return stringify(x, { space: ' ' });
}
function defaultRunner(description, callback) {
return callback();
}
function defaultAssert(actual, expected) {
var act = toString(actual);
if (act !== toString(expected)) {
throw new Error('Fixture mismatch, actual: ' + act);
}
}
var defaults = {
urls: [],
runner: defaultRunner,
base: '',
method: 'GET',
headers: {},
ignores: [],
placeholder: null,
transforms: [],
learn: false,
assert: defaultAssert,
fixtures: '/dev/null/'
};
function testUpstreamChanges(options) {
return Promise.all((options.urls || []).map(function(url) {
return opt('runner')(opt('url'), function() {
return axios({
url: opt('base') + opt('url'),
method: opt('method'),
headers: opt('headers')
}).then(test, test);
});
function opt(name) {
if (name === 'url' && _.isString(url)) return url;
if (url[name]) return url[name];
if (options[name]) return options[name];
return defaults[name];
}
function test(res) {
if (_.isError(res)) throw res;
var actual = _.omit(res, 'config');
opt('ignores').forEach(function(ignore) {
if (_.has(actual, ignore)) {
_.set(actual, ignore, opt('placeholder'));
}
});
opt('transforms').forEach(function(transform) {
try {
transform(actual);
} catch (e) {}
});
if (opt('learn')) {
fs.writeFileSync(filename(), toString(actual));
} else {
var expected = JSON.parse(fs.readFileSync(filename()));
opt('assert')(actual, expected);
}
}
function filename() {
return opt('fixtures')
+ (opt('method') !== defaults.method ? opt('method') + '_' : '')
+ opt('url')
.replace(/^\//, '')
.replace(/[^a-zA-Z0-9-]/g, '_')
.replace(/_+/g, '_')
+ '.json';
}
}));
}