API for generating server responses with any status codes

Hello, Habr! While working on a REST API wrapper library, I ran into a problem. To test the processing of erroneous server response codes (400, 500, 403, etc.), it is necessary to artificially create conditions on the server to receive the corresponding codes. With a properly configured server, for example, it is not easy to get a 500 error. And it is somehow necessary to test the error handler functions. I wrote a small API that generates erroneous server responses - httpme.tk



How to apply in testing?



For example, there is code like this ( python3 ):



from requests import session as requests_session

session = requests_session()
session.hooks = {
    'response': lambda r, *args, **kwargs: raise AccessError(' , ..     ') if r.status_code == 403  else pass
}

class AccessError(Exception):
    """ ''  """
    pass

def getter(url):
    return session.get(url)


In short, the code contains a function that returns a server response to a GET request for a given URL; if a 403 error occurs as a result of the request, an internal module exception is thrown AccessError.



This code needs to be tested and debugged. It is quite difficult to manually create the conditions for error 403, and even more so, for example, 500 (the server is working too well). The tester does not care under what conditions the server will issue a 403 error: he is testing not the API itself (for example), but the function that calls it. Therefore, to test throwing an exception with a 403 status code, it can do like this ( python3 + pytest ):



import pytest
from mymodule import 

def test_forbidden():
    with pytest.raises(AccessError):
        getter('http://httpme.tk/403')


How to use?



Very simple. Send a GET request to the server in http://httpme.tk/<status_code>. For example like this ( cURL ):



curl -G http://httpme.tk/500


Or like this ( python3 ):



from requests import get

get('http://httpme.tk/408')  # <Response [408]>


What's inside?



And inside is a small Flask application that calls a function abort(status_code)on every request.



Link to GitHub



That's all!



It is interesting to hear the community assessment of the usefulness of this service.




All Articles