csernazs / pytest-httpserver

Http server for pytest to test http clients
MIT License
209 stars 27 forks source link

Am I missing something here? Everything seems to require `httpserver.url_for` which breaks everything #307

Closed sg-s closed 4 months ago

sg-s commented 4 months ago

I'd like to use this to write mocked tests on some code, so something like this:


from my_module import some_code

def test_some_code(httpserver):
    httpserver.expect_request(
            "http://endpoint.com/wow/"
            method="POST",
            json=dict(foo="bar"),
        ).respond_with_json(dict(bar="foo"))

    assert some_code(dict(foo="bar")) == dict(bar="foo")

but it won't work because it tells me it can't find it. i don't want to modify some_code to look at something else

csernazs commented 4 months ago

Hi,

For expect_request you only need to provide the path of the url, eg: /wow in your example.

Then, you need to point your http client to an url returned by httpserver.url_for("/wow"), this will return something like http://localhost:12345/wow (port number will be picked up randomly).

See the example here: https://github.com/csernazs/pytest-httpserver/?tab=readme-ov-file#handling-a-simple-get-request

Zsolt

csernazs commented 4 months ago

FYI: pytest-httpserver runs a real http server, this is not a mocking library, if you want something different, then you could have mocked responses with the responses library which is written for requests.

There's a detailed text about the various ways you can test your http client, pytest-httpserver provides the one which runs a real http server on localhost and your client needs to be connected to it. But there are other possible ways as well. See the details in the docs.

sg-s commented 4 months ago

thank you @csernazs for the comments! i guess if i want to use it, i do have to modify my code to point to the location of the http server on localhost provided by this.