Skip to content

Commit

Permalink
FIXUP: rework error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
martinpitt committed Aug 5, 2024
1 parent f76963c commit 3388811
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
8 changes: 7 additions & 1 deletion test/common/bidi.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,15 @@ async def ws_reader(self, ws: aiohttp.client.ClientWebSocketResponse) -> None:
log_proto.debug("ws_reader: resolving pending command %i", data["id"])
if data["type"] == "success":
self.pending_commands[data["id"]].set_result(data["result"])
elif data["type"] == "exception":
self.pending_commands[data["id"]].set_exception(
WebdriverError(data["exceptionDetails"]["text"]))
elif data["type"] == "error":
self.pending_commands[data["id"]].set_exception(
WebdriverError(f"{data['error']}: {data.get('message', '')}"))
else:
self.pending_commands[data["id"]].set_exception(
WebdriverError(f"{data['type']}: {data['message']}"))
WebdriverError(f"unknown response type: {data!r}"))
del self.pending_commands[data["id"]]
continue

Expand Down
47 changes: 25 additions & 22 deletions test/common/testlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,10 +301,10 @@ def kill(self) -> None:
def bidi(self, method: str, **params: Any) -> JsonObject:
"""Send a Webdriver BiDi command and return the JSON response"""

res = asyncio.run_coroutine_threadsafe(self.driver.bidi(method, **params), self.loop).result()
if res.get("type") == "exception":
raise Error(res["exceptionDetails"]["text"])
return res
try:
return asyncio.run_coroutine_threadsafe(self.driver.bidi(method, **params), self.loop).result()
except bidi.WebdriverError as e:
raise Error(str(e)) from None

def cdp_command(self, method: str, **params: Any) -> JsonObject:
"""Send a Chrome DevTools Protocol command and return the JSON response"""
Expand Down Expand Up @@ -753,11 +753,6 @@ def wait_js_cond(self, cond: str, error_description: str = "null") -> None:
awaitPromise=True, target={"context": self.driver.context})
return
except Error as e:
# rewrite exception to have more context, also for compatibility with existing naughties
if "condition did not become true" in e.msg:
raise Error(f"timeout\nwait_js_cond({cond}): {e.msg}") from None
raise
except bidi.WebdriverError as e:
# can happen when waiting across page reloads
if (
# during page loading
Expand All @@ -770,8 +765,12 @@ def wait_js_cond(self, cond: str, error_description: str = "null") -> None:
):
sys.stderr.write("wait_js_cond: Ignoring/retrying %r" % e)
time.sleep(1)
else:
raise
continue

# rewrite exception to have more context, also for compatibility with existing naughties
if "condition did not become true" in e.msg:
raise Error(f"timeout\nwait_js_cond({cond}): {e.msg}") from None
raise

def wait_js_func(self, func: str, *args: object) -> None:
self.wait_js_cond("%s(%s)" % (func, ','.join(map(jsquote, args))))
Expand Down Expand Up @@ -1163,22 +1162,26 @@ def snapshot(self, title: str, label: str | None = None) -> None:
"""
if self.valid:
filename = unique_filename(f"{label or self.label}-{title}", "png")
ret = self.bidi("browsingContext.captureScreenshot", quiet=True, context=self.driver.top_context, origin="document")
if "data" in ret:
try:
ret = self.bidi("browsingContext.captureScreenshot", quiet=True,
context=self.driver.top_context, origin="document")
with open(filename, 'wb') as f:
f.write(base64.standard_b64decode(ret["data"]))
attach(filename, move=True)
print("Wrote screenshot to " + filename)
else:
print("Screenshot not available")
except Error as e:
print("Screenshot not available:", e)

filename = unique_filename(f"{label or self.label}-{title}", "html")
html = self.bidi("script.evaluate", expression="document.documentElement.outerHTML",
quiet=True, awaitPromise=False, target={"context": self.driver.context})
with open(filename, 'wb') as f:
f.write(html["result"]["value"].encode())
attach(filename, move=True)
print("Wrote HTML dump to " + filename)
try:
html = self.bidi("script.evaluate", expression="document.documentElement.outerHTML",
quiet=True, awaitPromise=False, target={"context": self.driver.context})
with open(filename, 'wb') as f:
f.write(html["result"]["value"].encode())
attach(filename, move=True)
print("Wrote HTML dump to " + filename)
except Error as e:
print("HTML dump not available:", e)

def _set_window_size(self, width: int, height: int) -> None:
self.bidi("browsingContext.setViewport", context=self.driver.top_context,
Expand Down Expand Up @@ -2179,7 +2182,7 @@ def snapshot(self, title: str, label: str | None = None) -> None:
if self.browser is not None:
try:
self.browser.snapshot(title, label)
except RuntimeError:
except Error:
# this usually runs in exception handlers; raising an exception here skips cleanup handlers, so don't
sys.stderr.write("Unexpected exception in snapshot():\n")
sys.stderr.write(traceback.format_exc())
Expand Down

0 comments on commit 3388811

Please sign in to comment.