How to prevent all writes to disk from within python
<p>When doing automated tests, I like to make sure my script does not write any data to the disk. I am doing tests on the script as a whole, not unit tests of individual functions.</p>

<p><strong>Is there a way to intercept all Disk-IO that a python script performs from within this script?</strong></p>

<p>Obviously, I can mock the open function (e.g. with  the mock package <a href="http://www.voidspace.org.uk/python/mock/helpers.html?#mock-open" rel="nofollow">http://www.voidspace.org.uk/python/mock/helpers.html?#mock-open</a> ) but the problem is that I need to know in what module the open happens. I have to mock <code>__main__.open</code> as well as <code>__module1.open</code> and <code>module2.open</code> and so on.
The problem is that I do not know what modules will write to files.</p>

<p>If mocking <code>open</code> is enough, you can stick the mock into the <a href="https://docs.python.org/3/library/builtins.html" rel="nofollow"><code>builtins</code> module</a>; this is the module that is consulted for all built-in functions:</p>

<pre><code>with mock.patch('builtins.open', mock_open()):
    # ...
</code></pre>

<p>In Python 2, the module was called <a href="https://docs.python.org/2/library/__builtin__.html" rel="nofollow"><code>__builtin__</code></a>.</p>

<p>Note that this doesn't necessarily catch all writes; anything that uses <code>os.open()</code> to use OS filehandles directly or uses <code>io.open()</code> or <code>codecs.open()</code> could still end up writing to disk.</p>

python