jeudi 4 août 2016

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')

Aucun commentaire:

Enregistrer un commentaire