简体   繁体   中英

How to use `httpretty` to mock out request

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM