lundberg / respx

Mock HTTPX with awesome request patterns and response side effects 🦋
https://lundberg.github.io/respx
BSD 3-Clause "New" or "Revised" License
581 stars 38 forks source link

`assert_all_called()` fails for regex mocks #246

Closed lecrepont01 closed 4 months ago

lecrepont01 commented 9 months ago

Hi,

When mocking routes with a regex path that I use in my test, my test will fail in the teardown when assert_all_called() is called. Is it compatible at all with such regex mocks ?

respx_mock.route(
        method="GET",
        url__regex=r"https://domain.com/[\w-]+/inventory/[\w-]+",
    ).mock(
        return_value=httpx.Response(200, json={"items": 3})
    )
[<Route <Method eq 'GET'> AND <URL regex re.compile('https://domain.com/[\\w-]+/inventory/[\\w-]+')>>]
lundberg commented 9 months ago

Could you provide some more details, e.g. is the respx_mock in your example a fixture or a global mock instance, maybe with multiple added routes?

lecrepont01 commented 9 months ago

Here is the fixture holding the assert :

@pytest.fixture(autouse=True)
def respx_configuration(
    respx_mock: respx.MockRouter,
) -> abc.Generator[None, None, None]:
    yield
    respx_mock.assert_all_called()

and a test

def test_mocked(respx_mock: respx.MockRouter):
    respx_mock.route(
        method="GET",
        url__regex=r"https://domain.com/[\w-]+/inventory/[\w-]+",
    ).mock(
        return_value=httpx.Response(200, json={"items": 3})
    )
    trigger_mocked_route()
lundberg commented 7 months ago

Hmm, for me this file works ...

import abc
from collections.abc import Generator
import httpx
import pytest
import respx

@pytest.fixture(autouse=True)
def respx_configuration(respx_mock: respx.MockRouter) -> Generator[None, None, None]:
    yield
    respx_mock.assert_all_called()

def test_mocked(respx_mock: respx.MockRouter):
    respx_mock.route(
        method="GET",
        url__regex=r"https://domain.com/[\w-]+/inventory/[\w-]+",
    ).mock(return_value=httpx.Response(200, json={"items": 3}))
    response = httpx.get("https://domain.com/foo-bar/inventory/ham-spam")
    assert response.status_code == 200
    assert response.json() == {"items": 3}
lundberg commented 4 months ago

@lecrepont01 I'm closing this, but please re-open if there's still an issue.