responses icon indicating copy to clipboard operation
responses copied to clipboard

mock requests.ConnectionError, assert function result

Open Mooreel opened this issue 6 years ago • 1 comments

I have a function that returns False if a requests.ConnectionError occurred. How can I test the result of the function in case this exception happens?

The following test fails with the Exception rather than asserting that the function should return False

@responses.activate
def test_get_system_mem_failure(self):
    responses.add(responses.GET,"https://myapi.com/api",
        body=Exception(requests.ConnectionError))
    with pytest.raises(requests.ConnectionError):
        self.assertEqual(sm.get_system_mem(),False)

Mooreel avatar May 24 '20 18:05 Mooreel

I have a function that returns False if a requests.ConnectionError occurred.

Assuming that your function is something like this:

def test_func():
    try:
        # some code which calls https://myapi.com/api and
        # might cause requests.ConnectionError
        requests.get("https://myapi.com/api")
    except requests.ConnectionError:
        return False

How can I test the result of the function in case this exception happens?

You can test your function behavior(return Fales in case of requests.ConnectionError) like this:

@responses.activate
def test_get_system_mem_failure():
    responses.add(responses.GET,"https://myapi.com/api",
        body=requests.ConnectionError())

    assert test_func() is False

hramezani avatar May 24 '20 19:05 hramezani