-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.spec.js
More file actions
236 lines (208 loc) · 7.79 KB
/
index.spec.js
File metadata and controls
236 lines (208 loc) · 7.79 KB
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
require('dotenv-flow').config();
const debugLog = require('debug')('test:debug');
const fetch = require('node-fetch');
const getPort = require('get-port');
const promisify = require('pify');
const mockSpawn = require('mock-spawn');
const nock = require('nock');
const crypto = require('crypto');
const pushEventPayload = require('./fixtures/pull_request_payload');
// Create signature for the push event payload
const hmac = crypto.createHmac('SHA1', process.env.GITHUB_SECRET);
hmac.update(JSON.stringify(pushEventPayload));
const pushEventPayloadSignature = hmac.digest('hex');
debugLog({ pushEventPayloadSignature });
describe('github-webhook-service', () => {
let port;
let mockSpawnMock;
let mockReadFileSync;
let mockWriteFileSync;
let mockRimraf;
let mockS3Upload;
beforeEach((done) => {
nock.disableNetConnect();
// get an available port for the server
getPort().then((availablePort) => {
port = availablePort;
done();
});
jest.mock('rimraf', () => {
mockRimraf = jest.fn((folderLocation, callback) => {
callback();
});
return mockRimraf;
});
jest.mock('child_process', () => {
mockSpawnMock = mockSpawn();
mockSpawnMock.setDefault(mockSpawnMock.simple(0));
return {
spawn: mockSpawnMock,
};
});
// set up possibility to mock specific readFileSync calls
jest.doMock('fs', () => {
const fs = jest.requireActual('fs');
const originalReadFileSync = fs.readFileSync;
let mockFiles = {};
fs.setMockFiles = (files) => {
mockFiles = {
...mockFiles,
...files,
};
};
mockReadFileSync = jest.fn((filename, ...rest) => {
if (mockFiles[filename]) {
return mockFiles[filename];
}
return originalReadFileSync.call(this, filename, ...rest);
});
fs.readFileSync = mockReadFileSync;
fs.createReadStream = jest.fn(filename => `Mocked readStream: ${filename}`);
mockWriteFileSync = jest.fn();
fs.writeFileSync = mockWriteFileSync;
return fs;
});
// use same upload mock for all three S3 calls
mockS3Upload = jest.fn((_params, _options, callback) => {
const errors = false;
const data = {};
callback(errors, data);
});
jest.mock('aws-sdk/clients/s3', () => {
function mockS3() {
return {
upload: mockS3Upload,
};
}
return mockS3;
});
});
afterEach(() => {
nock.restore();
});
test('the server accepts pull request webhook events', (done) => {
nock.enableNetConnect(`localhost:${port}`);
const mockGithubAPIPostBody = jest.fn(() => true);
const mockGithubAPI = nock('https://api.github.com:443')
.post(
'/repos/repository-owner/repository-name/statuses/git-commit-sha',
mockGithubAPIPostBody,
)
.times(2)
.reply(201);
const fs = require('fs');
fs.setMockFiles({
'/tmp/repository-name-master/dist/stats.json': JSON.stringify({
chunks: [
{
files: ['increased-bundle.js'],
size: 1,
},
],
}),
'/tmp/repository-name-feature-branch/dist/stats.json': JSON.stringify({
chunks: [
{
files: ['increased-bundle.js'],
size: 4000,
},
],
}),
});
const { server } = require('./index');
promisify(server.listen.bind(server))(port)
.then(() =>
fetch(`http://localhost:${port}`, {
method: 'POST',
body: JSON.stringify(pushEventPayload),
headers: {
'X-GitHub-Delivery': '123e4567-e89b-12d3-a456-426655440000',
'X-GitHub-Event': 'pull_request',
'X-Hub-Signature': `sha1=${pushEventPayloadSignature}`,
},
}))
.then((result) => {
// Check that the directories from the previous run has been deleted
expect(mockRimraf).toHaveBeenCalledTimes(2);
expect(mockRimraf).toHaveBeenCalledWith(
'/tmp/repository-name-master',
expect.any(Function),
);
expect(mockRimraf).toHaveBeenCalledWith(
'/tmp/repository-name-feature-branch',
expect.any(Function),
);
// Check that the github status is set to pending
expect(mockGithubAPIPostBody).toHaveBeenNthCalledWith(1, {
context: 'Perf',
state: 'pending',
});
// Download github repos and generate stats.json files
expect(mockSpawnMock.calls.length).toBe(6);
expect(mockSpawnMock.calls.map(({ command, args }) => `${command} ${args.join(' ')}`)).toEqual(expect.arrayContaining([
'git clone --branch master --single-branch --depth=1 git@github.com:repository-owner/repository-name /tmp/repository-name-master',
'yarn install --production=false --cwd=/tmp/repository-name-master',
'yarn --cwd=/tmp/repository-name-master build:webpack-bundle-analyzer',
'git clone --branch feature-branch --single-branch --depth=1 git@github.com:repository-owner/repository-name /tmp/repository-name-feature-branch',
'yarn install --production=false --cwd=/tmp/repository-name-feature-branch',
'yarn --cwd=/tmp/repository-name-feature-branch build:webpack-bundle-analyzer',
]));
// Check that the stats.json files are read
expect(mockReadFileSync).toHaveBeenNthCalledWith(
mockReadFileSync.mock.calls.length - 1,
'/tmp/repository-name-feature-branch/dist/stats.json',
);
expect(mockReadFileSync).toHaveBeenNthCalledWith(
mockReadFileSync.mock.calls.length,
'/tmp/repository-name-master/dist/stats.json',
);
// The report is generated correctly
expect(mockWriteFileSync).toHaveBeenCalledTimes(1);
const generatedReport = mockWriteFileSync.mock.calls[0][1];
expect(generatedReport).toMatchSnapshot();
expect(generatedReport).toMatch(/The total size increased with:\n.*\+4kB/);
expect(generatedReport).toMatch(/increased-bundle.js.*\n.*\+4kB.*\n.*4kB.*\n.*1B/);
// Files are uploaded to S3
expect(mockS3Upload).toHaveBeenCalledTimes(5);
expect(mockS3Upload).toHaveBeenCalledWith(
expect.objectContaining({
Body: 'Mocked readStream: /tmp/repository-name-feature-branch/dist/index.html',
Key: 'repository-name-feature-branch-index.html',
}),
expect.any(Object),
expect.any(Function),
);
expect(mockS3Upload).toHaveBeenCalledWith(
expect.objectContaining({
Body: 'Mocked readStream: /tmp/repository-name-feature-branch/dist/report.html',
Key: 'repository-name-feature-branch-report.html',
}),
expect.any(Object),
expect.any(Function),
);
expect(mockS3Upload).toHaveBeenCalledWith(
expect.objectContaining({
Body: 'Mocked readStream: /tmp/repository-name-master/dist/report.html',
Key: 'repository-name-master-report.html',
}),
expect.any(Object),
expect.any(Function),
);
// Check that the check results are reported back to github
expect(mockGithubAPI.isDone()).toBe(true);
expect(mockGithubAPIPostBody).toHaveBeenCalledTimes(2);
expect(mockGithubAPIPostBody).toHaveBeenNthCalledWith(2, {
context: 'Perf',
description: 'Size increase > 2kB (4kB) double check details',
state: 'failure',
target_url:
'https://s3-<region>.amazonaws.com/<bucket-name>/repository-name-feature-branch-index.html',
});
// Check that the server responded with 200
expect(result.status).toBe(200);
done();
})
.then(() => server.close())
.catch(console.error);
}, 1e3);
});