2017-03-07 80 views
0

我有以下代碼:問題嘲諷嵌套類中的DNSResolver

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) 

我該如何解決呢?

回答

0

顯然,我犯了一個錯誤,試圖通過添加額外的()(mock.Mock返回一個實例,而不是類模板)兩次實例化mocks。這是工作代碼 - 比較以前評論的部分。

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()