Sh4kE Sh4kE - 5 months ago 9
Python Question

How to mock an object attribute, I can't access?

I'm trying to mock the parser.html_source attribute of the following view in my unit test. I want to overwrite it with a former downloaded html of that page.

views.py:

def parse_online_page(request):
site_manager = SiteManager(Constants.LOGIN)
site_manager.login()
site_manager.change_to_frame(Constants.HEAD)

parser = HeadParser(html_source=site_manager.page_source)
parser.parse()

return redirect('another_page')


Here's my unit test:

TESTDATA_PATH = 'core/tests/assets'


class TestSession(TestCase):
def test_parser_view(self):
with patch('core.parsers.HeadParser') as parser_mock:
with open(os.path.join(TESTDATA_PATH, 'frame_head.html'), encoding='utf8') as f:
parser_mock.html_source = f.read()

response = self.client.get(reverse('core:parse_online_page'))
self.assertEqual(response.status_code, 302)

# assert that my html test asset was parsed correctly


Unfortunatly this does not overwrite the HeadParser's html_source attribute in all instances generated out of this class.

I don't even know if this is the right attribute to mock, I'm totally clueless.

Answer

Remember the advice in the mock documentation: patch where the class is used, not where it is defined. Here that means you should be mocking 'core.views.HeadParser'.

Comments