Overly Excessive
Overly Excessive

Reputation: 2125

Python mocking a parameter

I have some code which invokes a HTTP request and I would like to unit test a negative case where it should raise a specific exception for a 404 response. However I am trying to figure out how to mock the parameter so it can raise the HTTPError as a side-effect in the calling function, the mock object seems to create an invokable function which isn't the parameter that it accepts, it is only a scalar value.

def scrape(variant_url):
    try:
        with urlopen(variant_url) as response:
            doc = response.read()
            sizes = scrape_sizes(doc)
            price = scrape_price(doc)
            return VariantInfo([], sizes, [], price)

    except HTTPError as e:
        if e.code == 404:
            raise LookupError('Variant not found!')

        raise e

def test_scrape_negative(self):
    with self.assertRaises(LookupError):
        scrape('foo')

Upvotes: 0

Views: 214

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

Mock the urlopen() to raise an exception; you can do this by setting the side_effect attribute of the mock:

with mock.patch('urlopen') as urlopen_mock:
    urlopen_mock.side_effect = HTTPError('url', 404, 'msg', None, None)
    with self.assertRaises(LookupError):
        scrape('foo')

Upvotes: 1

Related Questions