我想知道我正在处理一个异常,该异常仅在数据库路径不正确时提出,并且仅在通过测试或未通过测试时才反映该错误。功能。目前,当任何错误包含在err子句除外中时,我的单元测试通过。
我怀疑我没有正确构造try-except语句来捕获正确的错误。对于pyodbc,我专门尝试捕获名为“ pyodbc.Error”的错误,但当前所有错误都会导致测试通过。
我希望测试失败,除非引发的错误是except子句中指定的错误。我不想进行“全部捕获”尝试。
def get_database():
try:
conn = pyodbc.connect(
r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=M:\Path\To\Database\My_Database.accdb;'
)
return conn
except pyodbc.Error as err: # Only error I wanted passed for the test!
raise err
@mock.patch('directory1.script1.pyodbc.connect')
def test_invalid_path_to_database(self, mock_conn):
mock_conn.side_effect = pyodbc.Error
# Passes no matter what exception is included in except clause!
self.assertRaises(pyodbc.Error, get_database)
答案 0 :(得分:0)
这是一个有效的示例,似乎捕获了非pyodbc.Error
错误。您能说明您要做什么吗?
import pyodbc
import unittest
import mock
def get_database():
try:
conn = pyodbc.connect(
r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=M:\Path\To\Database\My_Database.accdb;'
)
return conn
except pyodbc.Error as err: # Only error I wanted passed for the test!
raise ValueError('Non pyodbc error')
class Test(unittest.TestCase):
@mock.patch('pyodbc.connect')
def test_invalid_path_to_database(self, mock_conn):
mock_conn.side_effect = pyodbc.Error
self.assertRaises(pyodbc.Error, get_database)
if __name__ == '__main__':
unittest.main()
有输出
Traceback (most recent call last):
File "/Users/henry/projects/stack/.venv/lib/python3.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "example.py", line 21, in test_invalid_path_to_database
self.assertRaises(pyodbc.Error, get_database)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 743, in assertRaises
return context.handle('assertRaises', args, kwargs)
File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/case.py", line 178, in handle
callable_obj(*args, **kwargs)
File "example.py", line 13, in get_database
raise ValueError('Non pyodbc error')
ValueError: Non pyodbc error
----------------------------------------------------------------------
Ran 1 test in 0.002s