[TIP] Is this the best way to mock out a call to with open('foo') as f?

Michael Foord fuzzyman at voidspace.org.uk
Sat Oct 2 15:14:02 PDT 2010

  On 02/10/2010 22:31, Gregory P. Smith wrote:
> [snip...]
> 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,


> -gps
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


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...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20101002/8647d988/attachment.htm>

More information about the testing-in-python mailing list