pytest/unittest修改sys.path后如何正确mock.patch模块的get_conn函数
问题根源
Python的mock补丁遵循在哪使用就在哪打的规则,你之前所有尝试都是对get_conn的定义路径打补丁,但是实际调用get_conn的code.py模块已经在导入时把get_conn绑定到了自身的命名空间,修改原定义路径的引用不会影响code.py里已经导入的这个引用,所以mock不生效。
解决步骤
1. 修正sys.path插入顺序
首先修改conftest.py里的sys.path添加逻辑,把append改为insert到首位,避免系统中存在同名模块时优先加载外部模块:
import os import sys # 把dags目录放到sys.path最前面,优先加载项目内模块 sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "dags"))
2. 确定补丁路径
找到你要测试的code.py对应的导入路径:
比如你的code.py存放在dags/etl/report/code.py,那么它的导入路径就是etl.report.code,你需要打补丁的路径就是etl.report.code.get_conn。
3. 修正mock写法
不管是全局fixture还是单测试用例的补丁,都用上面的路径即可,示例如下:
全局fixture示例
import pytest from unittest import mock @pytest.fixture(autouse=True, scope="function") def mock_get_conn(): # 替换为你的code.py对应的补丁路径 with mock.patch("etl.report.code.get_conn") as mock_getter: # 提前适配上下文管理器的mock逻辑 mock_cursor = mock.MagicMock() mock_conn = mock.MagicMock() mock_conn.cursor.return_value.__enter__.return_value = mock_cursor mock_getter.return_value = mock_conn yield mock_getter, mock_cursor
单测试用例示例
from unittest import mock # 导入你要测试的select_records函数 from etl.report.code import select_records @mock.patch("etl.report.code.get_conn") def test_executes_sql_with_default_bindings(mock_getter): # arrange sql = "SELECT * FROM table" test_bindings = {} expect_records = [{"col1":1}, {"col1":2}] mock_cursor = mock.MagicMock() mock_cursor.fetchall.return_value = expect_records mock_conn = mock.MagicMock() mock_conn.cursor.return_value.__enter__.return_value = mock_cursor mock_getter.return_value = mock_conn # act res = select_records(conn_id="orca", sql=sql, bindings=test_bindings) # assert mock_getter.assert_called_once_with("orca") mock_cursor.execute.assert_called_once_with(sql, test_bindings) assert res == expect_records
内容的提问来源于stack exchange,提问作者Philippe Hebert
相关产品推荐
相关产品推荐

