[TIP] Is this the best way to mock out a call to with open('foo') as f?
fuzzyman at voidspace.org.uk
Sat Oct 2 15:14:02 PDT 2010
On 02/10/2010 22:31, Gregory P. Smith wrote:
> I tend to dislike mocking out anything in __builtins__ as that can
> really interfere with other code including code in the test harness at
> times depending on what exactly it is doing.
> When possible, assuming you control the code that is being tested, I
> recommend refactoring the original code as such:
> def to_html(self, filepath, _open=open):
> with _open(...) as x:
> To test this method, pass in your own fake or mock open function that
> returns an appropriate stringio for testing that you can validate the
> contents of later.
I *really* dislike this kind of dependency injection when it is just
done for testability. To paraphrase an ex-colleague of mine on this
topic: "you're screwing with your public interfaces".
Seriously though, what arguments a function / method takes is part of
the documentation (or contract) of how it is intended to be used. If
dependency injection is needed or useful for the application structure
then it can be quite elegant, but in Python it just isn't *necessary* to
use dependency injection for testability.
I'll follow up with specific comments about the use of mock in another
All the best,
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
READ CAREFULLY. By accepting and reading this email you agree,
on behalf of your employer, to release me from all obligations
and waivers arising from any and all NON-NEGOTIATED agreements,
licenses, terms-of-service, shrinkwrap, clickwrap, browsewrap,
confidentiality, non-disclosure, non-compete and acceptable use
policies ("BOGUS AGREEMENTS") that I have entered into with your
employer, its partners, licensors, agents and assigns, in
perpetuity, without prejudice to my ongoing rights and privileges.
You further represent that you have the authority to release me
from any BOGUS AGREEMENTS on behalf of your employer.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the testing-in-python