将MagicMock返回值传递给可测试功能
我开始为我的公司编写一些单位测试。我想从测试与数据库的连接开始。函数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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论