开发者

Mocking chained calls in Python

I am trying to test the following class开发者_如何学C using unittest and the mock library:

class Connection(object):
    def __init__(self, cookie):
    self.connect = None
    self.session = Session()
    self.session.load(cookie)
    # do some stuff with self.session
    self.some_info = self.session.data['the_info']

How could I test if when I create an instance of Connection, depending on the return of the Session instance, I assert if self.some_info is with the value I am expecting?

I wish to use the mock library. In its documentation I have an example of mocking chained calls (http://www.voidspace.org.uk/python/mock/examples.html#mocking-chained-calls), but it isn't very clear of how I can adapt it to my problem.

The Session.load(cookie) method sets some attributes in the Session instance. I would like to set this values fixed for my tests for every value of cookie.


Assume Connection is located in module package.module.connection

The following code should be how you would test your session:

import mock


class TestConnection(unittest.TestCase):

    @mock.patch('package.module.connection.Session')
    def test_some_info_on_session_is_set(self, fake_session):
        fake_session.data = {'the_info': 'blahblah'}
        cookie = Cookie()
        connection = Connection(cookie)
        self.assertEqual(connection.some_info, 'blahblah')
        fake_session.load.assert_called_once_with(cookie)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜