小编zys*_*ara的帖子

如何模拟psycopg2游标对象?

我在Python2中有这个代码段:

def super_cool_method():
    con = psycopg2.connect(**connection_stuff)
    cur = con.cursor(cursor_factory=DictCursor)
    cur.execute("Super duper SQL query")
    rows = cur.fetchall()

    for row in rows:
        # do some data manipulation on row
    return rows
Run Code Online (Sandbox Code Playgroud)

我想写一些单元测试.我想知道如何使用mock.patch它来修补光标和连接变量,以便它们返回一组伪造的数据?我为我的单元测试尝试了以下代码段,但无济于事:

@mock.patch("psycopg2.connect")
@mock.patch("psycopg2.extensions.cursor.fetchall")
def test_super_awesome_stuff(self, a, b):
    testing = super_cool_method()
Run Code Online (Sandbox Code Playgroud)

但我似乎得到以下错误:

TypeError: can't set attributes of built-in/extension type 'psycopg2.extensions.cursor'
Run Code Online (Sandbox Code Playgroud)

python unit-testing psycopg2 mocking python-2.7

15
推荐指数
2
解决办法
1万
查看次数

标签 统计

mocking ×1

psycopg2 ×1

python ×1

python-2.7 ×1

unit-testing ×1