3

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.

1
  • 1
    What do you have so far? Commented Mar 16, 2011 at 0:33

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

3 Comments

I didn't understand the patch decorator before. After your answer, I read again the mock documentation and see that is the better way (or the only one :-) ) to accomplish what I need.
Unfortunately the patch decorater is ok if I am trying to change the return of some function of Session class. But if I try to change the data dictionary, the test result in: TypeError: 'Mock' object is not subscriptable
@Renne your question is unclear. What are you trying to do exactly? Can you please post a snippet that demonstrates your problem? Also, your question, thusly, changes from its original form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.