Skip to content

Commit

Permalink
Fix files pattern not handling str and BytesIO
Browse files Browse the repository at this point in the history
  • Loading branch information
lundberg committed Mar 26, 2024
1 parent 15522db commit 26bc846
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
9 changes: 8 additions & 1 deletion respx/patterns.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import io
import json as jsonlib
import operator
import pathlib
Expand Down Expand Up @@ -560,7 +561,7 @@ class Files(MultiItemsMixin, Pattern):
key = "files"
value: MultiItems

def _normalize_file_value(self, value: FileTypes) -> Tuple[Any, ...]:
def _normalize_file_value(self, value: FileTypes) -> Tuple[Any, Any]:
# Mimic httpx `FileField` to normalize `files` kwarg to shortest tuple style
if isinstance(value, tuple):
filename, fileobj = value[:2]
Expand All @@ -571,6 +572,12 @@ def _normalize_file_value(self, value: FileTypes) -> Tuple[Any, ...]:
filename = ANY
fileobj = value

# Normalize file-like objects and strings to bytes to allow equality check
if isinstance(fileobj, io.BytesIO):
fileobj = fileobj.read()
elif isinstance(fileobj, str):
fileobj = fileobj.encode()

return filename, fileobj

def clean(self, value: RequestFiles) -> MultiItems:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_patterns.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import io
import re
from unittest.mock import ANY

Expand Down Expand Up @@ -444,6 +445,18 @@ def test_data_pattern(lookup, data, request_data, expected):
},
False,
),
(
Lookup.EQUAL,
{"file_1": ("filename.png", io.BytesIO(b"some..image..data"), "image/png")},
None,
True,
),
(
Lookup.EQUAL,
{"file_1": ("filename.png", "some..image..data", "image/png")}, # str data
{"file_1": ("filename.png", io.BytesIO(b"some..image..data"), "image/png")},
True,
),
(
Lookup.CONTAINS,
{
Expand Down Expand Up @@ -475,6 +488,15 @@ def test_data_pattern(lookup, data, request_data, expected):
},
True,
),
(
Lookup.CONTAINS,
{"file_1": "foo..."}, # str data
{
"file_1": ("filename_1.txt", io.BytesIO(b"foo...")),
"file_2": ("filename_2.txt", io.BytesIO(b"bar...")),
},
True,
),
(
Lookup.CONTAINS,
[("file_1", b"ham...")],
Expand Down

0 comments on commit 26bc846

Please sign in to comment.