[TIP] Creating fake filesystem entries for testing a program (was: mocking a file in /proc)

Ben Finney ben+python at benfinney.id.au
Tue May 9 16:43:51 PDT 2017

David Palao <dpalao.python at gmail.com> writes:

> But when it comes to functional tests (or acceptance tests), I'm not
> testing a *single* function of my code. I'm doing kind of a global
> black-box test to ensure that the user will get the expected result.

You are correct that those tests are not unit tests (because they are
not testing code units separately; they test the system ad a much larger

> And I want to do provide the correct result under different
> conditions. Therefore I need to find a way to provide a fake
> environment for my (functional, acceptance, black-box) tests.

That will be special to the system you're testing. But there are
commonalities among many such programs; the example that started this
thread – isolating the program from a specific filesystem and providing
an instrumented, fake filesystem in its place – is a common requirement.

The standard library contains ‘unittest.mock’ for creating mock objects
<URL:https://docs.python.org/3/library/unittest.mock.html>. This can be
used even if you're not writing unit tests.

Specifically, because “open a file from the filesystem” is something the
test framework *iteself* needs to do, it can be tricky to fake that. The
library has ‘unittest.mock.mock_open’ which makes it easier

> What I understand about TDD is that although the speed of execution of
> the tests is important, speed means nothing if correctness is
> sacrificed. So if I want to simulate a situation where some file has
> different contents in it, I need to test the program in an environment
> where that file has those different values. I don't see a way around
> it.

You're right. Providing a fake environment under control of the test
case, to set up controlled conditions and observe the program's
behaviour, is a normal and necessary part of testing.

If you want to get more precise and have more instruments on the fake
filesystem objects, you might try the Gajja library

I haven't worked on it for a while, and I'd love to receive a start at
API documentation, but it does have a brief tutorial.

 \      “The opposite of a correct statement is a false statement. But |
  `\     the opposite of a profound truth may well be another profound |
_o__)                                              truth.” —Niels Bohr |
Ben Finney

More information about the testing-in-python mailing list