【问题标题】:Why 'self' needed for patch and assert in Python?为什么 Python 中的补丁和断言需要“自我”?
【发布时间】:2016-06-28 04:02:18
【问题描述】:

我通常使用:

def create_patch(self, name, value = None):
    patcher = patch(name)
    mock = patcher.start()
    mock.return_value = value
    self.addCleanup(patcher.stop)
    return mock

def assertXmlEqual(self, a, b):
    with open(a, 'r') as f:
        axml = f.read()
    with open(b, 'r') as f:
        bxml = f.read()
    self.assertEqual(loads(dumps((parse(axml)))), loads(dumps((parse(bxml)))))

在测试用例中:

mockobj = self.create_patch('mymodule.myclass.mymethod', 'myvalue')

self.assertXmlEqual('expect.xml', 'result.xml')

但是对于每个单元测试类,我都必须复制它。

有什么方法可以让这些更独立于测试用例,更像一个库,比如 .net 中的 MoqAssert 以及 Ruby 中的 mockexpect

这是他们的行为方式。看?它们独立于测试用例。

MoqAssert

var obj = new Moq.Mock<MyPackage.MyClass>() { CallBase = true };
obj.Setup(p => p.MyMethod(Moq.It.IsAny<string>())).Returns(false);

Assert.AreEqual(expect, result)

allowexpect

obj = double
allow(obj).to receive(:my_method).and_return('myvalue')

expect(result).to eq(expect)
expect(obj).to have_received(:my_method).exactly(3).times

【问题讨论】:

    标签: python unit-testing mocking patch assert


    【解决方案1】:

    您可以创建一个基本测试用例,然后让所有其他测试用例继承自 而不是unittest.TestCase

    class MyBaseTestCase(unittest.TestCase):
        def create_patch(self, name, value = None):
            patcher = patch(name)
            mock = patcher.start()
            mock.return_value = value
            self.addCleanup(patcher.stop)
            return mock
    
        def assertXmlEqual(self, a, b):
            with open(a, 'r') as f:
                axml = f.read()
            with open(b, 'r') as f:
                bxml = f.read()
            self.assertEqual(loads(dumps((parse(axml)))), loads(dumps((parse(bxml)))))
    
    
    class MyTestCaseThatTestsSomething(MyBaseTestCase):
        def test_something(self):
            self.patch('something.dependency', 'Hello World')
            result_xml = something()
            self.assertXmlEqual(result_xml, expected_xml)
    

    【讨论】:

    • 很好地尝试继承。有没有另一种更优雅的方式,比如 .net 中的 MoqAssert 以及 Ruby 中的 mockexpect
    • @Mike -- 据我所知,这是 使用 python 的unittest 完成此任务的方法。我不知道MoqAssert 如何在.net 中工作,也不知道mockexpect 如何在ruby 中工作。前面提到的框架如何让它们“更优雅”?你到底在寻找什么行为?可能有一个不同的 Python 单元测试框架更接近您的需求。
    • 我添加了更多细节 :)
    猜你喜欢
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2011-06-09
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多