A stricter mock object cannot be a bad idea :-) I am not sure about your proposed API: some random code may already use this attribute. Maybe it can be a seal (mock) function which sets a secret attribute with a less common name?

Yeah, please open an issue on bugs.python.org ;-)


Le 29 mai 2017 11:33 PM, "Mario Corchero" <mariocj89@gmail.com> a écrit :
Hello Everyone!

First time writing to python-ideas.

Add a new mock class within the mock module, SealedMock (or RestrictedMock) that allows to restrict in a dynamic and recursive way the addition of attributes to it. The new class just defines a special attribute "sealed" which once set to True the behaviour of automatically creating mocks is blocked, as well as for all its "submocks".
See sealedmock. Don't focus on the implementation, it is ugly, it would be much simpler within mock.py.

Inspired by GMock RestrictedMock, SealedMock aims to allow the developer to define a narrow interface to the mock that defines what the mocks allows to be called on.
The feature of mocks returning mocks by default is extremely useful but not always desired. Quite often you rely on it only at the time you are writing the test but you want it to be disabled at the time the mock is passed into your code, that is what SealedMock aims to address.

This solution also prevents user errors when mocking incorrect paths or having typos when calling attributes/methods of the mock.
We have tried it internally in our company and it gives quite a nicer user experience for many use cases, specially for new users of mock as it helps out when you mock the wrong path.

  • Using auto_spec/spec is a possible solution but removes flexibility and is rather painful to write for each of the mocks and submocks being used.
  • Leaving it outside of the mock.py as it is not interesting enough. I am fine with it :) just proposing it in case you think otherwise.
  • Make it part of the standard Mock base class. Works for me, but I'd concerned on how can we do it in a backward compatible way. (Say someone is mocking something that has a "sealed" attribute already).
Let me know what you think, happy to open a enhancement in https://bugs.python.org/ and send a PR.


Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/