Sh4kE Sh4kE - 1 year ago 76
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.

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

parser = HeadParser(html_source=site_manager.page_source)

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 =

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 Source

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'.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download