如何在不覆盖`self`的情况下模拟基于类的View的特定方法?

时间:2016-04-06 02:42:01

标签: python django python-3.x django-class-based-views django-unittest

我正在尝试在django中的TestCase中修补视图的功能。我有一节课:

class BaseView(View):

    def _get_data(self):
        self.attribute = self.fancy_stuff()
        self.thing = self.do_other_stuff()

我需要将self.attribute模拟为一个空列表,如:

_get_data_fake_function():
    self.attribute = []
    self.thing = True

问题在于我在测试案例中如下:

class MyTests(TestCase):

    def setUp(self):
        self.view = BaseView
        self.view_instance = self.view()

        def test_stuff(self):
            with patch(self.view) as mock_view:
                ?

我担心self将引用TestCase实例,我对如何修补with patch(thing) as name部分感到困惑。 我可以修补视图或视图实例的方法,但无论哪种方式,我都不知道假函数将如何正确设置视图attribute和{{ 1}},而不是测试用例。

1 个答案:

答案 0 :(得分:1)

_get_data上修补BaseView方法,让side_effect在视图上设置相应的实例变量。

class MyTests(TestCase):

    def setUp(self):
        self.view = BaseView
        with patch.object(self.view, '_get_data', side_effect=view_data_mock):
            self.view_instance = self.view()

    def test_stuff(self):
        self.assertEqual([], self.view_instance.attribute)
        self.assertTrue(self.view_instance.thing)

def view_data_mock(view):
    view.attribute = []
    view.thing = True