ddd
ddd

Reputation: 5029

How to mock nested properties with PropertyMock

I am trying to mock a property of a property from the return value of a library function mlflow.get_run(run_id).data.metrics. I know how to mock a single layer like this:

m = mock.MagicMock(spec_set=mlflow.get_run)
type(m).metrics = mock.PropertyMock(side_effect=[1, 2])
print(m.metrics)
print(m.metrics)

###output
1
2

If I mock the nested property though I got error "MagicMock has no attribute 'data'"

type(m).data.metrics = mock.PropertyMock(side_effect=[1, 2])

What is the correct way to mock nested properties?

Upvotes: 0

Views: 1050

Answers (1)

D Malan
D Malan

Reputation: 11434

You need to basically repeat what you did for m and data. Set the return_value of the data property to another MagickMock and then set its type to PropertyMock.

from unittest import mock

m = mock.MagicMock(spec_set=mlflow.get_run)
type(m).data = mock.PropertyMock(return_value=mock.MagicMock())
type(type(m).data).metrics = mock.PropertyMock(side_effect=[1, 2])

print(m.data.metrics)
# 1
print(m.data.metrics)
# 2

Upvotes: 1

Related Questions