具有副作用的修补程序装饰程序:引发异常的问题

2024-05-12 23:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试的两个装饰器在某种意义上都能工作,因为它确实会产生副作用,但是我在unittest中遇到了引发的异常,这使得它失败了。我能做什么?代码如下:

# @patch('src.dao.dao.get_connection', ** {'return_value.raiseError.side_effect': Exception()})
@patch('src.dao.dao.get_connection', side_effect=my_foo())
def test_create_request(self, mock_conn):
    mock_conn.return_value = self.conn
    mock_cur = self.conn.cursor()
    mock_eid = 'to'
    mock_amount = 'throw'
    mock_message = 'an exception'
    try:
        mock_cur.execute("insert into reimbursements values(default, ?, ?, ?, 'pending', '')",
                     (mock_eid, mock_amount, mock_message))
        mock_conn.commit()
    finally:
        mock_conn.close()

运行unittest后出现以下错误:

Error
Traceback (most recent call last):
File "C:\Users\M\scoop\apps\python39\current\lib\unittest\mock.py", line 1337, in patched
return func(*newargs, **newkeywargs)
File "C:\Users\M\PycharmProjects\Project 1\tests\test_dao.py", line 47, in test_create_request
mock_cur.execute("insert into reimbursements values(default, ?, ?, ?, 'pending', '')",
pyodbc.DataError: ('22P02', '[22P02] ERROR: invalid input syntax for type money: "throw";\nError while executing the query (1) (SQLExecDirectW)')

Tags: testselfsrcgetreturnvalueunittestconnection