Python中针对“FileNotFoundError”的单元测试

4
我有以下代码,并希望在给定函数引发“FileNotFoundError”时进行单元测试。
def get_token():
try:
    auth = get_auth() # This function returns auth ,if file exists else throws "FileNotFoundError
except FileNotFoundError: 
    auth= create_auth()
return auth

我在解决如何测试出现“FileNotFoundError”并且不调用create_auth的条件方面遇到了问题。

如果有任何提示,将不胜感激。

谢谢!

1个回答

4
在您的单元测试中,您需要模拟 get_auth 函数并使用 .side_effect 属性使其引发一个 FileNotFoundError 错误:
@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth):
    mock_get_auth.side_effect = FileNotFoundError

您可以测试是否实际调用了create_auth

@mock.patch('path.to.my.file.create_auth')
@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth, mock_create_auth):
    mock_get_auth.side_effect = FileNotFoundError
    get_token()
    self.assertTrue(mock_create_auth.called)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接