【发布时间】:2017-04-05 23:00:08
【问题描述】:
我想编写一个单元测试,可以确保函数调用中的 SQL 语句在示意图上是正确的。它应该测试这个调用的执行。然后我想模拟对提交的调用,这样就不会发生对数据库的插入。我正在使用 psycopg2 进行测试。
我有一个类似的功能:
def test_insert(a, b, c):
con = psycopg2.connect(os.environ['PGDB'])
cur = con.cursor()
cur.execute('insert into test_table values ({a}, {b}, {c})'.format(a=a, b=b, c=c))
con.commit()
con.close()
当调用test_insert(1,2,3) 时,我看到插入到表中的行。现在我尝试模拟通话。到目前为止,我已经采取了一些方法:
@mock.patch('psycopg2.connect')
def test(mock_connect, a, b, c):
mock_con = mock_connect.return_value
mock_con.commit.return_value = None
insert_row(a, b, c)
这似乎有效,但实际上并没有调用执行语句。例如,test_insert(1,4,'xyz') 会失败,而 test(1,4,'xyz') 不会。接下来我尝试只模拟 psycopg2 中连接类的提交方法:
@mock.patch('psycopg2.extensions.connection.commit')
def test_insert(mock_commit, a, b, c):
mock_commit.return_value = None
insert_row(a,b,c)
但这给了我一个语法错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/a/.virtualenv/test/lib/python2.7/site-packages/mock/mock.py", line 1318, in patched
patching.__exit__(*exc_info)
File "/home/a/.virtualenv/test/lib/python2.7/site-packages/mock/mock.py", line 1480, in __exit__
setattr(self.target, self.attribute, self.temp_original)
TypeError: can't set attributes of built-in/extension type 'psycopg2.extensions.connection'
有什么好方法可以做我想做的事吗?
【问题讨论】:
标签: python unit-testing mocking psycopg2