[Tutor] How do I test file operations (Such as opening, reading, writing, etc.)?

Ben Finney ben+python at benfinney.id.au
Fri Jan 29 02:09:58 EST 2016


"Martin A. Brown" <martin at linux-ip.net> writes:

> Option A (tempfile):
>
>   Create a directory and copy your pristine tree into the directory
>   and make the base directory for the important data files
>   configurable. Also known as parameterization.

I consider that a poor option; real files complicate the test setup and
cleanup, they are always going to be slower, and they can lead to false
positives and false negatives in the test results.

All of those will act as a disincentive to add lots of unit tests for
filesystem-related areas of your code; and I think that's a disincentive
we don't need.

> Option D (use StringIO):
>
>   If you are less concerned about filesystem interactions and really 
>   just want an individual thingy that that behaves like a file, but 
>   can be constructed in memory, use StringIO (or cStringIO).

These are great if you can get away with them. But many programs use not
just file objects, but also interrogate the filesystem: they use
`os.stat`, `os.path.exists`, builtin `open`, etc.

We need to be able to control not only the in-memory file objects, but
the filesystem access for our fake files that don't actually exist on
the real filesystem.

> Option C (use pyfakefs):
>
>   Use pyfakefs, which acts like a filesystem for testing purposes.
>   https://pypi.python.org/pypi/pyfakefs
>   https://github.com/jmcgeheeiv/pyfakefs

I have today published a different approach, which I designed for one
code base ad is to date its only user. I'm looking for more feedback.

    <URL:https://pypi.python.org/pypi/gajja/>

See the ‘doc/tutorial.txt’ for a worked example of how it can be useful.
(and I'm still writing more documentation for general use.)

-- 
 \           “I do not believe in immortality of the individual, and I |
  `\        consider ethics to be an exclusively human concern with no |
_o__)  superhuman authority behind it.” —Albert Einstein, letter, 1953 |
Ben Finney



More information about the Tutor mailing list