Skip to content

Commit

Permalink
Fix files pattern not handling str and BytesIO (#260)
Browse files Browse the repository at this point in the history
  • Loading branch information
lundberg authored Mar 27, 2024
1 parent de7a983 commit 4237976
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 @@ -562,7 +563,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 @@ -573,6 +574,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 @@ -456,6 +457,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 @@ -487,6 +500,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 4237976

Please sign in to comment.