Python模拟基类的属性

时间:2018-04-11 22:09:58

标签: python unit-testing mocking patch

为了测试,我想在基类中更改单个Class实例的属性(self.attr)。

# app.py
class Base():
    def __init__(self):
        self.attr = 'original_value'

    def show(self):
        print(self.attr) 

class App():
    def __init__(self):  
        self.base = Base()

这是我尝试模拟Base类实例的属性attr

# test_app.py
from mock import Mock
from app import App

def test_mock_inherited_class_instance():
    """ With mocking. Change app.base.attr from 'original_value' to 'new_value'.
    """
    app = App()
    app.base = Mock()
    app.base.attr = 'new_value'
    app.base.show() # I'd like this to show 'new_value', NOT 'original_value'

1 个答案:

答案 0 :(得分:0)

类的实例成员或实例变量与类属性或类属性不同。这只是通过保留所有类属性来嘲笑attr

import mock
from app import App
from app import Base
import unittest
from StringIO import StringIO
class TestApp(unittest.TestCase):

    @mock.patch('sys.stdout', new_callable=StringIO)
    def test_mock_instance_var(self, mocked_stdout):

        base = Base()
        app = App()

        mock_base = mock.MagicMock(name='Base', spec=Base)
        instance = mock_base.return_value
        instance.attr.return_value = 'mmm'
        base.attr = instance.attr.return_value
        self.assertEqual(base.attr, 'mmm')

        app.base = base

        self.assertEqual(app.base.attr, 'mmm')
        # the print stdout of show()
        app.base.show()
        self.assertEqual(mocked_stdout.getvalue(), 'mmm\n')