在python中模拟mocked方法的返回值

时间:2015-02-24 00:42:31

标签: python unit-testing mocking

我有一个方法,我正在尝试测试,我想模拟我的测试方法调用的方法。这个模拟方法调用一个调用另一个方法的方法,依此类推。我想模拟顶级方法的返回值,但返回值丢失。我怀疑我没有在正确的地方修补,但我无法弄清楚应该在哪里打补丁。我读过:Where to patch,但我不知道我哪里出错了。

我尝试测试的方法是get_url,它首先要做的是创建一个Bar类的实例。 Bar然后调用我想要模拟的方法get_objresult应包含objectLocation个对象列表,每个对象都有一个网址。然而,我唯一得到的是一个没有返回值的模拟对象。

gamma.FooClass.py

import BarClass

class Foo(object):

    def get_bar(self):
        bar = BarClass.Bar()
        return bar

    def resolve(self):
        bar = self.get_bar()
        result = bar.resolve()
        res = []
        for location in result.objectLocation:
            res.append(location.url)
        return res

gamma.BarClass.py

from BarLocationClass import BarLocation

class Bar(BarLocation):

    def __init__(self):
        BarLocation.__init__(self)

    def resolveResponse(self,pid):
        url = self._rest_url('resolve/%(pid)s', pid='pid')
        return self.GET(url)

    def resolve(self):
        response = self.resolveResponse('pid')
        return self._read_response(response, 1, 0,'ObjectLocationList',response_contains_303_redirect=True)

gamma.BarLocationClass

from BarRestClass import BarRest

class BarLocation(BarRest):

    def __init__(self):
        BarRest.__init__(self)

    def _rest_url(self, path_format, **args):
        url = 'www.example.com'
        return url    

    def _read_response(self, response, major, minor, d1_type_name,
                                response_contains_303_redirect=False):
        return 'fake_obj'

BarRestClass.py

class BarRest(object):

    def GET(self, url, query=None, headers=None, n_tries=3,
            dump_path=None):

        return self._send_request('GET', url, query, headers, n_tries=n_tries,dump_path=dump_path) 

test.test_foobar.py

class objectLocation():
    def __init__(self):
        self.objectLocation = [Mock(url='www.example.com')]*2

class Test(unittest.TestCase):


    def setUp(self):
        self.client = foo.Foo()

    @patch.object(foo.BarClass.Bar,'resolve')
    def testName(self,mock_resolve):
        mock_resolve.return_value = objectLocation()
        output = self.client.resolve()
        self.assertEqual(['www.example.com','www.example.com'],output)


if __name__ == "__main__":
    unittest.main()

0 个答案:

没有答案