1313import os
1414import signal
1515import sys
16+ from urllib .parse import urldefrag , urlsplit , urlunsplit
1617
1718import pytest
1819
@@ -610,12 +611,24 @@ class Navigating(StubDevTools):
610611 """A browser whose first tab is ``start`` and whose new tabs are t1, t2, …, each attached as it opens, answering a
611612 navigation as ``pages`` says by URL: a status and the URL it ends on, then committed and, unless ``no-load``
612613 follows, loaded, or with ``("redirect", status, url)`` following, sending itself there by script before it loads;
613- ``refused``, a network error; ``silent``, never answered, as a page that never answers isn't; or ``stale``, a load
614- event with no commit."""
614+ ``refused``, a network error; ``aborted``, a document request that fails before it commits; ``silent``, never
615+ answered, as a page that never answers isn't; or ``stale``, a load event with no commit. A navigation that stays in
616+ a tab's document, to a URL with a fragment that differs from where it is (``at``) in its fragment alone, as a
617+ browser spells both (``_document``), moves within it and names no loader, as a browser's does; a reload loads where
618+ the tab is as a navigation there would, naming no loader either."""
615619
616- def __init__ (self , pages ):
620+ #: How long after the browser answers them a move within a document lands, and a reload starts loading.
621+ MOVE_LANDS_S , RELOAD_LOADS_S = 0.05 , 0.01
622+
623+ def __init__ (self , pages , reload_answers = True ):
617624 super ().__init__ ({"Target.getTargets" : {"targetInfos" : []}})
618- self .pages , self .opened , self .loaders = pages , 0 , 0
625+ self .pages , self .opened , self .loaders , self .urls , self .pending = pages , 0 , 0 , {}, []
626+ self .reload_answers = reload_answers
627+
628+ def at (self , target , url ):
629+ """The tab ``target`` at ``url``, as the browser tells the control."""
630+ self .urls [target ] = url
631+ self .send ("Target.targetInfoChanged" , _page (target , url ))
619632
620633 async def call (self , method , params = None , * , session_id = None , timeout_s = None ):
621634 if method == "Target.createTarget" :
@@ -626,12 +639,42 @@ async def call(self, method, params=None, *, session_id=None, timeout_s=None):
626639 self .send ("Target.attachedToTarget" , {"sessionId" : f"s-{ target } " , "waitingForDebugger" : True ,
627640 ** _page (target )})
628641 return {"targetId" : target }
642+ if method == "Page.reload" :
643+ self .calls .append ((method , params , session_id ))
644+ if not self .reload_answers :
645+ await asyncio .Event ().wait ()
646+ self .pending .append (asyncio .ensure_future (self ._reload (self .urls [session_id [2 :]], session_id )))
647+ return {}
629648 if method != "Page.navigate" :
630649 return await super ().call (method , params , session_id = session_id , timeout_s = timeout_s )
631650 self .calls .append ((method , params , session_id ))
632- page , target = self .pages [params ["url" ]], session_id [2 :]
651+ url , target = params ["url" ], session_id [2 :]
652+ if "#" in url and _document (url ) == _document (self .urls .get (target , "" )):
653+ self .pending .append (asyncio .ensure_future (self ._move_within (target , url , session_id )))
654+ return {"frameId" : target }
655+ return await self ._load (url , session_id )
656+
657+ async def _move_within (self , target , url , session_id ):
658+ """A move within a tab's document, which the browser answers before it lands."""
659+ await asyncio .sleep (self .MOVE_LANDS_S )
660+ self .send ("Page.navigatedWithinDocument" , {"frameId" : target , "url" : url }, session_id )
661+ self .at (target , url )
662+
663+ async def _reload (self , url , session_id ):
664+ """A reload, which the browser answers before it commits."""
665+ await asyncio .sleep (self .RELOAD_LOADS_S )
666+ await self ._load (url , session_id )
667+
668+ async def _load (self , url , session_id ):
669+ page , target = self .pages [url ], session_id [2 :]
670+ self .urls [target ] = url
633671 self .loaders += 1
634672 loader , request = f"L{ self .loaders } " , f"r{ self .loaders } "
673+ if page == "aborted" :
674+ document = {"requestId" : request , "loaderId" : loader , "type" : "Document" , "frameId" : target }
675+ self .send ("Network.requestWillBeSent" , document , session_id )
676+ self .send ("Network.loadingFailed" , {"requestId" : request , "errorText" : "net::ERR_ABORTED" }, session_id )
677+ return {"frameId" : target , "loaderId" : loader , "errorText" : "net::ERR_ABORTED" }
635678 if page == "refused" :
636679 return {"frameId" : target , "loaderId" : loader , "errorText" : "net::ERR_CONNECTION_REFUSED" }
637680 if page == "silent" :
@@ -655,6 +698,12 @@ def _document(self, session, target, loader, request, status, url):
655698 self .send ("Page.frameNavigated" , {"frame" : {"id" : target , "loaderId" : loader , "url" : url }}, session )
656699
657700
701+ def _document (url ):
702+ """The document ``url`` names, as a browser spells it: without its fragment, an empty path as "/"."""
703+ parts = urlsplit (urldefrag (url )[0 ])
704+ return urlunsplit (parts ._replace (path = parts .path or "/" ))
705+
706+
658707async def _started (devtools , viewport = (1280 , 800 )) -> BrowserControl :
659708 """A control following a browser just launched, on its first tab, ``start``."""
660709 control = BrowserControl (devtools , "agent" , viewport )
@@ -736,6 +785,66 @@ async def test_a_start_page_that_sends_itself_elsewhere_before_it_loads_is_judge
736785 assert (tab ["final_url" ], tab ["status" ], tab ["outcome" ]) == (final , status , outcome )
737786
738787
788+ @pytest .mark .asyncio
789+ @pytest .mark .parametrize ("at, url" , [("https://shop.test/#/orders" , "https://shop.test/#/orders" ),
790+ ("https://shop.test/#/cart" , "https://shop.test/#/orders" ),
791+ ("https://shop.test/#/orders" , "https://shop.test#/orders" )],
792+ ids = ["at-its-url" , "at-another-route-of-its-page" , "at-its-url-spelled-otherwise" ])
793+ async def test_a_start_tab_already_on_its_pages_document_is_reloaded_there_and_loads_again (at , url ):
794+ devtools = Navigating ({url : (200 , url )})
795+ control = await _started (devtools )
796+ devtools .at ("start" , at )
797+
798+ (tab ,) = await control .load_start_tabs ([url ], _shop , own_timeout_s = 2 )
799+
800+ assert (tab ["outcome" ], tab ["status" ], tab ["final_url" ], tab ["error" ]) == ("loaded" , 200 , url , None )
801+ assert [(method , params ) for method , params , on in devtools .calls if on == "s-start" and method in (
802+ "Page.navigate" , "Page.reload" )] == [("Page.navigate" , {"url" : url }), ("Page.reload" , {})]
803+ assert not control ._loading
804+
805+
806+ @pytest .mark .asyncio
807+ async def test_a_start_tab_whose_reload_fails_before_it_commits_fails_at_once_naming_why ():
808+ url = "https://shop.test/#/orders"
809+ devtools = Navigating ({url : "aborted" })
810+ control = await _started (devtools )
811+ devtools .at ("start" , url )
812+ loop = asyncio .get_running_loop ()
813+ started = loop .time ()
814+
815+ (tab ,) = await control .load_start_tabs ([url ], _shop , own_timeout_s = 2 )
816+
817+ assert (tab ["outcome" ], tab ["error" ]) == ("failed" , "net::ERR_ABORTED" )
818+ assert loop .time () - started < 1
819+
820+
821+ @pytest .mark .asyncio
822+ async def test_a_start_tab_whose_reload_never_answers_times_out_and_leaves_no_cause_for_a_later_navigation ():
823+ url = "https://shop.test/#/orders"
824+ devtools = Navigating ({url : (200 , url )}, reload_answers = False )
825+ control = await _started (devtools )
826+ devtools .at ("start" , url )
827+
828+ (tab ,) = await control .load_start_tabs ([url ], _shop , own_timeout_s = 0.5 )
829+ await asyncio .sleep (0 )
830+
831+ assert tab ["outcome" ] == "timed_out"
832+ assert "start" not in control .causes ._next
833+
834+
835+ @pytest .mark .asyncio
836+ async def test_a_start_tab_on_another_page_of_its_site_navigates_and_isnt_reloaded ():
837+ url = "https://shop.test/#/orders"
838+ devtools = Navigating ({url : (200 , url )})
839+ control = await _started (devtools )
840+ devtools .at ("start" , "https://shop.test/account" )
841+
842+ (tab ,) = await control .load_start_tabs ([url ], _shop , own_timeout_s = 2 )
843+
844+ assert (tab ["outcome" ], tab ["final_url" ]) == ("loaded" , url )
845+ assert (_sent (devtools , "Page.navigate" ), _sent (devtools , "Page.reload" )) == ([({"url" : url }, "s-start" )], [])
846+
847+
739848@pytest .mark .asyncio
740849async def test_a_start_tab_still_loading_when_the_browser_ends_fails_naming_that_and_is_kept_with_its_pipe_gone ():
741850 def gone (params , session ):
0 commit comments