File: README.md

package info (click to toggle)
python-mock-open 1.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 152 kB
  • sloc: python: 842; makefile: 6; sh: 4
file content (57 lines) | stat: -rw-r--r-- 2,345 bytes parent folder | download
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
=========
[![PyPI version](https://badge.fury.io/py/mock-open.svg)](https://pypi.python.org/pypi/mock-open/)
[![Build Status](https://travis-ci.org/nivbend/mock-open.svg?branch=master)](https://travis-ci.org/nivbend/mock-open)
[![GitHub license](https://img.shields.io/github/license/nivbend/mock-open.svg)](https://github.com/nivbend/mock-open/blob/master/LICENSE)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/nivbend/mock-open/graphs/commit-activity)
[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](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