Python 模拟 psycopg2 连接和光标

sna*_*low 1 python unit-testing mocking contextmanager pytest

我无法模拟 psycopg2 数据库连接和游标,因为我已将其重构为使用游标的上下文管理器。我知道使用上下文管理器时,会调用额外的魔术方法来进行资源设置和清理(__enter____exit__),但即使将其添加到组合中也没有缩小问题的范围。

这是代码:

import os
import psycopg2
import psycopg2.extras

DB_HOST = os.getenv('DB_HOST')     
DB_PORT = os.getenv('DB_PORT')
DB_NAME = os.getenv('DB_NAME')
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')            
CONN = psycopg2.connect(f'dbname={DB_NAME} user={DB_USER} host={DB_HOST} port={DB_PORT} password={DB_PASSWORD}')

def my_func():
    message = None
    print(CONN)  # Added to debug - this never prints out a magic mock reference

    select_sql = 'SELECT * FROM app.users WHERE name = %s LIMIT 1;'
    with CONN.cursor(cursor_factory = psycopg2.extras.DictCursor) as cursor:
        print(cursor) # Debug - no magic mock reference
        cursor.execute(select_sql, ("Bob"))
        row = cursor.fetchone()

    if row is not None: 
        message = "name found"
    else:
        message = "name not found"

    return message

Run Code Online (Sandbox Code Playgroud)

这是测试代码和我模拟连接和光标的尝试

import pytest

from src import my_class
from unittest import mock

class TestFunction:
    @mock.patch('psycopg2.connect')
    def test_my_func(self, mock_connect):

        mock_cursor = mock.MagicMock()
        mock_cursor.__enter__.return_value.fetchone.return_value = {
            "id": 1,
            "name": "Bob",
            "age": 25
        }
        mock_connect.return_value.cursor.return_value = mock_cursor

        result = my_class.my_func()
        assert result == "found"
Run Code Online (Sandbox Code Playgroud)

cursor如果我调用全局连接,我不确定如何模拟连接或光标CONN。当前运行的 pytest 显示测试失败,并且打印语句显示底层对象不是魔法模拟。如何使用上下文管理器模拟全局数据库连接和数据库游标?任何帮助表示赞赏。

sna*_*low 8

我找到了解决办法!我感觉我的问题出在全局变量上CONN,并研究了如何模拟 python 全局变量并进行了尝试。我的打印声明最终表明这些实例确实是 Magic Mocks。

这是有道理的,在我的测试中,我只调用被测试的方法,而不是使用全局变量触发代码 - 所以只需将其设置为您想要的值即可。一旦你得到答案,听起来就很简单了,对吧?

mock_cursor = mock.MagicMock()
mock_cursor.fetchone.return_value = {
      "id": 1,
      "name": "Bob",
      "age": 25
}
mock_connect.cursor.return_value.__enter__.return_value = mock_cursor
my_class.CONN = mock_connect

Run Code Online (Sandbox Code Playgroud)

没有什么比回答你自己的问题更好的了!