I'm trying to Mock a class using pytest-mock but I don't quite understand how to do it, even after reading articles everywhere.
The thing is I have a class called Model
which one of the attributes returns a list of other elements of different objects inside the model Line
, Square
, Circle
, etc. The Model
is generated by reading a huge file and it will be used in many places throughout the application, so I turned into mocking it, because in this phase I just want to check if it works as expected.
I'm using pytest-mock
, but it's not very clear for me. I've tried:
def test_parse_find_elements_by_name(parser, mocker):
def mock_objects(self):
return ["a","b","c"]
model = Model()
mocker.patch(
"orcaflow.Model.objects",
mock_objects
)
assert model.objects == ["a", "b", "c"]
But it returns a method
, not an attribute (with the @property decorator). A work around was to use the mock
package by itself:
@pytest.fixture
def mocked_model(mocker):
objects = []
for i in range(10):
obj = MagicMock()
obj.name = "Line %d" % i
objects.append(obj)
model = Mock(objects = objects )
return model
Is there a way to do it directly with pytest-mock or some way smarter to do it?