"Virtual" file system mock object - replacing stuff in __builtins__

Peter Hansen peter at engcorp.com
Fri Mar 5 10:19:37 EST 2004


Remy Blank wrote:

> As a fan of TDD (test-driven development), I use the unittest module to 
> write the test cases for these tools. However, to make the test cases 
> independent of the file system environment, I simulate a file system 
> tree with a mock object using the following technique (sorry for the 
> long posting):
> [snip code]
> Now my questions:
>  - Am I doing something fundamentally forbidden (replacing stuff in 
> existing modules like __builtins__ or os)?
>  - Is there a better way of achieving the same result?
>  - If the technique is generally useful, would there be interest in 
> having a full-featured "virtual" file system mock object? I couldn't 
> find anything similar on Google.

It's not fundamentally forbidden to stick things in __builtins__, or 
even other standard modules, but it's rarely necessary and might be 
subject to a future ban if those people who periodically discuss 
disallow assignments to __builtins__ have their way and forget about 
those of us who need the technique for testing.

Nevertheless, if you are really doing things in a test-driven fashion, 
it should not be necessary to use __builtins__, if the open() calls and 
such are in your own code.  In that case just create a reference to your 
mock file system methods in the module under test, using the names 
"open" and "stat" and so forth, and they will shadow the __builtin__ 
names.  (Locals are found first, then globals, then builtins.)

I don't know of a better way of doing this, and in fact we've built our 
own mock file system in several different projects, in a limited fashion.

The idea of a standardized or at least widely used "full-featured" 
virtual file system is an excellent one!  Writing tests that rely on the 
real filesystem can be awkward and is probably one of the many small 
things stopping/slowing some people from adopting TDD more.

-Peter



More information about the Python-list mailing list