简体   繁体   中英

Mocking chained calls in Python

I am trying to test the following class 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM