python - 如何从调用方法的函数中修补参数?
问题描述
你好,我对单元测试很陌生,因此我遇到了 unittest.mock 的一个大问题。我的项目由不同的模块组成。我的第一个模块是通用:
general.py
def do_something(item, collection):
# some more code that i want to test
try:
collection.insert_one(item)
except:
print("did not work")
我的第二个模块是 my_module.py
mymodule.py
import general
from pymongo import MongoClient
client = MongoClient("localhost", 27017)
db = client['db']
collection = db['col']
item =
{
"id": 1
}
def method:
general.do_something(item, collection)
现在我想测试 general.py 中的 do_something(item, collection) 方法,因此我想模拟 collection.insert_one(item)。我没有找到可能的解决方案。我用补丁试过了,但我的问题是,参数集合(这是一个 pymongo 集合)是一个调用函数的参数。我现在如何设法模拟 collection.insert_one?
我的目标是提取 collection.insert_one 并在其中设置一个 MagicMock。这个 Magic Mock 应该有可能崩溃以检查 except 部分是否有效,或者不崩溃以检查 try 部分是否有效。
TestGeneral.py
import unnittest
class TestGeneral(unittest.TestCase):
@patch()
def test_general():
先感谢您!:)
解决方案
您实际上不需要在这里模拟,您可以创建一个具有类似功能的类。
TestGeneral.py
import unnittest
class TestGeneral(unittest.TestCase):
def test_general_success():
assert general.do_something(collection(), None)
def test_general_failure():
with self.assertRaises(Exception):
general.do_something(collection(fail=True), None))
class collection:
def __init__(self, fail=False):
self.fail = fail
def insert_one(self, item):
if self.fail:
raise Exception
return True
然后您还可以检查标准输出以确保成功使用打印
推荐阅读
- php - Laravel 测试中间件中的 URL 参数 BEFORE 组中间件
- javascript - await 不能按预期在nodejs项目上工作
- python - 使用 Geany IDE 找不到加密模块
- docker - 如何在使用 docker 时禁用 Portainer 上的 CLI?
- architecture - 基于云的虚拟实验室环境架构
- javascript - 将代码部署到 gh-page 后,React 门户不起作用
- odoo - Odoo studio:如何在 o2m 或 m2o 字段中设置模型的值
- azure - 如何在 Azure 上部署 rustici 引擎?
- php - 我收到一个错误“您必须启用 intl 扩展才能使用 CakePHP。”
- reactjs - 没有合适的加载器来处理 js WebPack babel-loader