How to get a request that is not the last in HttPretty?

1.6k Views Asked by At

Using the HTTPretty library for Python, I can create mock HTTP responses for my unit tests. When the code I am testing runs, instead of my request reaching the third party, the request is intercepted and my code receives the response I configured.

I then use last_request() and can check the url my code requested, any parameters, etc.

What I would like is to know how can I access not just the last request but also any other requests my code sent before the last one.

This seems to be possible. In the documentation it uses a list called latest_requests. For example here

But that doesn't seem to work for me. I get an AttributeError AttributeError: module 'httpretty' has no attribute 'latest_requests'

Here is some code that illustrates what I am trying to do and where I get AttributeError

import httpretty
import requests

httpretty.enable()
httpretty.register_uri(
    method=httpretty.GET,
    uri='http://www.firsturl.com',
    status=200,
    body='First Body'
)

httpretty.enable()
httpretty.register_uri(
    method=httpretty.GET,
    uri='http://www.secondurl.com',
    status=200,
    body='secondBody'
)

firstresponse = requests.get('http://www.firsturl.com')
secondresponse = requests.get('http://www.secondurl.com')

print(httpretty.latest_requests[-1].url)

# clean up
httpretty.disable()
httpretty.reset()

Thanks!!

1

There are 1 best solutions below

0
On BEST ANSWER

Unfortunately, after reading the docs and attempting to get your code working, I can only describe the documentation as blatantly incorrect. There appear to be three | separate | pull requests from several years ago that claim to make httpretty.latest_requests a real attribute but none of them have merged in for whatever reason.

With all of that said, I managed to get the list of all previous requests by calling

 httpretty.HTTPretty.latest_requests

This returns a list of HTTPrettyRequest objects. Seeing as httpretty.last_request() returns an HTTPrettyRequest object, that attribute is probably what you're looking for.

Unfortunately, .url is not defined on that class (but it is defined on the blank request object which doesn't make any sense). If you want to check that the request URL is what you're expecting, you pretty much have to try reconstructing it yourself:

req = httpretty.HTTPretty.latest_requests[-1]
url = req.headers.get('Host', '') + req.path

If you're passing anything in the query string, you'll have to reconstruct that from req.querystring although that's not ordered so you probably don't want to turn that into a string for matching purposes. Also, if all of your requests are going to the same domain, you can leave off the host part and just compare req.path.