-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
record.coffee
560 lines (462 loc) · 13.8 KB
/
record.coffee
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
_ = require("lodash")
os = require("os")
la = require("lazy-ass")
chalk = require("chalk")
check = require("check-more-types")
debug = require("debug")("cypress:server:record")
Promise = require("bluebird")
isForkPr = require("is-fork-pr")
commitInfo = require("@cypress/commit-info")
api = require("../api")
logger = require("../logger")
errors = require("../errors")
capture = require("../capture")
upload = require("../upload")
env = require("../util/env")
terminal = require("../util/terminal")
humanTime = require("../util/human_time")
ciProvider = require("../util/ci_provider")
onBeforeRetry = (details) ->
errors.warning(
"DASHBOARD_API_RESPONSE_FAILED_RETRYING", {
delay: humanTime.long(details.delay, false)
tries: details.total - details.retryIndex
response: details.err
}
)
logException = (err) ->
## give us up to 1 second to
## create this exception report
logger.createException(err)
.timeout(1000)
.catch ->
## dont yell about any errors either
runningInternalTests = ->
env.get("CYPRESS_INTERNAL_E2E_TESTS") is "1"
warnIfCiFlag = (ci) ->
## if we are using the ci flag that means
## we have an old version of the CLI tools installed
## and that we need to warn the user what to update
if ci
type = switch
when env.get("CYPRESS_CI_KEY")
"CYPRESS_CI_DEPRECATED_ENV_VAR"
else
"CYPRESS_CI_DEPRECATED"
errors.warning(type)
haveProjectIdAndKeyButNoRecordOption = (projectId, options) ->
## if we have a project id
## and we have a key
## and (record or ci) hasn't been set to true or false
(projectId and options.key) and (
_.isUndefined(options.record) and _.isUndefined(options.ci)
)
warnIfProjectIdButNoRecordOption = (projectId, options) ->
if haveProjectIdAndKeyButNoRecordOption(projectId, options)
## log a warning telling the user
## that they either need to provide us
## with a RECORD_KEY or turn off
## record mode
errors.warning("PROJECT_ID_AND_KEY_BUT_MISSING_RECORD_OPTION", projectId)
throwIfIndeterminateCiBuildId = (ciBuildId, parallel, group) ->
if (not ciBuildId and not ciProvider.provider()) and (parallel or group)
errors.throw(
"INDETERMINATE_CI_BUILD_ID",
{
group,
parallel
},
ciProvider.detectableCiBuildIdProviders()
)
throwIfRecordParamsWithoutRecording = (record, ciBuildId, parallel, group) ->
if not record and _.some([ciBuildId, parallel, group])
errors.throw("RECORD_PARAMS_WITHOUT_RECORDING", {
ciBuildId,
group,
parallel
})
throwIfIncorrectCiBuildIdUsage = (ciBuildId, parallel, group) ->
## we've been given an explicit ciBuildId
## but no parallel or group flag
if ciBuildId and (not parallel and not group)
errors.throw("INCORRECT_CI_BUILD_ID_USAGE", { ciBuildId })
throwIfNoProjectId = (projectId) ->
if not projectId
errors.throw("CANNOT_RECORD_NO_PROJECT_ID")
getSpecRelativePath = (spec) ->
_.get(spec, "relative", null)
uploadArtifacts = (options = {}) ->
{ video, screenshots, videoUploadUrl, shouldUploadVideo, screenshotUploadUrls } = options
uploads = []
count = 0
nums = ->
count += 1
chalk.gray("(#{count}/#{uploads.length})")
send = (pathToFile, url) ->
success = ->
console.log(" - Done Uploading #{nums()}", chalk.blue(pathToFile))
fail = (err) ->
debug("failed to upload artifact %o", {
file: pathToFile
stack: err.stack
})
console.log(" - Failed Uploading #{nums()}", chalk.red(pathToFile))
uploads.push(
upload.send(pathToFile, url)
.then(success)
.catch(fail)
)
if videoUploadUrl and shouldUploadVideo
send(video, videoUploadUrl)
if screenshotUploadUrls
screenshotUploadUrls.forEach (obj) ->
screenshot = _.find(screenshots, { screenshotId: obj.screenshotId })
send(screenshot.path, obj.uploadUrl)
if not uploads.length
console.log(" - Nothing to Upload")
Promise
.all(uploads)
.catch (err) ->
errors.warning("DASHBOARD_CANNOT_UPLOAD_RESULTS", err)
logException(err)
updateInstanceStdout = (options = {}) ->
{ instanceId, captured } = options
stdout = captured.toString()
makeRequest = ->
api.updateInstanceStdout({
stdout
instanceId
})
api.retryWithBackoff(makeRequest, { onBeforeRetry })
.catch (err) ->
debug("failed updating instance stdout %o", {
stack: err.stack
})
errors.warning("DASHBOARD_CANNOT_CREATE_RUN_OR_INSTANCE", err)
## dont log exceptions if we have a 503 status code
logException(err) unless err.statusCode is 503
.finally(capture.restore)
updateInstance = (options = {}) ->
{ instanceId, results, captured, group, parallel, ciBuildId } = options
{ stats, tests, hooks, video, screenshots, reporterStats, error } = results
video = Boolean(video)
cypressConfig = options.config
stdout = captured.toString()
## get rid of the path property
screenshots = _.map screenshots, (screenshot) ->
_.omit(screenshot, "path")
makeRequest = ->
api.updateInstance({
stats
tests
error
video
hooks
stdout
instanceId
screenshots
reporterStats
cypressConfig
})
api.retryWithBackoff(makeRequest, { onBeforeRetry })
.catch (err) ->
debug("failed updating instance %o", {
stack: err.stack
})
if parallel
return errors.throw("DASHBOARD_CANNOT_PROCEED_IN_PARALLEL", {
response: err,
flags: {
group,
ciBuildId,
},
})
errors.warning("DASHBOARD_CANNOT_CREATE_RUN_OR_INSTANCE", err)
## dont log exceptions if we have a 503 status code
if err.statusCode isnt 503
logException(err)
.return(null)
else
null
getCommitFromGitOrCi = (git) ->
la(check.object(git), 'expected git information object', git)
ciProvider.commitDefaults({
sha: git.sha
branch: git.branch
authorName: git.author
authorEmail: git.email
message: git.message
remoteOrigin: git.remote
defaultBranch: null
})
createRun = (options = {}) ->
_.defaults(options, {
group: null,
parallel: null,
ciBuildId: null,
})
{ projectId, recordKey, platform, git, specPattern, specs, parallel, ciBuildId, group } = options
recordKey ?= env.get("CYPRESS_RECORD_KEY") or env.get("CYPRESS_CI_KEY")
if not recordKey
## are we a forked PR and are we NOT running our own internal
## e2e tests? currently some e2e tests fail when a user submits
## a PR because this logic triggers unintended here
if isForkPr.isForkPr() and not runningInternalTests()
## bail with a warning
return errors.warning("RECORDING_FROM_FORK_PR")
## else throw
errors.throw("RECORD_KEY_MISSING")
## go back to being a string
if specPattern
specPattern = specPattern.join(",")
if ciBuildId
## stringify
ciBuildId = String(ciBuildId)
specs = _.map(specs, getSpecRelativePath)
commit = getCommitFromGitOrCi(git)
debug("commit information from Git or from environment variables")
debug(commit)
makeRequest = ->
api.createRun({
specs
group
parallel
platform
ciBuildId
projectId
recordKey
specPattern
ci: {
params: ciProvider.ciParams()
provider: ciProvider.provider()
}
commit
})
api.retryWithBackoff(makeRequest, { onBeforeRetry })
.catch (err) ->
debug("failed creating run %o", {
stack: err.stack
})
switch err.statusCode
when 401
recordKey = recordKey.slice(0, 5) + "..." + recordKey.slice(-5)
errors.throw("DASHBOARD_RECORD_KEY_NOT_VALID", recordKey, projectId)
when 404
errors.throw("DASHBOARD_PROJECT_NOT_FOUND", projectId)
when 412
errors.throw("DASHBOARD_INVALID_RUN_REQUEST", err.error)
when 422
{ code, payload } = err.error
runUrl = _.get(payload, "runUrl")
switch code
when "RUN_GROUP_NAME_NOT_UNIQUE"
errors.throw("DASHBOARD_RUN_GROUP_NAME_NOT_UNIQUE", {
group,
runUrl,
ciBuildId,
})
when "PARALLEL_GROUP_PARAMS_MISMATCH"
{ browserName, browserVersion, osName, osVersion } = platform
errors.throw("DASHBOARD_PARALLEL_GROUP_PARAMS_MISMATCH", {
group,
runUrl,
ciBuildId,
parameters: {
osName,
osVersion,
browserName,
browserVersion,
specs,
}
})
when "PARALLEL_DISALLOWED"
errors.throw("DASHBOARD_PARALLEL_DISALLOWED", {
group,
runUrl,
ciBuildId,
})
when "PARALLEL_REQUIRED"
errors.throw("DASHBOARD_PARALLEL_REQUIRED", {
group,
runUrl,
ciBuildId,
})
when "ALREADY_COMPLETE"
errors.throw("DASHBOARD_ALREADY_COMPLETE", {
runUrl,
group,
parallel,
ciBuildId,
})
when "STALE_RUN"
errors.throw("DASHBOARD_STALE_RUN", {
runUrl,
group,
parallel,
ciBuildId,
})
else
errors.throw("DASHBOARD_UNKNOWN_INVALID_REQUEST", {
response: err,
flags: {
group,
parallel,
ciBuildId,
},
})
else
if parallel
return errors.throw("DASHBOARD_CANNOT_PROCEED_IN_PARALLEL", {
response: err,
flags: {
group,
ciBuildId,
},
})
## warn the user that assets will be not recorded
errors.warning("DASHBOARD_CANNOT_CREATE_RUN_OR_INSTANCE", err)
## report on this exception
## and return null
logException(err)
.return(null)
createInstance = (options = {}) ->
{ runId, group, groupId, parallel, machineId, ciBuildId, platform, spec } = options
spec = getSpecRelativePath(spec)
makeRequest = ->
api.createInstance({
spec
runId
groupId
platform
machineId
})
api.retryWithBackoff(makeRequest, { onBeforeRetry })
.catch (err) ->
debug("failed creating instance %o", {
stack: err.stack
})
if parallel
return errors.throw("DASHBOARD_CANNOT_PROCEED_IN_PARALLEL", {
response: err,
flags: {
group,
ciBuildId,
},
})
errors.warning("DASHBOARD_CANNOT_CREATE_RUN_OR_INSTANCE", err)
## dont log exceptions if we have a 503 status code
if err.statusCode isnt 503
logException(err)
.return(null)
else
null
createRunAndRecordSpecs = (options = {}) ->
{ specPattern, specs, sys, browser, projectId, projectRoot, runAllSpecs, parallel, ciBuildId, group } = options
recordKey = options.key
commitInfo.commitInfo(projectRoot)
.then (git) ->
debug("found the following git information")
debug(git)
platform = {
osCpus: sys.osCpus
osName: sys.osName
osMemory: sys.osMemory
osVersion: sys.osVersion
browserName: browser.displayName
browserVersion: browser.version
}
createRun({
git
specs
group
parallel
platform
recordKey
ciBuildId
projectId
specPattern
})
.then (resp) ->
if not resp
runAllSpecs()
else
{ runUrl, runId, machineId, groupId } = resp
captured = null
instanceId = null
beforeSpecRun = (spec) ->
debug("before spec run %o", { spec })
capture.restore()
captured = capture.stdout()
createInstance({
spec
runId
group
groupId
platform
parallel
ciBuildId
machineId
})
.then (resp = {}) ->
{ instanceId } = resp
## pull off only what we need
return _
.chain(resp)
.pick("spec", "claimedInstances", "totalInstances")
.extend({
estimated: resp.estimatedWallClockDuration
})
.value()
afterSpecRun = (spec, results, config) ->
## dont do anything if we failed to
## create the instance
return if not instanceId
debug("after spec run %o", { spec })
console.log("")
terminal.header("Uploading Results", {
color: ["blue"]
})
console.log("")
updateInstance({
group
config
results
captured
parallel
ciBuildId
instanceId
})
.then (resp) ->
return if not resp
{ video, shouldUploadVideo, screenshots } = results
{ videoUploadUrl, screenshotUploadUrls } = resp
uploadArtifacts({
video
screenshots
videoUploadUrl
shouldUploadVideo
screenshotUploadUrls
})
.finally ->
## always attempt to upload stdout
## even if uploading failed
updateInstanceStdout({
captured
instanceId
})
runAllSpecs(beforeSpecRun, afterSpecRun, runUrl)
module.exports = {
createRun
createInstance
updateInstance
updateInstanceStdout
uploadArtifacts
warnIfCiFlag
throwIfNoProjectId
throwIfIndeterminateCiBuildId
throwIfIncorrectCiBuildIdUsage
warnIfProjectIdButNoRecordOption
throwIfRecordParamsWithoutRecording
createRunAndRecordSpecs
getCommitFromGitOrCi
}