Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Verifying constructor calling another constructor

I want to verify Foo() calls Bar() without actually calling Bar(). And then I want to verify that obj is assigned with whatever Bar() returns.

I tried the following:

class Bar:
    def __init__(self, a):
        print(a)

class Foo:
    def __init__(self):
        self.obj = Bar(1)

###

import pytest
from unittest.mock import Mock, patch
from mod import Foo, Bar

@pytest.fixture # With stdlib
def mock_bar():
    with patch('mod.Bar') as mock:
        yield mock

def test_foo(mock_bar):
    result = Foo()
    mock_bar.assert_called_once_with(1)
    assert result.obj == mock_bar

But it would fail and say that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

E       AssertionError: assert <MagicMock na...='5265642864'> == <MagicMock na...='5265421696'>
E         Full diff:
E         - <MagicMock name='Bar' id='5265421696'>
E         ?                                 ^ ^^
E         + <MagicMock name='Bar()' id='5265642864'>
E         ?                     ++          +  ^ ^

>Solution :

This line:

assert result.obj == mock_bar

Should be:

assert result.obj == mock_bar.return_value

It is the result of calling Bar which gets assigned in self.obj = Bar(1), not Bar itself.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading