Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 似乎无法在另一个文件中修补类和方法_Python_Python 3.x_Mocking_Python Unittest_Magicmock - Fatal编程技术网

Python 似乎无法在另一个文件中修补类和方法

Python 似乎无法在另一个文件中修补类和方法,python,python-3.x,mocking,python-unittest,magicmock,Python,Python 3.x,Mocking,Python Unittest,Magicmock,我一直在一个小模型上把头撞在墙上,就像这样: TypeError: __init__() missing 2 required positional arguments: 'a' and 'b' 这是树: src ├── __init__.py ├── file_a.py ├── file_b.py test ├── test_a.py 在文件a中: class qaz(object): def __init__(self): print("\n\nin qaz"

我一直在一个小模型上把头撞在墙上,就像这样:

TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'
这是树:

src
├── __init__.py
├── file_a.py
├── file_b.py


test
├── test_a.py
在文件a中:

class qaz(object):
    def __init__(self):
        print("\n\nin qaz")

    def exec_bar(self):
        bar_inst = bar()
        bar_inst.execute("a", "b")

在文件b中:

class bar(object):
    def __init__(self, a, b):
        print("\n\nin bar")

    def execute(self, c, d):
        print("\n\nin bar -> execute")

所以,我想模拟酒吧,这样我可以测试一个没有任何问题

在测试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'

这意味着模拟不起作用。我似乎无法找出我的错误所在。

在文件b中,您希望在init中传递两个参数 定义初始自我,a,b:

但在文件a中,当您为类bar创建对象时,并没有传递任何参数 bar_inst=bar

这就是为什么你看到了错误 TypeError:_init__缺少2个必需的位置参数:“a”和“b”

你可以做两件事:

从def _init__self、a、b中删除参数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()



Sai Ram解决了这个问题,但想发布代码供将来参考。测试结果是这样的,

从unittest.mock导入补丁,MagicMock 从src.file\u导入qaz 从src.file\u b导入栏

class BarTester(unittest.TestCase):

    @patch.object(bar, '__init__', return_value=None)
    @patch.object(bar, 'execute', return_value=None)
    def test_bar(self, *mock_bar):
        q = qaz()
        q.exec_bar()

嗨-不幸的是,这就是问题所在。我使用mocking库来避免这种情况——它不需要它。我不介意传递初始化变量,但是execute没有被嘲笑。我现在得到了它,我能够在没有MagicMock和不同导入语句的情况下使它工作。我不确定,如果那是你想要的。解决方案:添加到我的第一条评论哦有趣!最后,我需要模拟init和exec_bar函数。你的方法能做到这一点吗?是的,你也能做到。有关如何使用patch.object的详细信息,请参见此处