-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
424 lines (384 loc) · 13.9 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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/// <reference types="Cypress" />
// @ts-check
const debug = require('debug')('cypress-split')
const { getSpecs } = require('find-cypress-specs')
const ghCore = require('@actions/core')
const { getChunk } = require('./chunk')
const { findFile } = require('./find-file')
const {
splitByDuration,
hasTimeDifferences,
mergeTimings,
} = require('./timings')
const {
getEnvironmentFlag,
printSpecsList,
printSpecsListWithDurations,
} = require('./utils')
const path = require('path')
const os = require('os')
const fs = require('fs')
const humanizeDuration = require('humanize-duration')
const label = 'cypress-split:'
const isDefined = (x) => typeof x !== 'undefined'
/**
* Initialize Cypress split plugin using Cypress "on" and "config" arguments.
* @param {Cypress.PluginEvents} on Cypress "on" event registration
* @param {Cypress.Config} config Cypress config object
*/
function cypressSplit(on, config) {
// maybe the user called this function with a single argument
// then we assume it is the config object
if (arguments.length === 1) {
debug('single argument, assuming it is the config object')
// @ts-ignore
config = on
}
if (config.spec) {
debug('config has specs set')
debug(config.spec)
}
// if we want to see all settings
// console.log(config)
// the user can specify the split flag / numbers
// using either OS process environment variables
// or Cypress env variables
debug('Cypress config env')
debug(config.env)
debug('current working directory %s', process.cwd())
debug('project root folder %s', config.projectRoot)
// collect the test results to generate a better report
const specResults = {}
// map from absolute to relative spec names as reported by Cypress
const specAbsoluteToRelative = {}
on('after:spec', (spec, results) => {
// console.log(results, results)
const passed = results.stats.failures === 0 && results.stats.passes > 0
if (passed) {
debug('after:spec for passed %s %o', spec.relative, results.stats)
} else {
debug('after:spec for %s %o', spec.relative, results.stats)
}
const cwd = process.cwd()
const absoluteSpecPath = spec.absolute || path.join(cwd, spec.relative)
// make sure there are no duplicate specs for some reason
if (specResults[absoluteSpecPath]) {
console.error(
'Warning: cypress-split found duplicate test results for %s',
absoluteSpecPath,
)
}
specResults[absoluteSpecPath] = results
specAbsoluteToRelative[absoluteSpecPath] = spec.relative
})
let SPLIT = process.env.SPLIT || config.env.split || config.env.SPLIT
let SPLIT_INDEX = process.env.SPLIT_INDEX || config.env.splitIndex
let SPLIT_FILE = process.env.SPLIT_FILE || config.env.splitFile
// some CI systems like TeamCity provide agent index starting with 1
// let's check for SPLIT_INDEX1 and if it is set,
// use it instead of zero-based SPLIT_INDEX
if (process.env.SPLIT_INDEX1 || config.env.splitIndex) {
const indexOne = process.env.SPLIT_INDEX1 || config.env.splitIndex
SPLIT_INDEX = Number(indexOne) - 1
debug(
'set SPLIT_INDEX to %d from index starting with 1 "%s"',
SPLIT_INDEX,
indexOne,
)
}
// potentially a list of files to run / split
let SPEC = process.env.SPEC || config.env.spec || config.env.SPEC
/** @type {string[]|undefined} absolute spec filenames */
let specs
if (typeof SPEC === 'string' && SPEC) {
specs = SPEC.split(',')
.map((s) => s.trim())
.filter(Boolean)
.map((specFilename) => {
// make sure every spec filename is absolute
return path.resolve(specFilename)
})
console.log(
'%s have explicit %d spec %s',
label,
specs.length,
specs.length === 1 ? 'file' : 'files',
)
}
if (SPLIT === 'true' || SPLIT === true) {
// the user wants us to determine the machine index
// and the total number of machines, which is possible for some CI systems
if (process.env.CIRCLECI) {
SPLIT = process.env.CIRCLE_NODE_TOTAL
SPLIT_INDEX = process.env.CIRCLE_NODE_INDEX
console.log(
'%s detected CircleCI machine %d of %d',
label,
SPLIT_INDEX,
SPLIT,
)
} else if (process.env.CI_NODE_INDEX && process.env.CI_NODE_TOTAL) {
// GitLab CI
// https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
SPLIT = process.env.CI_NODE_TOTAL
// GitLabCI index starts with 1
// convert it to zero base
SPLIT_INDEX = Number(process.env.CI_NODE_INDEX) - 1
console.log(
'%s detected GitLabCI machine %d of %d',
label,
SPLIT_INDEX,
SPLIT,
)
} else {
throw new Error('Do not know how to determine the correct split')
}
}
if (isDefined(SPLIT) && isDefined(SPLIT_INDEX)) {
if (!specs) {
const returnAbsolute = true
// @ts-ignore
specs = getSpecs(config, undefined, returnAbsolute)
}
console.log('%s there are %d found specs', label, specs.length)
// console.log(specs)
const splitN = Number(SPLIT)
const splitIndex = Number(SPLIT_INDEX)
console.log('%s chunk %d of %d', label, splitIndex + 1, splitN)
debug('get chunk %o', { specs, splitN, splitIndex })
/** @type {string[]} absolute spec filenames */
let splitSpecs
const cwd = process.cwd()
console.log('%s specs from the current directory %s', label, cwd)
let foundSplitFile
if (SPLIT_FILE) {
debug('loading split file %s', SPLIT_FILE)
try {
foundSplitFile = findFile(SPLIT_FILE)
if (!foundSplitFile) {
throw new Error(
`Could not find ${SPLIT_FILE} based on the current working directory ${cwd}`,
)
}
const splitFile = JSON.parse(fs.readFileSync(foundSplitFile, 'utf8'))
const previousDurations = splitFile.durations
const averageDuration =
previousDurations
.map((item) => item.duration)
.reduce((sum, duration) => (sum += duration), 0) /
previousDurations.length
const specsWithDurations = specs.map((specName) => {
const relativeSpec = path.relative(cwd, specName)
const foundInfo = previousDurations.find(
(item) => item.spec === relativeSpec,
)
if (!foundInfo) {
return {
specName,
duration: Math.round(averageDuration),
}
} else {
return {
specName,
duration: Math.round(foundInfo.duration),
}
}
})
debug('splitting by duration %d ways', splitN)
debug(specsWithDurations)
const { chunks, sums } = splitByDuration(splitN, specsWithDurations)
debug('split by duration')
debug(chunks)
debug('sums of durations for chunks')
debug(sums)
splitSpecs = chunks[splitIndex].map((item) => item.specName)
console.log(
'%s split %d specs using durations from %s file',
label,
specsWithDurations.length,
SPLIT_FILE,
)
console.log(
'%s approximate total duration for current chunk is %s (plus Cypress overhead)',
label,
humanizeDuration(Math.round(sums[splitIndex])),
)
printSpecsListWithDurations(chunks[splitIndex])
} catch (err) {
console.error('%s Could not split specs by duration', label)
console.error(err.message)
console.error('%s splitting as is by name', label)
splitSpecs = getChunk(specs, splitN, splitIndex)
printSpecsList(splitSpecs)
}
} else {
splitSpecs = getChunk(specs, splitN, splitIndex)
printSpecsList(splitSpecs)
}
debug('split specs')
debug(splitSpecs)
const addSpecResults = () => {
// at this point, the specAbsoluteToRelative object should be filled
const specRows = splitSpecs.map((absoluteSpecPath, k) => {
const relativeName = specAbsoluteToRelative[absoluteSpecPath]
const specRow = [String(k + 1), relativeName || absoluteSpecPath]
const specResult = specResults[absoluteSpecPath]
if (specResult) {
// shorted to relative filename
debug('spec results for %s', relativeName)
debug(specResult.stats)
// the duration field depends on the Cypress version
const specDuration = Math.round(
specResult.stats.duration || specResult.stats.wallClockDuration,
)
const humanSpecDuration = humanizeDuration(specDuration)
debug(
'spec took %d ms, human duration %s',
specDuration,
humanSpecDuration,
)
// have to convert numbers to strings
specRow.push(String(specResult.stats.passes))
specRow.push(String(specResult.stats.failures))
specRow.push(String(specResult.stats.pending))
specRow.push(String(specResult.stats.skipped))
specRow.push(humanSpecDuration)
} else {
console.error('Could not find spec results for %s', absoluteSpecPath)
}
return specRow
})
return specRows
}
on('after:run', () => {
if (SPLIT_FILE) {
console.log('%s here are passing spec timings', label)
const specDurations = splitSpecs
.map((absoluteSpecPath, k) => {
const relativeName = specAbsoluteToRelative[absoluteSpecPath]
const specResult = specResults[absoluteSpecPath]
if (specResult) {
const passsed =
specResult.stats.passes > 0 && specResult.stats.failures === 0
if (passsed) {
const duration = Math.round(
specResult.stats.duration ||
specResult.stats.wallClockDuration,
)
return {
spec: relativeName,
duration,
}
} else {
debug('spec %s has not passed, ignoring timing', relativeName)
return
}
} else {
return
}
})
.filter(Boolean)
const timings = {
durations: specDurations,
}
const timingsString = JSON.stringify(timings, null, 2)
console.log(timingsString)
if (!foundSplitFile) {
console.log('%s writing out timings file %s', label, SPLIT_FILE)
fs.writeFileSync(SPLIT_FILE, timingsString + '\n', 'utf8')
} else {
const splitFile = JSON.parse(fs.readFileSync(foundSplitFile, 'utf8'))
const hasUpdatedTimings = hasTimeDifferences(splitFile, timings, 0.1)
if (hasUpdatedTimings) {
// TODO: merge split file with new timings
// do not forget specs not present in the current run!
const mergedTimings = mergeTimings(splitFile, timings)
const mergedText = JSON.stringify(mergedTimings, null, 2)
console.log(
'%s writing out updated timings file %s',
label,
SPLIT_FILE,
)
debug('previous timings has %d entries', splitFile.durations.length)
debug('current timings has %d entries', timings.durations.length)
debug(
'merged timings has %d entries written to %s',
mergedTimings.durations.length,
foundSplitFile,
)
fs.writeFileSync(foundSplitFile, mergedText + '\n', 'utf8')
} else {
console.log('%s spec timings unchanged', label)
}
}
}
const shouldWriteSummary = getEnvironmentFlag('SPLIT_SUMMARY', true)
debug('shouldWriteSummary', shouldWriteSummary)
if (shouldWriteSummary) {
// only output the GitHub summary table AFTER the run
// because GH does not show the summary before the job finishes
// so we might as well wait for all spec results to come in
if (process.env.GITHUB_ACTIONS) {
const specRows = addSpecResults()
// https://github.blog/2022-05-09-supercharging-github-actions-with-job-summaries/
ghCore.summary
.addHeading(
`${label} chunk ${splitIndex + 1} of ${splitN} (${
splitSpecs.length
} ${splitSpecs.length === 1 ? 'spec' : 'specs'})`,
)
.addTable([
[
{ data: 'K', header: true },
{ data: 'Spec', header: true },
{ data: 'Passed ✅', header: true },
{ data: 'Failed ❌', header: true },
{ data: 'Pending ✋', header: true },
{ data: 'Skipped ↩️', header: true },
{ data: 'Duration 🕗', header: true },
],
...specRows,
])
.addLink(
'bahmutov/cypress-split',
'https://github.com/bahmutov/cypress-split',
)
.write()
}
}
})
if (splitSpecs.length) {
debug('setting the spec pattern to')
debug(splitSpecs)
// if working with Cypress v9, there is integration folder
// @ts-ignore
if (config.integrationFolder) {
debug('setting test files')
// @ts-ignore
config.testFiles = splitSpecs.map((name) =>
// @ts-ignore
path.relative(config.integrationFolder, name),
)
} else {
// Cypress v10+
config.specPattern = splitSpecs
}
} else {
// copy the empty spec file from our source folder into temp folder
const tempFilename = path.join(
os.tmpdir(),
`empty-${splitIndex + 1}-of-${splitN}.cy.js`,
)
const emptyFilename = path.resolve(__dirname, 'empty-spec.cy.js')
fs.copyFileSync(emptyFilename, tempFilename)
console.log(
'%s no specs to run, running an empty spec file %s',
label,
tempFilename,
)
config.specPattern = tempFilename
}
return config
}
}
module.exports = cypressSplit