From 34fab31e56ceab8ce53e651079b37e7f4971b552 Mon Sep 17 00:00:00 2001 From: sarayourfriend Date: Fri, 21 Jun 2024 10:41:30 +1000 Subject: [PATCH] Ensure body is tested matching regex pattern type --- src/pook/assertion.py | 3 +++ tests/unit/mock_test.py | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/pook/assertion.py b/src/pook/assertion.py index 152f1e6..1871a52 100644 --- a/src/pook/assertion.py +++ b/src/pook/assertion.py @@ -50,6 +50,9 @@ def matches(x, y, regex_expr=False): # Parse regex expression, if needed x = strip_regex(x) if regex_expr and isregex_expr(x) else x + if isinstance(x.pattern, str) and hasattr(y, "decode"): + y = y.decode("utf-8", "backslashescape") + # Assert regular expression via unittest matchers return test_case().assertRegex(y, x) or True diff --git a/tests/unit/mock_test.py b/tests/unit/mock_test.py index cd6b088..fb702ae 100644 --- a/tests/unit/mock_test.py +++ b/tests/unit/mock_test.py @@ -2,6 +2,7 @@ import json import itertools from textwrap import dedent +import re import pook from pook.mock import Mock @@ -213,6 +214,26 @@ def test_body_not_matches(httpbin, mock, mock_body, request_body): assert errors[0].startswith("BodyMatcher: ") +def test_body_matches_string_regex(httpbin, mock): + mock.body(re.compile(r"hello, me!")) + req = Request( + url=httpbin.url, + body="This is a big sentence... hello, me! wow, another part", + ) + + assert mock.match(req) == (True, []) + + +def test_body_matches_bytes_regex(httpbin, mock): + mock.body(re.compile(rb"hello, me!")) + req = Request( + url=httpbin.url, + body="This is a big sentence... hello, me! wow, another part", + ) + + assert mock.match(req) == (True, []) + + def test_xml_matches(httpbin, mock): xml = dedent( """