问题描述
我试图了解mock/monkeypatch/pytest-mock
功能.
让我知道是否可行.如果不能,请建议我如何测试此代码.
Let me know if this is possible. If not could you please suggest how I can test this code.
我的代码结构:
/
./app
../__init__.py
../some_module1
.../__init__.py
../some_module2
.../__init__.py
./tests
../test_db.py
/app/__init__.py
是启动我的应用程序(如果有帮助的话,是Flask应用程序)的地方,同时还初始化了到MongoDB数据库的数据库连接对象:
The /app/__init__.py
is where my application (a Flask application if it helps) is started along with initializing a database connection object to a MongoDB database:
# ...
def create_app():
# ...
return app
db_conn = DB()
some_module1
和some_module
导入db_conn
对象并将其用作其功能的一部分:
The some_module1
and some_module
import the db_conn
object and use it as part of their functions:
## some_module1/__init__.py
from app import db_conn
...
db = db_conn.db_name2.db_collection2
def some_func1():
data = db.find()
# check and do something with data
return boolean_result
...
## some_module2/__init__.py
from app import db_conn
...
db = db_conn.db_name1.db_collection1
def some_func2():
data = db.find()
# check and do something with data
return boolean_result
...
在测试中,我想根据从数据库接收到的数据来测试我的代码是否正常运行.我想模拟数据库,更具体地说是db_conn
对象,因为我不想使用真实的数据库(设置和维护环境需要大量工作).
In my tests, I want to test if my code works properly based on the data received from the database.I want to mock the database, more specifically the db_conn
object since I don't want to use a real database (which would be a lot of work setting up the environment and maintaining it).
关于如何模拟db_conn
的任何建议?
Any suggestions on how I can emulate the db_conn
?
我一直在探索pytest-mock
和magicmock
,但是我不认为或不知道如何在测试中模拟db_conn
.
I've been exploring pytest-mock
and magicmock
but I don't think or know how to mock the db_conn
in my test.
推荐答案
我相信您不对真实数据库中的案例进行测试是正确的,因为如果您使用外部依赖项,则不再进行单元测试.
I believe you are right not testing cases on a real database because it's not unit testing anymore if you are using external dependencies.
有可能指定return-value
并对其进行自定义(对于Mock
或MagicMock
对象,每次迭代甚至返回不同的返回值).
There is a possibility to specify return-value
and customize it (different return values on each iteration even) for Mock
or MagicMock
objects.
from unittest.mock import Mock, patch
from app import db_conn
@patch('app.db_conn.find')
def test_some_func1(db_con_mock):
...
assert ...
请记住,在每个patch
中,您都应指定db_conn
的导入路径-使用db_conn
**的路径(我假设每个测试中的路径都不相同) ),而不是它的定义位置.
Keep in mind that in each patch
you should specify the import path of db_conn
- the path where db_conn
**is used (I assume it's a different path in each test), not where it is defined.
这篇关于如何使用pytest-mock或magicmock模拟导入的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!