将MagicMock返回值传递给可测试功能

发布于 2025-01-24 03:58:49 字数 1080 浏览 2 评论 0原文

我开始为我的公司编写一些单位测试。我想从测试与数据库的连接开始。函数get_database_connection() - 在此处未指定的模块中定义 - 连接到我的数据库。否则,会提出异常并返回

import pyodbc
import unittest
from unittest.mock import patch, MagicMock
import package.module
from package.module2 import get_database_connection


@patch("package.module.get_database_connection", MagicMock(return_value=r'Driver=SQL Server;Server=localhost;Database=myDB;Trusted_Connection=yes;'))
def test_get_database_connection():
    assert get_database_connection() is not None
    assert isinstance(get_database_connection(), pyodbc.Connection)

我正在为此项目使用Pytest和Unittest Frameworks。尽管我是测试的新手,但我的印象是MagicMock@patch Decorator中找到的对象将其返回值传递给get_database_connection()。但是,运行$ pytest -v -s返回错误:

get_database_connection() missing 1 required positional argument: 'parameter1'

我在这里缺少什么?也许我误解了MagicMock和该图书馆的运作方式。

*编辑:为了澄清,我传递给@patch的第一个参数是get_database_connection()使用的位置,而不是定义的位置。

I'm beginning to write some unit tests for my company. I want to start by testing the connection to my database. Function get_database_connection()- which is defined in a module not specified here- connects to my database. Otherwise, an exception is raised and returns None.

import pyodbc
import unittest
from unittest.mock import patch, MagicMock
import package.module
from package.module2 import get_database_connection


@patch("package.module.get_database_connection", MagicMock(return_value=r'Driver=SQL Server;Server=localhost;Database=myDB;Trusted_Connection=yes;'))
def test_get_database_connection():
    assert get_database_connection() is not None
    assert isinstance(get_database_connection(), pyodbc.Connection)

I'm using pytest and unittest frameworks for this project. Though I am new at testing, I was under the impression that the MagicMock object found in the @patch decorator would pass its return value to get_database_connection(). However, running $ pytest -v -s returns the error:

get_database_connection() missing 1 required positional argument: 'parameter1'

What am I missing here? Maybe I am misunderstanding how MagicMock and this library works.

*EDIT: For clarification, the first argument I am passing to @patch is the location where get_database_connection() is used, not where it is defined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文