简体   繁体   English

在python中对“FileNotFoundError”进行单元测试

[英]Unit testing for “FileNotFoundError” in python

I have the following code and wanted to untitest when the given function raises for "FileNotFoundError 我有以下代码,并且当给定函数为“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

I am having trouble figuring out how to test the condition where it raises "FileNotFoundError" and doesn't call create_auth. 我无法弄清楚如何测试引发“FileNotFoundError”并且不调用create_auth的情况。

Any hint would be appreciated 任何提示都将不胜感激

Thanks 谢谢

In your unit test you'd need to mock the get_auth function and cause it to raise a FileNotFoundError by using the .side_effect attribute: 在单元测试中,您需要模拟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

You can then test whether create_auth was actually called: 然后,您可以测试是否实际调用了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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM