在DNSResolver中模拟嵌套类的问题

时间:2017-03-07 14:47:45

标签: python mocking python-unittest

我有以下代码:

import unittest, mock

class MockedRRData(object):
        def to_text(self):
            return '0 example.com.'


class MockedResponse(object):
    answer = [[MockedRRData()]]


class MockedReturnValue(object):
    response = MockedResponse()


class MockedDNSResolver(object):

    def query(self, domain_name, query_type):
        return MockedReturnValue()


class DNSQueryTest(unittest.TestCase):

    def setUp(self):
#        MockedRRData = mock.Mock(to_text=lambda: '0 example.com.')
#        MockedResponse = mock.Mock(answer=[[MockedRRData()]])
#        MockedReturnValue = mock.Mock()
#        MockedReturnValue.attach_mock(MockedResponse, 'response')
#        MockedReturnValue = mock.Mock(response=MockedResponse())
        self.fake_dns_resolver = mock.Mock(query=lambda *args, **kwargs: MockedReturnValue())

    def test_mock(self):
        for rrset in self.fake_dns_resolver.query('a', 'b').response.answer:
            for rrdata in rrset:
                print(rrdata.to_text())

unittest.main()

它有效,但我想过渡到完全使用模拟类 - 如评论中所示。问题是,当我取消注释时,即使只是我的评论的最后一行,我得到以下内容:

E
======================================================================
ERROR: test_mock (__main__.DNSQueryTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/a.py", line 33, in test_mock
    for rrset in self.fake_dns_resolver.query('a', 'b').response.answer:
TypeError: 'Mock' object is not iterable

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

我该如何解决?

1 个答案:

答案 0 :(得分:0)

显然,我错误地尝试通过添加额外的()来实例化两次模拟(mock.Mock返回一个实例,而不是一个类模板)。这是工作代码 - 比较之前评论过的部分。

import unittest, mock

class MockedRRData(object):
        def to_text(self):
            return '0 profound.mail.pairserver.com.'


class MockedResponse(object):
    answer = [[MockedRRData()]]


class MockedReturnValue(object):
    response = MockedResponse()


class MockedDNSResolver(object):

    def query(self, domain_name, query_type):
        return MockedReturnValue()


class DNSQueryTest(unittest.TestCase):

    def setUp(self):
        MockedRRData = mock.Mock(to_text=lambda: '0 profound.mail.pairserver.com.')
        MockedResponse = mock.Mock(answer=[[MockedRRData]])
        MockedReturnValue = mock.Mock(response=MockedResponse)
        self.fake_dns_resolver = mock.Mock(query=lambda *args, **kwargs: MockedReturnValue)

    def test_mock(self):
        for rrset in self.fake_dns_resolver.query('a', 'b').response.answer:
            for rrdata in rrset:
                print(rrdata.to_text())

unittest.main()