Skip to content

Commit 4237976

Browse files
authored
Fix files pattern not handling str and BytesIO (#260)
1 parent de7a983 commit 4237976

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

respx/patterns.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import io
12
import json as jsonlib
23
import operator
34
import pathlib
@@ -562,7 +563,7 @@ class Files(MultiItemsMixin, Pattern):
562563
key = "files"
563564
value: MultiItems
564565

565-
def _normalize_file_value(self, value: FileTypes) -> Tuple[Any, ...]:
566+
def _normalize_file_value(self, value: FileTypes) -> Tuple[Any, Any]:
566567
# Mimic httpx `FileField` to normalize `files` kwarg to shortest tuple style
567568
if isinstance(value, tuple):
568569
filename, fileobj = value[:2]
@@ -573,6 +574,12 @@ def _normalize_file_value(self, value: FileTypes) -> Tuple[Any, ...]:
573574
filename = ANY
574575
fileobj = value
575576

577+
# Normalize file-like objects and strings to bytes to allow equality check
578+
if isinstance(fileobj, io.BytesIO):
579+
fileobj = fileobj.read()
580+
elif isinstance(fileobj, str):
581+
fileobj = fileobj.encode()
582+
576583
return filename, fileobj
577584

578585
def clean(self, value: RequestFiles) -> MultiItems:

tests/test_patterns.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import io
12
import re
23
from unittest.mock import ANY
34

@@ -456,6 +457,18 @@ def test_data_pattern(lookup, data, request_data, expected):
456457
},
457458
False,
458459
),
460+
(
461+
Lookup.EQUAL,
462+
{"file_1": ("filename.png", io.BytesIO(b"some..image..data"), "image/png")},
463+
None,
464+
True,
465+
),
466+
(
467+
Lookup.EQUAL,
468+
{"file_1": ("filename.png", "some..image..data", "image/png")}, # str data
469+
{"file_1": ("filename.png", io.BytesIO(b"some..image..data"), "image/png")},
470+
True,
471+
),
459472
(
460473
Lookup.CONTAINS,
461474
{
@@ -487,6 +500,15 @@ def test_data_pattern(lookup, data, request_data, expected):
487500
},
488501
True,
489502
),
503+
(
504+
Lookup.CONTAINS,
505+
{"file_1": "foo..."}, # str data
506+
{
507+
"file_1": ("filename_1.txt", io.BytesIO(b"foo...")),
508+
"file_2": ("filename_2.txt", io.BytesIO(b"bar...")),
509+
},
510+
True,
511+
),
490512
(
491513
Lookup.CONTAINS,
492514
[("file_1", b"ham...")],

0 commit comments

Comments
 (0)