Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
“的单元测试”;FileNotFoundError";用python_Python_Unit Testing_Python 3.x_Mocking - Fatal编程技术网

“的单元测试”;FileNotFoundError";用python

“的单元测试”;FileNotFoundError";用python,python,unit-testing,python-3.x,mocking,Python,Unit Testing,Python 3.x,Mocking,我有下面的代码,希望在给定函数引发“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 我不知道如何测试它引发“FileNotFound

我有下面的代码,希望在给定函数引发“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\u auth的情况

任何暗示都将不胜感激


谢谢

在单元测试中,您需要模拟
get\u auth
函数,并使用
属性使其引发
FileNotFoundError
。副作用
属性:

@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth):
    mock_get_auth.side_effect = FileNotFoundError
然后,您可以测试是否实际调用了
create\u 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)