Skip to content

Commit 6e1a593

Browse files
authored
test: add test_navigation.py (part 1) (#82)
1 parent 1d4b718 commit 6e1a593

20 files changed

+646
-146
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,12 +128,12 @@ async def run():
128128
browser = await chromium.launch()
129129
page = await browser.newPage()
130130

131-
async def log_and_continue_request(route, request):
131+
def log_and_continue_request(route, request):
132132
print(request.url)
133-
await route.continue_()
133+
await asyncio.create_task(route.continue_())
134134

135135
# Log and continue all network requests
136-
await page.route('**', lambda route, request: asyncio.ensure_future(log_and_continue_request(route, request)))
136+
await page.route('**', lambda route, request: log_and_continue_request(route, request))
137137

138138
await page.goto('http://todomvc.com')
139139
await browser.close()

playwright/browser_context.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -76,27 +76,23 @@ def _on_route(self, route: Route, request: Request) -> None:
7676
if handler_entry.matcher.matches(request.url):
7777
handler_entry.handler(route, request)
7878
return
79-
asyncio.ensure_future(route.continue_())
79+
asyncio.create_task(route.continue_())
8080

8181
def _on_binding(self, binding_call: BindingCall) -> None:
8282
func = self._bindings.get(binding_call._initializer["name"])
8383
if func is None:
8484
return
85-
asyncio.ensure_future(binding_call.call(func))
85+
asyncio.create_task(binding_call.call(func))
8686

8787
def setDefaultNavigationTimeout(self, timeout: int) -> None:
8888
self._timeout_settings.set_navigation_timeout(timeout)
89-
asyncio.ensure_future(
90-
self._channel.send(
91-
"setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)
92-
)
89+
self._channel.send_no_reply(
90+
"setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)
9391
)
9492

9593
def setDefaultTimeout(self, timeout: int) -> None:
9694
self._timeout_settings.set_timeout(timeout)
97-
asyncio.ensure_future(
98-
self._channel.send("setDefaultTimeoutNoReply", dict(timeout=timeout))
99-
)
95+
self._channel.send_no_reply("setDefaultTimeoutNoReply", dict(timeout=timeout))
10096

10197
@property
10298
def pages(self) -> List[Page]:

playwright/connection.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ async def send(self, method: str, params: dict = None) -> Any:
4141
return result[key]
4242
return result
4343

44+
def send_no_reply(self, method: str, params: dict = None) -> None:
45+
if params is None:
46+
params = dict()
47+
self._scope.send_message_to_server_no_reply(self._guid, method, params)
48+
4449

4550
class ChannelOwner(BaseEventEmitter):
4651
def __init__(
@@ -95,7 +100,13 @@ def dispose(self) -> None:
95100
self._parent._children.remove(self)
96101

97102
async def send_message_to_server(self, guid: str, method: str, params: Dict) -> Any:
98-
return await self._connection._send_message_to_server(guid, method, params)
103+
callback = self._connection._send_message_to_server(guid, method, params)
104+
return await callback.future
105+
106+
def send_message_to_server_no_reply(
107+
self, guid: str, method: str, params: Dict
108+
) -> Any:
109+
self._connection._send_message_to_server(guid, method, params)
99110

100111
def create_remote_object(self, type: str, guid: str, initializer: Dict) -> Any:
101112
result: ChannelOwner
@@ -140,9 +151,9 @@ async def wait_for_object_with_known_name(self, guid: str) -> Any:
140151
self._waiting_for_object[guid] = callback
141152
return await callback
142153

143-
async def _send_message_to_server(
154+
def _send_message_to_server(
144155
self, guid: str, method: str, params: Dict
145-
) -> Any:
156+
) -> ProtocolCallback:
146157
self._last_id += 1
147158
id = self._last_id
148159
message = dict(
@@ -154,7 +165,7 @@ async def _send_message_to_server(
154165
self._transport.send(message)
155166
callback = ProtocolCallback(self._loop)
156167
self._callbacks[id] = callback
157-
return await callback.future
168+
return callback
158169

159170
def _dispatch(self, msg: ParsedMessagePayload) -> None:
160171

playwright/page.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def _on_route(self, route: Route, request: Request) -> None:
225225
def _on_binding(self, binding_call: "BindingCall") -> None:
226226
func = self._bindings.get(binding_call._initializer["name"])
227227
if func:
228-
asyncio.ensure_future(binding_call.call(func))
228+
asyncio.create_task(binding_call.call(func))
229229
self._browser_context._on_binding(binding_call)
230230

231231
def _on_worker(self, worker: Worker) -> None:
@@ -273,17 +273,13 @@ def frames(self) -> List[Frame]:
273273

274274
def setDefaultNavigationTimeout(self, timeout: int) -> None:
275275
self._timeout_settings.set_navigation_timeout(timeout)
276-
asyncio.ensure_future(
277-
self._channel.send(
278-
"setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)
279-
)
276+
self._channel.send_no_reply(
277+
"setDefaultNavigationTimeoutNoReply", dict(timeout=timeout)
280278
)
281279

282280
def setDefaultTimeout(self, timeout: int) -> None:
283281
self._timeout_settings.set_timeout(timeout)
284-
asyncio.ensure_future(
285-
self._channel.send("setDefaultTimeoutNoReply", dict(timeout=timeout))
286-
)
282+
self._channel.send_no_reply("setDefaultTimeoutNoReply", dict(timeout=timeout))
287283

288284
async def querySelector(self, selector: str) -> Optional[ElementHandle]:
289285
return await self._main_frame.querySelector(selector)
@@ -723,6 +719,6 @@ async def call(self, func: FunctionWithSource) -> None:
723719
await self._channel.send("resolve", dict(result=serialize_argument(result)))
724720
except Exception as e:
725721
tb = sys.exc_info()[2]
726-
asyncio.ensure_future(
722+
asyncio.create_task(
727723
self._channel.send("reject", dict(error=serialize_error(e, tb)))
728724
)

playwright/sync_base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ def __init__(
3434
wait_helper.reject_on_timeout(
3535
timeout or 30000, f'Timeout while waiting for event "${event}"'
3636
)
37-
self._future = asyncio.ensure_future(
37+
self._future = asyncio.create_task(
3838
wait_helper.wait_for_event(sync_base._async_obj, event, predicate)
3939
)
4040

playwright/wait_helper.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,15 +37,15 @@ def reject_on_timeout(self, timeout: int, message: str) -> None:
3737
if timeout == 0:
3838
return
3939
self.reject_on(
40-
asyncio.ensure_future(asyncio.sleep(timeout / 1000)), TimeoutError(message)
40+
asyncio.create_task(asyncio.sleep(timeout / 1000)), TimeoutError(message)
4141
)
4242

4343
def reject_on(self, future: asyncio.Future, error: Error) -> None:
4444
async def future_wrapper() -> Error:
4545
await future
4646
return error
4747

48-
result = asyncio.ensure_future(future_wrapper())
48+
result = asyncio.create_task(future_wrapper())
4949
result.add_done_callback(lambda f: future.cancel())
5050
self._failures.append(result)
5151

tests/assets/historyapi.html

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script>
2+
window.addEventListener('DOMContentLoaded', () => {
3+
history.pushState({}, '', '#1');
4+
});
5+
</script>

tests/assets/self-request.html

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
<script>
2+
var req = new XMLHttpRequest();
3+
req.open('GET', '/self-request.html');
4+
req.send(null);
5+
</script>

tests/test_browsercontext.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ async def test_close_should_work_for_empty_context(browser):
136136

137137
async def test_close_should_abort_wait_for_event(browser):
138138
context = await browser.newContext()
139-
promise = asyncio.ensure_future(context.waitForEvent("page"))
139+
promise = asyncio.create_task(context.waitForEvent("page"))
140140
await context.close()
141141
with pytest.raises(Error) as exc_info:
142142
await promise
@@ -425,7 +425,7 @@ def handle(route, request):
425425
assert request.resourceType == "document"
426426
assert request.frame == page.mainFrame
427427
assert request.frame.url == "about:blank"
428-
asyncio.ensure_future(route.continue_())
428+
asyncio.create_task(route.continue_())
429429

430430
await context.route("**/empty.html", lambda route, request: handle(route, request))
431431
page = await context.newPage()
@@ -442,7 +442,7 @@ async def test_route_should_unroute(context, server):
442442

443443
def handler(route, request, ordinal):
444444
intercepted.append(ordinal)
445-
asyncio.ensure_future(route.continue_())
445+
asyncio.create_task(route.continue_())
446446

447447
def handler1(route, request):
448448
handler(route, request, 1)
@@ -473,15 +473,15 @@ def handler1(route, request):
473473
async def test_route_should_yield_to_page_route(context, server):
474474
await context.route(
475475
"**/empty.html",
476-
lambda route, request: asyncio.ensure_future(
476+
lambda route, request: asyncio.create_task(
477477
route.fulfill(status=200, body="context")
478478
),
479479
)
480480

481481
page = await context.newPage()
482482
await page.route(
483483
"**/empty.html",
484-
lambda route, request: asyncio.ensure_future(
484+
lambda route, request: asyncio.create_task(
485485
route.fulfill(status=200, body="page")
486486
),
487487
)
@@ -494,15 +494,15 @@ async def test_route_should_yield_to_page_route(context, server):
494494
async def test_route_should_fall_back_to_context_route(context, server):
495495
await context.route(
496496
"**/empty.html",
497-
lambda route, request: asyncio.ensure_future(
497+
lambda route, request: asyncio.create_task(
498498
route.fulfill(status=200, body="context")
499499
),
500500
)
501501

502502
page = await context.newPage()
503503
await page.route(
504504
"**/non-empty.html",
505-
lambda route, request: asyncio.ensure_future(
505+
lambda route, request: asyncio.create_task(
506506
route.fulfill(status=200, body="page")
507507
),
508508
)
@@ -647,16 +647,16 @@ async def test_page_event_should_report_when_a_new_page_is_created_and_closed(
647647

648648

649649
async def test_page_event_should_report_initialized_pages(context, server):
650-
page_promise = asyncio.ensure_future(context.waitForEvent("page"))
651-
asyncio.ensure_future(context.newPage())
652-
newPage = await page_promise
650+
page_event_promise = asyncio.create_task(context.waitForEvent("page"))
651+
asyncio.create_task(context.newPage())
652+
newPage = await page_event_promise
653653
assert newPage.url == "about:blank"
654654

655-
popup_promise = asyncio.ensure_future(context.waitForEvent("page"))
656-
evaluate_promise = asyncio.ensure_future(
655+
popup_event_promise = asyncio.create_task(context.waitForEvent("page"))
656+
evaluate_promise = asyncio.create_task(
657657
newPage.evaluate("window.open('about:blank')")
658658
)
659-
popup = await popup_promise
659+
popup = await popup_event_promise
660660
assert popup.url == "about:blank"
661661
await evaluate_promise
662662

tests/test_click.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ async def click():
187187
await page.click("button", timeout=0)
188188
done.append(True)
189189

190-
clicked = asyncio.ensure_future(click())
190+
clicked = asyncio.create_task(click())
191191
await give_it_a_chance_to_click(page)
192192
assert await page.evaluate("result") == "Was not clicked"
193193
assert done == []
@@ -206,7 +206,7 @@ async def click():
206206
await page.click("button", timeout=0)
207207
done.append(True)
208208

209-
clicked = asyncio.ensure_future(click())
209+
clicked = asyncio.create_task(click())
210210
await give_it_a_chance_to_click(page)
211211
assert await page.evaluate("result") == "Was not clicked"
212212
assert done == []
@@ -249,7 +249,7 @@ async def click():
249249
await page.click("button", timeout=0)
250250
done.append(True)
251251

252-
clicked = asyncio.ensure_future(click())
252+
clicked = asyncio.create_task(click())
253253
await give_it_a_chance_to_click(page)
254254
assert done == []
255255
await page.evalOnSelector("button", "b => b.parentElement.style.display = 'block'")
@@ -561,7 +561,7 @@ async def click():
561561
await page.click("button")
562562
clicked.append(True)
563563

564-
click_promise = asyncio.ensure_future(click())
564+
click_promise = asyncio.create_task(click())
565565
assert clicked == [False]
566566

567567
await page.evalOnSelector(".flyover", "flyOver => flyOver.style.left = '0'")
@@ -628,7 +628,7 @@ async def click():
628628
await page.click("text=Click target")
629629
done.append(True)
630630

631-
click_promise = asyncio.ensure_future(click())
631+
click_promise = asyncio.create_task(click())
632632
await give_it_a_chance_to_click(page)
633633
assert await page.evaluate("() => window.__CLICKED") is None
634634
assert done == []
@@ -661,7 +661,7 @@ async def click():
661661
await page.click("input")
662662
done.append(True)
663663

664-
click_promise = asyncio.ensure_future(click())
664+
click_promise = asyncio.create_task(click())
665665
await give_it_a_chance_to_click(page)
666666
assert await page.evaluate("window.__CLICKED") is None
667667
assert done == []
@@ -680,7 +680,7 @@ async def click():
680680
await page.click("select")
681681
done.append(True)
682682

683-
click_promise = asyncio.ensure_future(click())
683+
click_promise = asyncio.create_task(click())
684684
await give_it_a_chance_to_click(page)
685685
assert await page.evaluate("window.__CLICKED") is None
686686
assert done == []
@@ -725,7 +725,7 @@ async def click():
725725
await page.click("text=Click target")
726726
done.append(True)
727727

728-
click_promise = asyncio.ensure_future(click())
728+
click_promise = asyncio.create_task(click())
729729
await give_it_a_chance_to_click(page)
730730
assert await page.evaluate("window.__CLICKED") is None
731731
assert done == []
@@ -742,7 +742,7 @@ async def test_wait_for_LABEL_to_be_clickable_when_it_has_pointer_events_none(
742742
await page.setContent(
743743
'<label onclick="javascript:window.__CLICKED=true;" style="pointer-events:none"><span>Click target</span></label>'
744744
)
745-
click_promise = asyncio.ensure_future(page.click("text=Click target"))
745+
click_promise = asyncio.create_task(page.click("text=Click target"))
746746
# Do a few roundtrips to the page.
747747
for _ in range(5):
748748
assert await page.evaluate("window.__CLICKED") is None
@@ -803,7 +803,8 @@ async def test_fail_when_element_detaches_after_animation(page, server):
803803
await page.goto(server.PREFIX + "/input/animating-button.html")
804804
await page.evaluate("addButton()")
805805
handle = await page.querySelector("button")
806-
promise = asyncio.ensure_future(handle.click())
806+
promise = asyncio.create_task(handle.click())
807+
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
807808
await page.evaluate("stopButton(true)")
808809
error = None
809810
try:
@@ -823,7 +824,8 @@ async def click():
823824
await page.click("button")
824825
clicked.append(True)
825826

826-
promise = asyncio.ensure_future(click())
827+
promise = asyncio.create_task(click())
828+
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
827829
assert clicked == []
828830
assert await page.evaluate("window.clicked") is None
829831
await page.evaluate("stopButton(true)")
@@ -864,7 +866,8 @@ async def test_retry_when_element_is_animating_from_outside_the_viewport(page, s
864866
"""
865867
)
866868
handle = await page.querySelector("button")
867-
promise = asyncio.ensure_future(handle.click())
869+
promise = asyncio.create_task(handle.click())
870+
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
868871
await handle.evaluate("button => button.className = 'animated'")
869872
await promise
870873
assert await page.evaluate("window.clicked")
@@ -896,7 +899,8 @@ async def test_fail_when_element_is_animating_from_outside_the_viewport_with_for
896899
"""
897900
)
898901
handle = await page.querySelector("button")
899-
promise = asyncio.ensure_future(handle.click(force=True))
902+
promise = asyncio.create_task(handle.click(force=True))
903+
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
900904
await handle.evaluate("button => button.className = 'animated'")
901905
error = None
902906
try:
@@ -943,7 +947,8 @@ async def test_click_the_button_when_window_inner_width_is_corrupted(page, serve
943947

944948

945949
async def test_timeout_when_click_opens_alert(page, server):
946-
dialog_promise = asyncio.ensure_future(page.waitForEvent("dialog"))
950+
dialog_promise = asyncio.create_task(page.waitForEvent("dialog"))
951+
await asyncio.sleep(0) # execute scheduled tasks, but don't await them
947952
await page.setContent('<div onclick="window.alert(123)">Click me</div>')
948953
error = None
949954
try:

0 commit comments

Comments
 (0)