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

Ben Finney ben+python at benfinney.id.au
Wed Jan 27 23:57:23 EST 2016


boB Stepp <robertvstepp at gmail.com> writes:

> I don't want to mess with what will become the program's *real*
> classifiers.txt (And other needed text files to come, that will
> likewise be editable.), so how do I simulate these various needed file
> operations in a way that tests the actual program code, but without
> touching the actual data files?

This is a common requirement: you want to test using fake filesystem
entries, but *only* for certain filesystem entries. Other filesystem
access should go through to the real filesystem as normal.

> I was looking at "How to Mock Python's `open` function" at
> http://www.ichimonji10.name/blog/6/, which looks potentially
> promising, but looks complicated.

Not only that, but filesystem access is especially problematic for
running unit test suites: the invocation of test cases will itself often
require real access to the filesystem, so fiddling with that inside your
test case will make test failures much more difficult to debug.

Common solutions include “ehhh, don't bother making test doubles for the
filesystem then”, or “let the tests access loads of real files and hang
the drain on speed”, or other unsatisfactory compromises.


Would you – would other readers here – be sufficiently interested to
work with me on refining a small library I wrote to address this
problem?

I haven't yet created a published project for it, but it would probably
benefit from real-world use in more than the single code base I needed
it for. If I could know there will be several people benefiting and
providing feedback, that would be motivation to work on it further.

-- 
 \      “An expert is a man who has made all the mistakes which can be |
  `\                         made in a very narrow field.” —Niels Bohr |
_o__)                                                                  |
Ben Finney



More information about the Tutor mailing list