-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
navigation.coffee
844 lines (653 loc) · 23.9 KB
/
navigation.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
_ = require("lodash")
whatIsCircular = require("@cypress/what-is-circular")
moment = require("moment")
UrlParse = require("url-parse")
Promise = require("bluebird")
$utils = require("../../cypress/utils")
$errUtils = require("../../cypress/error_utils")
$Log = require("../../cypress/log")
$Location = require("../../cypress/location")
debug = require('debug')('cypress:driver:navigation')
id = null
previousDomainVisited = null
hasVisitedAboutBlank = null
currentlyVisitingAboutBlank = null
knownCommandCausedInstability = null
REQUEST_URL_OPTS = "auth failOnStatusCode retryOnNetworkFailure retryOnStatusCodeFailure method body headers"
.split(" ")
VISIT_OPTS = "url log onBeforeLoad onLoad timeout requestTimeout"
.split(" ")
.concat(REQUEST_URL_OPTS)
reset = (test = {}) ->
knownCommandCausedInstability = false
## continuously reset this
## before each test run!
previousDomainVisited = false
## make sure we reset that we haven't
## visited about blank again
hasVisitedAboutBlank = false
currentlyVisitingAboutBlank = false
id = test.id
VALID_VISIT_METHODS = ['GET', 'POST']
isValidVisitMethod = (method) ->
_.includes(VALID_VISIT_METHODS, method)
timedOutWaitingForPageLoad = (ms, log) ->
debug('timedOutWaitingForPageLoad')
$errUtils.throwErrByPath("navigation.timed_out", {
args: {
configFile: Cypress.config("configFile")
ms
}
onFail: log
})
bothUrlsMatchAndRemoteHasHash = (current, remote) ->
## the remote has a hash
## or the last char of href
## is a hash
(remote.hash or remote.href.slice(-1) is "#") and
## both must have the same origin
(current.origin is remote.origin) and
## both must have the same pathname
(current.pathname is remote.pathname) and
## both must have the same query params
(current.search is remote.search)
cannotVisitDifferentOrigin = (origin, previousUrlVisited, remoteUrl, existingUrl, log) ->
differences = []
if remoteUrl.protocol isnt existingUrl.protocol
differences.push('protocol')
if remoteUrl.port isnt existingUrl.port
differences.push('port')
if remoteUrl.superDomain isnt existingUrl.superDomain
differences.push('superdomain')
errOpts = {
onFail: log
args: {
differences: differences.join(', ')
previousUrl: previousUrlVisited
attemptedUrl: origin
}
}
$errUtils.throwErrByPath("visit.cannot_visit_different_origin", errOpts)
specifyFileByRelativePath = (url, log) ->
$errUtils.throwErrByPath("visit.specify_file_by_relative_path", {
onFail: log
args: {
attemptedUrl: url
}
})
aboutBlank = (cy, win) ->
new Promise (resolve) ->
cy.once("window:load", resolve)
$utils.locHref("about:blank", win)
navigationChanged = (Cypress, cy, state, source, arg) ->
## get the current url of our remote application
url = cy.getRemoteLocation("href")
debug('navigation changed:', url)
## dont trigger for empty url's or about:blank
return if _.isEmpty(url) or url is "about:blank"
## start storing the history entries
urls = state("urls") ? []
previousUrl = _.last(urls)
## ensure our new url doesnt match whatever
## the previous was. this prevents logging
## additionally when the url didnt actually change
return if url is previousUrl
## else notify the world and log this event
Cypress.action("cy:url:changed", url)
urls.push(url)
state("urls", urls)
state("url", url)
## don't output a command log for 'load' or 'before:load' events
# return if source in command
return if knownCommandCausedInstability
## ensure our new url doesnt match whatever
## the previous was. this prevents logging
## additionally when the url didnt actually change
Cypress.log({
name: "new url"
message: url
event: true
type: "parent"
end: true
snapshot: true
consoleProps: ->
obj = {
"New Url": url
}
if source
obj["Url Updated By"] = source
if arg
obj.Args = arg
return obj
})
formSubmitted = (Cypress, e) ->
Cypress.log({
type: "parent"
name: "form sub"
message: "--submitting form--"
event: true
end: true
snapshot: true
consoleProps: -> {
"Originated From": e.target
"Args": e
}
})
pageLoading = (bool, Cypress, state) ->
return if state("pageLoading") is bool
state("pageLoading", bool)
Cypress.action("app:page:loading", bool)
stabilityChanged = (Cypress, state, config, stable, event) ->
debug('stabilityChanged:', stable)
if currentlyVisitingAboutBlank
if stable is false
## if we're currently visiting about blank
## and becoming unstable for the first time
## notifiy that we're page loading
pageLoading(true, Cypress, state)
return
else
## else wait until after we finish visiting
## about blank
return
## let the world know that the app is page:loading
pageLoading(!stable, Cypress, state)
## if we aren't becoming unstable
## then just return now
return if stable isnt false
## if we purposefully just caused the page to load
## (and thus instability) don't log this out
return if knownCommandCausedInstability
## bail if we dont have a runnable
## because beforeunload can happen at any time
## we may no longer be testing and thus dont
## want to fire a new loading event
## TODO
## this may change in the future since we want
## to add debuggability in the chrome console
## which at that point we may keep runnable around
return if not state("runnable")
options = {}
_.defaults(options, {
timeout: config("pageLoadTimeout")
})
options._log = Cypress.log({
type: "parent"
name: "page load"
message: "--waiting for new page to load--"
event: true
consoleProps: -> {
Note: "This event initially fires when your application fires its 'beforeunload' event and completes when your application fires its 'load' event after the next page loads."
}
})
cy.clearTimeout("page load")
onPageLoadErr = (err) ->
state("onPageLoadErr", null)
{ originPolicy } = $Location.create(window.location.href)
try
$errUtils.throwErrByPath("navigation.cross_origin", {
onFail: options._log
args: {
configFile: Cypress.config("configFile")
message: err.message
originPolicy: originPolicy
}
})
catch err
return err
state("onPageLoadErr", onPageLoadErr)
loading = ->
debug('waiting for window:load')
new Promise (resolve, reject) ->
cy.once "window:load", ->
cy.state("onPageLoadErr", null)
options._log.set("message", "--page loaded--").snapshot().end()
resolve()
reject = (err) ->
if r = state("reject")
r(err)
loading()
.timeout(options.timeout, "page load")
.catch Promise.TimeoutError, ->
## clean this up
cy.state("onPageLoadErr", null)
try
timedOutWaitingForPageLoad(options.timeout, options._log)
catch err
reject(err)
normalizeTimeoutOptions = (options) ->
## there are really two timeout values - pageLoadTimeout
## and the underlying responseTimeout. for the purposes
## of resolving resolving the url, we only care about
## responseTimeout - since pageLoadTimeout is a driver
## and browser concern. therefore we normalize the options
## object and send 'responseTimeout' as options.timeout
## for the backend.
_
.chain(options)
.pick(REQUEST_URL_OPTS)
.extend({ timeout: options.responseTimeout })
.value()
module.exports = (Commands, Cypress, cy, state, config) ->
reset()
Cypress.on("test:before:run", reset)
Cypress.on "stability:changed", (bool, event) ->
## only send up page loading events when we're
## not stable!
stabilityChanged(Cypress, state, config, bool, event)
Cypress.on "navigation:changed", (source, arg) ->
navigationChanged(Cypress, cy, state, source, arg)
Cypress.on "form:submitted", (e) ->
formSubmitted(Cypress, e)
visitFailedByErr = (err, url, fn) ->
err.url = url
Cypress.action("cy:visit:failed", err)
fn()
requestUrl = (url, options = {}) ->
Cypress.backend(
"resolve:url",
url,
normalizeTimeoutOptions(options)
)
.then (resp = {}) ->
switch
## if we didn't even get an OK response
## then immediately die
when not resp.isOkStatusCode
err = new Error
err.gotResponse = true
_.extend(err, resp)
throw err
when not resp.isHtml
## throw invalid contentType error
err = new Error
err.invalidContentType = true
_.extend(err, resp)
throw err
else
resp
Cypress.on "window:before:load", (contentWindow) ->
## TODO: just use a closure here
current = state("current")
return if not current
runnable = state("runnable")
return if not runnable
options = _.last(current.get("args"))
options?.onBeforeLoad?.call(runnable.ctx, contentWindow)
Commands.addAll({
reload: (args...) ->
throwArgsErr = =>
$errUtils.throwErrByPath("reload.invalid_arguments")
switch args.length
when 0
forceReload = false
options = {}
when 1
if _.isObject(args[0])
options = args[0]
else
forceReload = args[0]
when 2
forceReload = args[0]
options = args[1]
else
throwArgsErr()
## clear the current timeout
cy.clearTimeout("reload")
cleanup = null
reload = ->
new Promise (resolve, reject) ->
forceReload ?= false
options ?= {}
_.defaults options, {
log: true
timeout: config("pageLoadTimeout")
}
if not _.isBoolean(forceReload)
throwArgsErr()
if not _.isObject(options)
throwArgsErr()
if options.log
options._log = Cypress.log()
options._log.snapshot("before", {next: "after"})
cleanup = ->
knownCommandCausedInstability = false
cy.removeListener("window:load", resolve)
knownCommandCausedInstability = true
cy.once("window:load", resolve)
$utils.locReload(forceReload, state("window"))
reload()
.timeout(options.timeout, "reload")
.catch Promise.TimeoutError, (err) ->
timedOutWaitingForPageLoad(options.timeout, options._log)
.finally ->
cleanup?()
return null
go: (numberOrString, options = {}) ->
_.defaults options, {
log: true
timeout: config("pageLoadTimeout")
}
if options.log
options._log = Cypress.log()
win = state("window")
goNumber = (num) ->
if num is 0
$errUtils.throwErrByPath("go.invalid_number", { onFail: options._log })
cleanup = null
if options._log
options._log.snapshot("before", {next: "after"})
go = ->
Promise.try ->
didUnload = false
beforeUnload = ->
didUnload = true
## clear the current timeout
cy.clearTimeout()
cy.once("window:before:unload", beforeUnload)
didLoad = new Promise (resolve) ->
cleanup = ->
cy.removeListener("window:load", resolve)
cy.removeListener("window:before:unload", beforeUnload)
cy.once("window:load", resolve)
knownCommandCausedInstability = true
win.history.go(num)
retWin = ->
## need to set the attributes of 'go'
## consoleProps here with win
## make sure we resolve our go function
## with the remove window (just like cy.visit)
state("window")
Promise
.delay(100)
.then ->
knownCommandCausedInstability = false
## if we've didUnload then we know we're
## doing a full page refresh and we need
## to wait until
if didUnload
didLoad.then(retWin)
else
retWin()
go()
.timeout(options.timeout, "go")
.catch Promise.TimeoutError, (err) ->
timedOutWaitingForPageLoad(options.timeout, options._log)
.finally ->
cleanup?()
return null
goString = (str) ->
switch str
when "forward" then goNumber(1)
when "back" then goNumber(-1)
else
$errUtils.throwErrByPath("go.invalid_direction", {
onFail: options._log
args: { str }
})
switch
when _.isFinite(numberOrString) then goNumber(numberOrString)
when _.isString(numberOrString) then goString(numberOrString)
else
$errUtils.throwErrByPath("go.invalid_argument", { onFail: options._log })
visit: (url, options = {}) ->
if options.url and url
$errUtils.throwErrByPath("visit.no_duplicate_url", { args: { optionsUrl: options.url, url: url }})
if _.isObject(url) and _.isEqual(options, {})
## options specified as only argument
options = url
url = options.url
if not _.isString(url)
$errUtils.throwErrByPath("visit.invalid_1st_arg")
consoleProps = {}
if not _.isEmpty(options)
consoleProps["Options"] = _.pick(options, VISIT_OPTS)
_.defaults(options, {
auth: null
failOnStatusCode: true
retryOnNetworkFailure: true
retryOnStatusCodeFailure: false
method: 'GET'
body: null
headers: {}
log: true
responseTimeout: config('responseTimeout')
timeout: config("pageLoadTimeout")
onBeforeLoad: ->
onLoad: ->
})
if !_.isUndefined(options.qs) and not _.isObject(options.qs)
$errUtils.throwErrByPath("visit.invalid_qs", { args: { qs: String(options.qs) }})
if options.retryOnStatusCodeFailure and not options.failOnStatusCode
$errUtils.throwErrByPath("visit.status_code_flags_invalid")
if not isValidVisitMethod(options.method)
$errUtils.throwErrByPath("visit.invalid_method", { args: { method: options.method }})
if not _.isObject(options.headers)
$errUtils.throwErrByPath("visit.invalid_headers")
if _.isObject(options.body) and path = whatIsCircular(options.body)
$errUtils.throwErrByPath("visit.body_circular", { args: { path }})
if options.log
message = url
if options.method != 'GET'
message = "#{options.method} #{message}"
options._log = Cypress.log({
message: message
consoleProps: -> consoleProps
})
url = $Location.normalize(url)
if baseUrl = config("baseUrl")
url = $Location.qualifyWithBaseUrl(baseUrl, url)
if qs = options.qs
url = $Location.mergeUrlWithParams(url, qs)
cleanup = null
## clear the current timeout
cy.clearTimeout("visit")
win = state("window")
$autIframe = state("$autIframe")
runnable = state("runnable")
changeIframeSrc = (url, event) ->
## when the remote iframe's load event fires
## callback fn
new Promise (resolve) ->
## if we're listening for hashchange
## events then change the strategy
## to listen to this event emitting
## from the window and not cy
## see issue 652 for why.
## the hashchange events are firing too
## fast for us. They even resolve asynchronously
## before other application's hashchange events
## have even fired.
if event is "hashchange"
win.addEventListener("hashchange", resolve)
else
cy.once(event, resolve)
cleanup = ->
if event is "hashchange"
win.removeEventListener("hashchange", resolve)
else
cy.removeListener(event, resolve)
knownCommandCausedInstability = false
knownCommandCausedInstability = true
$utils.iframeSrc($autIframe, url)
onLoad = ({runOnLoadCallback, totalTime}) ->
## reset window on load
win = state("window")
## the onLoad callback should only be skipped if specified
if runOnLoadCallback isnt false
options.onLoad?.call(runnable.ctx, win)
if options._log
options._log.set({
url
totalTime
})
return Promise.resolve(win)
go = ->
## hold onto our existing url
existing = $utils.locExisting()
## TODO: $Location.resolve(existing.origin, url)
if $Location.isLocalFileUrl(url)
return specifyFileByRelativePath(url, options._log)
## in the case we are visiting a relative url
## then prepend the existing origin to it
## so we get the right remote url
if not $Location.isFullyQualifiedUrl(url)
remoteUrl = $Location.fullyQualifyUrl(url)
remote = $Location.create(remoteUrl ? url)
## reset auth options if we have them
if a = remote.authObj
options.auth = a
## store the existing hash now since
## we'll need to apply it later
existingHash = remote.hash ? ""
existingAuth = remote.auth ? ""
if previousDomainVisited and remote.originPolicy isnt existing.originPolicy
## if we've already visited a new superDomain
## then die else we'd be in a terrible endless loop
return cannotVisitDifferentOrigin(remote.origin, previousDomainVisited, remote, existing, options._log)
current = $Location.create(win.location.href)
## if all that is changing is the hash then we know
## the browser won't actually make a new http request
## for this, and so we need to resolve onLoad immediately
## and bypass the actual visit resolution stuff
if bothUrlsMatchAndRemoteHasHash(current, remote)
## https://github.com/cypress-io/cypress/issues/1311
if current.hash is remote.hash
consoleProps["Note"] = "Because this visit was to the same hash, the page did not reload and the onBeforeLoad and onLoad callbacks did not fire."
return onLoad({runOnLoadCallback: false})
return changeIframeSrc(remote.href, "hashchange")
.then(onLoad)
if existingHash
## strip out the existing hash if we have one
## before telling our backend to resolve this url
url = url.replace(existingHash, "")
if existingAuth
## strip out the existing url if we have one
url = url.replace(existingAuth + "@", "")
requestUrl(url, options)
.then (resp = {}) =>
{url, originalUrl, cookies, redirects, filePath} = resp
## reapply the existing hash
url += existingHash
originalUrl += existingHash
if filePath
consoleProps["File Served"] = filePath
else
if url isnt originalUrl
consoleProps["Original Url"] = originalUrl
if options.log
message = options._log.get('message')
if redirects and redirects.length
message = [message].concat(redirects).join(" -> ")
options._log.set({message: message})
consoleProps["Resolved Url"] = url
consoleProps["Redirects"] = redirects
consoleProps["Cookies Set"] = cookies
remote = $Location.create(url)
## if the origin currently matches
## then go ahead and change the iframe's src
## and we're good to go
# if origin is existing.origin
if remote.originPolicy is existing.originPolicy
previousDomainVisited = remote.origin
url = $Location.fullyQualifyUrl(url)
changeIframeSrc(url, "window:load")
.then ->
onLoad(resp)
else
## if we've already visited a new origin
## then die else we'd be in a terrible endless loop
if previousDomainVisited
return cannotVisitDifferentOrigin(remote.origin, previousDomainVisited, remote, existing, options._log)
## tell our backend we're changing domains
## TODO: add in other things we want to preserve
## state for like scrollTop
s = {
currentId: id
tests: Cypress.getTestsState()
startTime: Cypress.getStartTime()
emissions: Cypress.getEmissions()
}
s.passed = Cypress.countByTestState(s.tests, "passed")
s.failed = Cypress.countByTestState(s.tests, "failed")
s.pending = Cypress.countByTestState(s.tests, "pending")
s.numLogs = $Log.countLogsByTests(s.tests)
Cypress.action("cy:collect:run:state")
.then (a = []) ->
## merge all the states together holla'
s = _.reduce a, (memo, obj) ->
_.extend(memo, obj)
, s
Cypress.backend("preserve:run:state", s)
.then ->
## and now we must change the url to be the new
## origin but include the test that we're currently on
newUri = new UrlParse(remote.origin)
newUri
.set("pathname", existing.pathname)
.set("query", existing.search)
.set("hash", existing.hash)
## replace is broken in electron so switching
## to href for now
# $utils.locReplace(window, newUri.toString())
$utils.locHref(newUri.toString(), window)
## we are returning a Promise which never resolves
## because we're changing top to be a brand new URL
## and want to block the rest of our commands
return Promise.delay(1e9)
.catch (err) ->
switch
when err.gotResponse, err.invalidContentType
visitFailedByErr err, err.originalUrl, ->
args = {
url: err.originalUrl
path: err.filePath
status: err.status
statusText: err.statusText
redirects: err.redirects
contentType: err.contentType
}
msg = switch
when err.gotResponse
type = if err.filePath then "file" else "http"
"visit.loading_#{type}_failed"
when err.invalidContentType
"visit.loading_invalid_content_type"
$errUtils.throwErrByPath(msg, {
onFail: options._log
args: args
})
else
visitFailedByErr err, url, ->
$errUtils.throwErrByPath("visit.loading_network_failed", {
onFail: options._log
args: {
url: url
error: err
stack: err.stack
}
noStackTrace: true
})
visit = ->
## if we've visiting for the first time during
## a test then we want to first visit about:blank
## so that we nuke the previous state. subsequent
## visits will not navigate to about:blank so that
## our history entries are intact
if not hasVisitedAboutBlank
hasVisitedAboutBlank = true
currentlyVisitingAboutBlank = true
aboutBlank(cy, win)
.then ->
currentlyVisitingAboutBlank = false
go()
else
go()
visit()
.timeout(options.timeout, "visit")
.catch Promise.TimeoutError, (err) =>
timedOutWaitingForPageLoad(options.timeout, options._log)
.finally ->
cleanup?()
return null
})