From 26bc846034a4a531dcf0a26e4ec71e5cedf55851 Mon Sep 17 00:00:00 2001 From: Jonas Lundberg Date: Tue, 26 Mar 2024 18:35:43 +0100 Subject: [PATCH] Fix files pattern not handling `str` and `BytesIO` --- respx/patterns.py | 9 ++++++++- tests/test_patterns.py | 22 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/respx/patterns.py b/respx/patterns.py index d8b00b5..876632c 100644 --- a/respx/patterns.py +++ b/respx/patterns.py @@ -1,3 +1,4 @@ +import io import json as jsonlib import operator import pathlib @@ -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] @@ -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: diff --git a/tests/test_patterns.py b/tests/test_patterns.py index dda7914..c35ff84 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -1,3 +1,4 @@ +import io import re from unittest.mock import ANY @@ -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, { @@ -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...")],