Check HTTP request that expires with HTTPretty

Using the HTTPretty library for Python, I can create a response of optional HTTP responses and then pick them up, that is, using the library requests it as follows:

import httpretty import requests # set up a mock httpretty.enable() httpretty.register_uri( method=httpretty.GET, uri='http://www.fakeurl.com', status=200, body='My Response Body' ) response = requests.get('http://www.fakeurl.com') # clean up httpretty.disable() httpretty.reset() print(response) 

Output: <Response [200]>

Is there also the opportunity to register a uri that cannot be reached (for example, connection timeout, connection failure, ...), so that no response is received at all (which does not match the established connection, which gives an HTTP error code such how is 404)?

I want to use this behavior in unit testing to ensure that my error handling works properly (which does different things if there is no connection and connection is established, bad HTTP code). As a workaround, I could try connecting to an invalid server, for example http://192.0.2.0 , which will time out anyway. However, I would prefer to run all my unit tests without using any real network connections.

+6
source share
1 answer

Meanwhile, I got it using the HTTPretty callback body , it seems to create the desired behavior. See Inline Comments below. Actually, this is not quite the same as what I was looking for (this is not the server that cannot be reached, and therefore the request time , but on the server that throws a timeout exception after it is reached, the effect is the same for my usecase .

However, if someone knows a different solution, I look forward to it.

 import httpretty import requests # enable HTTPretty httpretty.enable() # create a callback body that raises an exception when opened def exceptionCallback(request, uri, headers): # raise your favourite exception here, eg requests.ConnectionError or requests.Timeout raise requests.Timeout('Connection timed out.') # set up a mock and use the callback function as response body httpretty.register_uri( method=httpretty.GET, uri='http://www.fakeurl.com', status=200, body=exceptionCallback ) # try to get a response from the mock server and catch the exception try: response = requests.get('http://www.fakeurl.com') except requests.Timeout as e: print('requests.Timeout exception got caught...') print(e) # do whatever... # clean up httpretty.disable() httpretty.reset() 
+6
source

Source: https://habr.com/ru/post/982894/


All Articles