dean89
dean89

Reputation: 141

Mock two get responses with different result

I'am trying to mock two same get requests but with different result. My goal is to test second exception (except requests.exceptions.RequestException) but I can't make it work so that first requests.get pass and second requests.get fail to "connect" and therefore to reach second exception. Is that even possible? Thx!

try:
    tenants = requests.get('https://hostname_1')     

    for tenant in tenants:

        try:
            a = requests.get('https://host_2')

            try:          
                some_function(arguments)

            except Exception as e:
                print(e)

        except requests.exceptions.RequestException as e:
            print(e)

except Exception as e:
    print(e)

here is what I tried:

@patch("argo_probe_poem.poem_cert.requests.get")
@patch("argo_probe_poem.poem_cert.requests.get")
def test_raise_request_exception(self, mock_requests1, mock_requests2):
    mock_requests1.side_effect = pass_web_api
    mock_requests2.side_effect = requests.exceptions.RequestException

    with self.assertRaises(SystemExit) as e:
        utils_func(self.arguments)

    self.assertEqual(e.exception.code, 2)

Upvotes: 1

Views: 1009

Answers (1)

blhsing
blhsing

Reputation: 106901

You can make the Mock object return different values and/or raise different exceptions on different calls by specifying an iterable as the side_effect attribute.

An excerpt from the documentation:

If you pass in an iterable, it is used to retrieve an iterator which must yield a value on every call. This value can either be an exception instance to be raised, or a value to be returned from the call to the mock...

So your test code should roughly look like:

@patch("argo_probe_poem.poem_cert.requests.get")
def test_raise_request_exception(self, mock_requests):
    mock_requests.side_effect = pass_web_api, requests.exceptions.RequestException

    with self.assertRaises(requests.exceptions.RequestException) as e:
        utils_func(self.arguments)

Upvotes: 1

Related Questions