Quantcast
Channel: Jeremy Satterfield
Viewing all articles
Browse latest Browse all 39

Mocking a property in Python

$
0
0

Anytime I see someone turning an instance method into a property on a Python object, I always have to step back and rethink whether it's really the right thing to do. While properties certain have valid use cases, I often see them overused and misused. This can result in code that is harder to refactor should you decide you actually do want to accept arguments as well as less straight forward to separate in unit tests.

The way I found to deal with the latter case is pretty simple but unituitive at first. Simply stub out the property on the class, then assign the property value on the instance.

# Use __class__ if you don't have the class imported
self.mox.StubOutWithMock(self.book.__class__, 'reviews')
self.book.editors = ['editor 1', 'editor 2']
# replace with a MockAnything to go deeper
self.mock.StubOutWithMock(Company, 'employees')
Company.employees = self.mock.CreateMockAnything()
company.employees.are_executives().AndReturn(['CEO', 'COO', 'CIO'])
campaign3.reviews.are_developers().AndReturn(['Jim', 'John', 'Joey'])

Viewing all articles
Browse latest Browse all 39

Trending Articles