Вот рабочий пример, который, кажется, ловит не 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