简体   繁体   English

用Python模拟链式调用

[英]Mocking chained calls in Python

I am trying to test the following class using unittest and the mock library: 我试图使用unittestmock库测试以下类:

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? 我怎么能测试当我创建一个Connection实例时,根据Session实例的返回,如果self.some_info具有我期望的值,我断言?

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. 在我的文档中,我有一个模拟链式调用的例子( http://www.voidspace.org.uk/python/mock/examples.html#mocking-chained-calls ),但我不清楚我怎么能适应我的问题。

The Session.load(cookie) method sets some attributes in the Session instance. Session.load(cookie)方法在Session实例中设置一些属性。 I would like to set this values fixed for my tests for every value of cookie. 我想为我的测试设置这个值固定为cookie的每个值。

Assume Connection is located in module package.module.connection 假设Connection位于模块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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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