3

I am trying to patch a function of a view within a TestCase in django. I have a class:

class BaseView(View):

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

I need to mock out self.attribute to an empty list like:

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

An issue is that I'm within a test case like:

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:
                ?

I fear the self is going to refer to the TestCase instance, and I'm confused on how to patch in the with patch(thing) as name part. I could patch the view's or the view instance's method, but either way I don't know how the fake function will correctly set the view's attribute and thing, not the test cases.

halfer
  • 19,824
  • 17
  • 99
  • 186
codyc4321
  • 9,014
  • 22
  • 92
  • 165
  • 1
    Have you tried patching `fancy_stuff` to return an empty list? – magni- Apr 06 '16 at 09:14
  • tried that and realized I have to patch both things `_get_data` does – codyc4321 Apr 06 '16 at 17:01
  • 1
    You can name that `self` variable whatever you want. It being called `self` is just a convention. If you like, name it `this`, or `that`, or `whatever`. – poke Apr 06 '16 at 17:14
  • either way it sets the TestCase instance the attributes, not the view. See how `self.thing` should be set on `BaseView`, but patching within the test class has them set on the test class – codyc4321 Apr 06 '16 at 19:36
  • 1
    @codyc4321 I added an answer below, lemme know if it works / if you have other questions – magni- Apr 08 '16 at 08:27
  • i tried yesterday and it did work, ty – codyc4321 Apr 08 '16 at 16:25

1 Answers1

1

Patch the _get_data method on BaseView to have a side_effect that sets the appropriate instance variables on the view.

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
magni-
  • 1,934
  • 17
  • 20