在类方法中使用pytest monkeypatch时结果不清楚

时间:2019-04-18 16:37:38

标签: python pytest

我正在将我的一个项目中的测试从unittest转换为pytest,因此我仍在学习其工作方式。在此过程中,我使用Monkeypatch更改了一种内部方法的返回值。

TestConfiguration

这对于所示的方法和setup_method类的所有其他方法都非常有效。

但是我还有另一个类扩展了BorgQtTestCase的{​​{1}}。

class TestGuiConfiguration(BorgQtTestCase):
    """Test how the Qt frontend writes and reads, to and from the configuration
    file."""
    def setup_method(self, monkeypatch):
        super().setup_method()
        copyfile(self.config_path, '/tmp/test.conf')
        monkeypatch.setattr(self.form.config, '_get_path', self.mock_return)
        self.form.config.read()

    def teardown_method(self):
        self.form.config.path = '/tmp/test.conf'
        if os.path.exists(self.form.config.path):
            os.remove(self.form.config.path)

    def test_set_form_values(self):
        self.form.config.set_form_values()
        assert (self.form.config.password
                == self.form.config.line_edit_password.text())

在该类中,monkeypatch不起作用,运行测试时出现以下错误:

def setup_method(self, monkeypatch):
        super().setup_method()
        copyfile(self.config_path, '/tmp/test.conf')
>       monkeypatch.setattr(self.form.config, '_get_path', self.mock_return)
E       AttributeError: 'function' object has no attribute 'setattr'

我发现了这篇文章https://stackoverflow.com/a/42334155/7723859,并且提供的解决方案与固定装置一起工作了,我真的不太明白为什么。 他写道,Monkeypatch在unittest.TestCase类中不起作用,但是我没有在使用该类,并且Monkeypatch在常规方法中起作用,而在setup_method中却没有。 有人知道为什么这里出问题了吗?

0 个答案:

没有答案