Skip to content

Commit b8b7155

Browse files
authored
fix: raise Error instead of assert for user input validation (#3245)
1 parent 1de5d37 commit b8b7155

7 files changed

Lines changed: 29 additions & 25 deletions

File tree

‎playwright/_impl/_assertions.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1103,7 +1103,8 @@ def to_expected_text_values(
11031103
ignoreCase: Optional[bool] = None,
11041104
) -> Sequence[ExpectedTextValue]:
11051105
out: List[ExpectedTextValue] = []
1106-
assert isinstance(items, (list, tuple))
1106+
if not isinstance(items, (list, tuple)):
1107+
raise Error("Expected a list or tuple of strings or patterns")
11071108
for item in items:
11081109
if isinstance(item, str):
11091110
o = ExpectedTextValue(

‎playwright/_impl/_fetch.py‎

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -354,9 +354,8 @@ async def fetch(
354354
if isinstance(to_impl(urlOrRequest), network.Request)
355355
else None
356356
)
357-
assert request or isinstance(
358-
urlOrRequest, str
359-
), "First argument must be either URL string or Request"
357+
if not request and not isinstance(urlOrRequest, str):
358+
raise Error("First argument must be either URL string or Request")
360359
return await self._inner_fetch(
361360
request,
362361
url,
@@ -391,17 +390,16 @@ async def _inner_fetch(
391390
) -> "APIResponse":
392391
if self._close_reason:
393392
raise TargetClosedError(self._close_reason)
394-
assert (
393+
if (
395394
(1 if data is not None else 0)
396395
+ (1 if form is not None else 0)
397396
+ (1 if multipart is not None else 0)
398-
) <= 1, "Only one of 'data', 'form' or 'multipart' can be specified"
399-
assert (
400-
maxRedirects is None or maxRedirects >= 0
401-
), "'max_redirects' must be greater than or equal to '0'"
402-
assert (
403-
maxRetries is None or maxRetries >= 0
404-
), "'max_retries' must be greater than or equal to '0'"
397+
) > 1:
398+
raise Error("Only one of 'data', 'form' or 'multipart' can be specified")
399+
if maxRedirects is not None and maxRedirects < 0:
400+
raise Error("'max_redirects' must be greater than or equal to '0'")
401+
if maxRetries is not None and maxRetries < 0:
402+
raise Error("'max_retries' must be greater than or equal to '0'")
405403
url = url or (request.url if request else url)
406404
method = method or (request.method if request else "GET")
407405
# Cannot call allHeaders() here as the request may be paused inside route handler.
@@ -518,9 +516,8 @@ async def _form_data_field_to_form_field(name: str, value: Any) -> FormField:
518516
)
519517
if is_file_payload(value):
520518
payload = cast(FilePayload, value)
521-
assert isinstance(
522-
payload["buffer"], bytes
523-
), f"Unexpected buffer type of form field {name!r}"
519+
if not isinstance(payload["buffer"], bytes):
520+
raise Error(f"Unexpected buffer type of form field {name!r}")
524521
return FormField(name=name, file=file_payload_to_json(payload))
525522
if isinstance(value, (str, int, float, bool)):
526523
return FormField(name=name, value=str(value))

‎playwright/_impl/_js_handle.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,8 @@ def serialize_value(
185185
if isinstance(value, ParseResult):
186186
return {"u": urlunparse(value)}
187187
if isinstance(value, Pattern):
188-
assert isinstance(value.pattern, str), "Only str patterns are supported."
188+
if not isinstance(value.pattern, str):
189+
raise Error("Only str patterns are supported.")
189190
return {"r": {"p": value.pattern, "f": escape_regex_flags(value)}}
190191

191192
if value in visitor_info.visited:

‎playwright/_impl/_str_utils.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
import re
1717
from typing import Pattern, Union
1818

19+
from playwright._impl._errors import Error
20+
1921

2022
def escape_regex_flags(pattern: Pattern) -> str:
2123
flags = ""
@@ -27,11 +29,14 @@ def escape_regex_flags(pattern: Pattern) -> str:
2729
flags += "s"
2830
if (pattern.flags & int(re.MULTILINE)) != 0:
2931
flags += "m"
30-
assert (
32+
if (
3133
pattern.flags
3234
& ~(int(re.MULTILINE) | int(re.IGNORECASE) | int(re.DOTALL) | int(re.UNICODE))
33-
== 0
34-
), "Unexpected re.Pattern flag, only MULTILINE, IGNORECASE and DOTALL are supported."
35+
!= 0
36+
):
37+
raise Error(
38+
"Unexpected re.Pattern flag, only MULTILINE, IGNORECASE and DOTALL are supported."
39+
)
3540
return flags
3641

3742

‎tests/async/test_fetch_global.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ async def test_should_throw_an_error_when_max_redirects_is_less_than_0(
467467
) -> None:
468468
request = await playwright.request.new_context()
469469
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
470-
with pytest.raises(AssertionError) as exc_info:
470+
with pytest.raises(Error) as exc_info:
471471
await request.fetch(
472472
server.PREFIX + "/a/redirect1", method=method, max_redirects=-1
473473
)
@@ -507,7 +507,7 @@ async def test_should_reject_empty_data_with_form(
507507
) -> None:
508508
request = await playwright.request.new_context()
509509
with pytest.raises(
510-
AssertionError,
510+
Error,
511511
match="Only one of 'data', 'form' or 'multipart' can be specified",
512512
):
513513
await request.post(

‎tests/async/test_page_evaluate.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ async def test_evaluate_return_regex_unsupported_by_python(page: Page) -> None:
397397

398398

399399
async def test_evaluate_throw_for_unsupported_regex(page: Page) -> None:
400-
with pytest.raises(AssertionError, match="Unexpected re.Pattern flag"):
400+
with pytest.raises(Error, match="Unexpected re.Pattern flag"):
401401
await page.evaluate("a => a", re.compile("foo", re.VERBOSE))
402-
with pytest.raises(AssertionError, match="Only str patterns are supported"):
402+
with pytest.raises(Error, match="Only str patterns are supported"):
403403
await page.evaluate("a => a", re.compile(b"foo"))

‎tests/sync/test_fetch_global.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,7 @@ def test_should_throw_an_error_when_max_redirects_is_less_than_0(
318318
) -> None:
319319
request = playwright.request.new_context()
320320
for method in ["GET", "PUT", "POST", "OPTIONS", "HEAD", "PATCH"]:
321-
with pytest.raises(AssertionError) as exc_info:
321+
with pytest.raises(Error) as exc_info:
322322
request.fetch(
323323
server.PREFIX + "/a/redirect1", method=method, max_redirects=-1
324324
)
@@ -351,7 +351,7 @@ def test_should_reject_empty_data_with_form(
351351
) -> None:
352352
request = playwright.request.new_context()
353353
with pytest.raises(
354-
AssertionError,
354+
Error,
355355
match="Only one of 'data', 'form' or 'multipart' can be specified",
356356
):
357357
request.post(

0 commit comments

Comments
 (0)