Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions doc/howto.rst
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ query string as a dictionary.

Behind the scenes an additional step is done by the library: it parses up the
query_string into the dict and then compares it with the dict provided.
Empty values are preserved. For example, ``query_string={"flag": ""}`` matches
both ``?flag=`` and ``?flag``. Neither matches an empty dictionary.
If a parameter appears more than once, a dictionary matches its first value,
including an empty value. A ``werkzeug.datastructures.MultiDict`` matches all
values, including empty ones.


URI matching
Expand Down
5 changes: 3 additions & 2 deletions pytest_httpserver/httpserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,13 @@ def __init__(self, query_dict: Mapping[str, str] | MultiDict[str, str]) -> None:
key-value mapping where both key and value should be string. If there are multiple
values specified for the same key in the request, the first element will be used.
If you want to match multiple values, use a MultiDict object from werkzeug, which
represents multiple values for one key.
represents multiple values for one key. Empty values are kept, including
parameters without an equals sign. An empty value is distinct from a missing key.
"""
self.query_dict = query_dict

def get_comparing_values(self, request_query_string: bytes) -> tuple[Mapping[str, str], Mapping[str, str]]:
query = MultiDict(urllib.parse.parse_qsl(request_query_string.decode("utf-8")))
query = MultiDict(urllib.parse.parse_qsl(request_query_string.decode("utf-8"), keep_blank_values=True))
if isinstance(self.query_dict, MultiDict):
return (query, self.query_dict)
else:
Expand Down
11 changes: 11 additions & 0 deletions releasenotes/notes/empty-query-values-4e70831a4cba318c.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fixes:
- |
Preserve empty query values when matching dictionaries and MultiDict objects.
Both ``flag=`` and ``flag`` match ``{"flag": ""}`` and no longer match ``{}``.
For repeated parameters, dictionary matching uses the first value even when it
is empty. MultiDict matching includes every empty value.
upgrade:
- |
Dictionary expectations must include parameters with empty values.
A request for ``flag=&foo=123`` previously matched ``{"foo": "123"}``.
It now requires ``{"flag": "", "foo": "123"}``.
38 changes: 38 additions & 0 deletions tests/test_querymatcher.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pytest
from werkzeug.datastructures import MultiDict

from pytest_httpserver.httpserver import BooleanQueryMatcher
Expand Down Expand Up @@ -55,3 +56,40 @@ def test_qm_mapping_multiple_values():
md = MultiDict([("k1", "v1"), ("k1", "v2")])
qm = MappingQueryMatcher(md)
assert_match(qm, b"k1=v1&k1=v2")


@pytest.mark.parametrize("query_string", [b"flag=", b"flag", b"flag=&", b"&flag="])
def test_qm_mapping_empty_value(query_string):
qm = MappingQueryMatcher({"flag": ""})
assert_match(qm, query_string)
assert_not_match(qm, b"")
assert_not_match(qm, b"flag=value")


@pytest.mark.parametrize("query_string", [b"flag=", b"flag", b"flag=&flag="])
def test_qm_mapping_empty_value_is_not_missing(query_string):
qm = MappingQueryMatcher({})
assert_not_match(qm, query_string)
assert_match(qm, b"")


@pytest.mark.parametrize("query_string", [b"flag=&flag=value", b"flag&flag=value"])
def test_qm_mapping_first_value_is_empty(query_string):
assert_match(MappingQueryMatcher({"flag": ""}), query_string)
assert_not_match(MappingQueryMatcher({"flag": "value"}), query_string)
assert_match(MappingQueryMatcher({"flag": "value"}), b"flag=value&flag=")


@pytest.mark.parametrize("query_string", [b"flag=&flag=value", b"flag&flag=value"])
def test_qm_mapping_multiple_values_include_empty(query_string):
qm = MappingQueryMatcher(MultiDict([("flag", ""), ("flag", "value")]))
assert_match(qm, query_string)
assert_not_match(qm, b"flag=value")
assert_not_match(qm, b"flag=")


def test_qm_mapping_empty_encoded_name():
qm = MappingQueryMatcher({"empty name": "", "": "value"})
assert_match(qm, b"empty%20name=&=value")
assert_match(qm, b"=value&empty+name=")
assert_not_match(qm, b"=value")
35 changes: 35 additions & 0 deletions tests/test_querystring.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import pytest
import requests
from werkzeug.datastructures import MultiDict

from pytest_httpserver import HTTPServer

Expand Down Expand Up @@ -32,3 +34,36 @@ def test_querystring_dict(httpserver: HTTPServer):
httpserver.check_assertions()
assert response.text == "example_response"
assert response.status_code == 200


@pytest.mark.parametrize("query_string", [{"flag": ""}, MultiDict([("flag", ""), ("flag", "value")])])
def test_querystring_empty_value(httpserver: HTTPServer, query_string):
httpserver.expect_request("/foobar", query_string=query_string).respond_with_data("example_response")
response = requests.get(
httpserver.url_for("/foobar"),
params=query_string.items(multi=True) if isinstance(query_string, MultiDict) else query_string,
)
httpserver.check_assertions()
assert response.status_code == 200
assert response.text == "example_response"


def test_querystring_empty_value_does_not_match_missing(httpserver: HTTPServer):
httpserver.expect_request("/foobar", query_string={}).respond_with_data("example_response")
response = requests.get(httpserver.url_for("/foobar"), params={"flag": ""})
assert response.status_code == 500
with pytest.raises(AssertionError, match="No handler found"):
httpserver.check_assertions()


@pytest.mark.xfail(
strict=True,
raises=AssertionError,
reason="Blank query values must be included in the expected dictionary",
)
def test_querystring_dict_ignores_empty_value(httpserver: HTTPServer):
httpserver.expect_request("/foobar", query_string={"foo": "123"}).respond_with_data("example_response")
response = requests.get(httpserver.url_for("/foobar?flag=&foo=123"))
httpserver.check_assertions()
assert response.status_code == 200
assert response.text == "example_response"
Loading