Python 模拟一个参数

Python mocking a parameter

我有一些调用 HTTP 请求的代码,我想对一个负面案例进行单元测试,它应该为 404 响应引发特定异常。但是我想弄清楚如何模拟参数,以便它可以将 HTTPError 作为调用函数的副作用,模拟对象似乎创建了一个可调用函数,它不是它接受的参数, 它只是一个标量值。

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

模拟 urlopen() 引发异常;您可以通过设置模拟的 side_effect attribute 来做到这一点:

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