Skip to content

json_params_matcher fails on falsy top-level JSON primitives (0, False, "") #834

Open

Description

@mayureshsonawane17

Describe the bug

When matching a request body containing a falsy top-level JSON primitive (such as 0, False, or ""), matchers.json_params_matcher fails to match the incoming request because (params or {}) in responses/matchers.py evaluates to {}.

Additional context

In responses/matchers.py line 138:

json_params = (params or {}) if not isinstance(params, list) else params

Because (params or {}) uses boolean truthiness (or), any falsy valid JSON primitive value (0, False, "", 0.0) is replaced with {}.

When a client sends requests.post(url, json=0), request_body is "0" and json_module.loads(request_body) produces 0. The equality comparison json_params == json_body compares {} == 0, which evaluates to False. The mock fails with:
request.body doesn't match: 0 doesn't match {}

Instead, json_params should only default to {} when params is None:

json_params = {} if params is None else params

I checked existing issues and PRs (such as #559 and #814); none currently track falsy top-level scalar JSON primitives.

Version of responses

0.26.3

Steps to Reproduce

import responses
from responses import matchers
import requests

@responses.activate
def test_json_primitive():
    responses.add(
        responses.POST,
        "https://example.com/api",
        body="OK",
        match=[matchers.json_params_matcher(0)],
    )
    # Sending 0 as the JSON body
    resp = requests.post("https://example.com/api", json=0)
    assert resp.status_code == 200

test_json_primitive()

Expected Result

The mock should match the request successfully since the request payload (0) matches the expected matcher parameter (0).

Actual Result

ConnectionError: Connection refused by Responses - the call doesn't match any registered mock.

Request:
- POST https://example.com/api

Available matches:
- POST https://example.com/api request.body doesn't match: 0 doesn't match {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions