Python模拟缓存的方法

时间:2018-08-07 09:42:02

标签: python unit-testing mocking

我有一个可缓存方法的类:

class Foo:

   def __init__(self, package: str):
      self.is_installed = functools.lru_cache()(
        self.is_installed)

   def is_installed():
       #implementation here

以及通过在类的实例上循环来调用该方法的代码

try:
  if Foo('package').is_installed():
except Exception as e:
  print('Could not install')
else:
  print('Installed properly')

我正在尝试通过模拟is_installed方法引发异常来测试此代码。

@patch.object(Foo, 'is_installed')
def test_exception_installing_bear(self, mock_method):
    mock_method.side_effect = Exception('Something bad')
    # code to assert 'could not install' in stdout

但是它不起作用。不引发异常,并且断言失败。另一方面,输出显示为installed properly。我认为它有一些要缓存的东西。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

  

查看文档

unittest.TestCase.assertRaises

  

替代

with self.assertRaises(Exception):
    mock_args = {'side_effect': Exception}
    with mock.patch('foo.Foo.is_installed', **mock_args):
         Foo.is_installed
相关问题