lundi 20 août 2018

Use a MagicMock as its own return value?

Normally, a MagicMock returns new MagicMocks for any attribute or method called on it:

>>> mm = MagicMock()
>>> mm
<MagicMock id='140094558921616'>
>>> mm()
<MagicMock name='mock()' id='140094551215016'>
>>> mm.foo()
<MagicMock name='mock.foo()' id='140094551605656'>

Lately, I've been writing fixtures that instead return the same mock for all methods and attributes on the mocked class:

>>> mm = MagicMock()
>>> mm.return_value = mm
>>> mm.foo.return_value = mm
>>> mm
<MagicMock id='140094551638984'>
>>> mm()
<MagicMock id='140094551638984'>
>>> mm.foo()
<MagicMock id='140094551638984'>

This has been convenient, as my fixture can simply yield this single mock and multiple assertions can be run against it. I have not seen any downsides: the called,call_count, and call_args attributes continue to work accurately for each of the mocked attributes.

However, the fact that MagicMock doesn't work this way out of the box makes me feel like I might be missing something.

Is this a bad idea?

Aucun commentaire:

Enregistrer un commentaire