python - 似乎无法在另一个文件中修补类和方法
问题描述
我一直在用这样的小模型把头撞在墙上:
这是树:
src
├── __init__.py
├── file_a.py
├── file_b.py
test
├── test_a.py
在 file_a 中:
class qaz(object):
def __init__(self):
print("\n\nin qaz")
def exec_bar(self):
bar_inst = bar()
bar_inst.execute("a", "b")
在 file_b 中:
class bar(object):
def __init__(self, a, b):
print("\n\nin bar")
def execute(self, c, d):
print("\n\nin bar -> execute")
所以,我想模拟bar
,以便我可以a
毫无问题地进行测试。
在 test_a 中:
from unittest.mock import patch, MagicMock
from src.file_a import qaz
from src.file_b import bar
class BarTester(unittest.TestCase):
@patch('src.file_b.bar')
def test_bar(self, mock_bar):
bar_inst = MagicMock()
bar_inst.execute.return_value = None
mock_bar.return_value = bar_inst
q = qaz()
q.exec_bar()
每次都会失败,如下所示:
TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'
这意味着模拟不起作用。我似乎无法弄清楚我做错了什么。
解决方案
在 file_b 中,您期望在“ init ”中传递 2 个参数
def __init__(self, a, b):
但是在为类栏创建对象时,在 file_a 中,您没有传递任何参数
bar_inst = bar()
这就是您看到错误的原因
TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'
你做两件事:
- 删除参数 a 和 b
def __init__(self, a, b):
- 传递参数时
新解决方案:
from mock import patch
import unittest
from src.file_a import qaz
from src.file_b import bar
class BarTester(unittest.TestCase):
@patch.object(bar, '__init__', return_value=None)
def test_bar(self, *mock_stdout):
q = qaz()
q.exec_bar()
推荐阅读
- javascript - 如何通过使用 JS EventListener 的 HTML 表单的输入来更改 HTML 元素的背景颜色
- flutter - 将数据添加到 initState 中的列表以将其显示为 DropdownMenuItem
- c++ - 我遇到了一个错误 E0003,它说#include 文件包含它自己
- python - 不一致的返回值Pylint
- macos - 如何在 macOS 上的 SwiftUI 中实现拖放到 3rd 方应用程序
- notepad++ - 如何用逗号空格小写字符替换句号空格和小写字符?
- css - 响应性 CSS 媒体查询或容器?
- javascript - ReactJS:Okta Auth RestoreOriginalUri 函数未重定向
- python - Pyspark Py4JJava错误:
- django - 根据 django 中给出的项目数量打印循环数据