1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
mock-open
=========
[](https://pypi.python.org/pypi/mock-open/)
[](https://travis-ci.org/nivbend/mock-open)
[](https://github.com/nivbend/mock-open/blob/master/LICENSE)
[](https://GitHub.com/nivbend/mock-open/graphs/commit-activity)
[](http://makeapullrequest.com)
A better mock for file I/O.
Install
-------
```
$ pip install mock-open
```
class `MockOpen`
----------------
The `MockOpen` class should work as a stand-in replacement for [`mock.mock_open`][mock-open] with
some added features (though it tries to conform to how the builtin `open` works where the two
differ):
* Multiple file support, including a mapping-like access to file mocks by path:
```python
from mock_open import MockOpen
mock_open = MockOpen()
mock_open["/path/to/file"].read_data = "Data from a fake file-like object"
mock_open["/path/to/bad_file"].side_effect = IOError()
```
You can also configure behavior via the regular `mock` library API:
```python
mock_open = MockOpen()
mock_open.return_value.write.side_effect = IOError()
```
* Persistent file contents between calls to `open`:
```python
with patch("builtins.open", MockOpen()):
with open("/path/to/file", "w") as handle:
handle.write("Some text")
with open("/path/to/file", "r") as handle:
assert "Some text" == handle.read()
```
* All the regular file operations: `read`, `readline`, `readlines`, `write`, `writelines`, `seek`,
`tell`.
Acknowledgements
----------------
This library uses modified versions of tests from the [CPython source code][CPython] as part of its
test suite. The original tests are licensed under the [PSF license agreement][PSF License] and are
copyright of the Python Software Foundation.
[mock-open]: http://docs.python.org/library/unittest.mock.html#mock-open
[CPython]: https://github.com/python/cpython
[PSF License]: https://docs.python.org/license.html#terms-and-conditions-for-accessing-or-otherwise-using-python
|