How to mock psycopg2 cursor object?

后端 未结 3 1810

I have this code segment in Python2:

def super_cool_method():
    con = psycopg2.connect(**connection_stuff)
    cur = con.cursor(cursor_factory=DictCursor)
         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 03:13

    Since the cursor is the return value of con.cursor, you only need to mock the connection, then configure it properly. For example,

    query_result = [("field1a", "field2a"), ("field1b", "field2b")]
    with mock.patch('psycopg2.connect') as mock_connect:
        mock_connect.cursor.return_value.fetchall.return_value = query_result
        super_cool_method()
    

提交回复
热议问题