How to use `httpretty` to mock out request

1.2k Views Asked by At

Here's a test I've tried writing:

import httpretty
import requests


@httpretty.activate
def test():

    httpretty.register_uri(
        httpretty.GET,
        "http://localhost:8000",
        body='{"origin": "127.0.0.1"}',
        status=200
    )
    requests.get("http://localhost:8000")

When I run it with pytest, however, I get

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionRefusedError(111, 'Connection refused'))

Looking at the documentation, I thought I'd followed it ad verbatim - any suggestions?

1

There are 1 best solutions below

0
On

The specific problem with the code block in the question is that when specifying a port, httpretty needs you to include a trailing slash in the url in the call to register_uri. There's actually a warning about this in the documentation for register_uri, but it still strikes me as something of a missing stair.

So, the code you would need for your basic example to work is:

httpretty.register_uri(
        httpretty.GET,
        "http://localhost:8000/",
        body='{"origin": "127.0.0.1"}',
        status=200
    )

I found this tip and also ran into my own problems which seem to indicate that maybe specifying a port isn't the only factor in play when it comes to trailing slashes.

I ended up switching to the responses library, which seems to get along better with pytest fixtures anyway.