Skip to content

Commit

Permalink
Added more usage documentation to gh-pages
Browse files Browse the repository at this point in the history
  • Loading branch information
mrbean-bremen committed Feb 6, 2018
1 parent 6065596 commit dac3479
Show file tree
Hide file tree
Showing 4 changed files with 143 additions and 19 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ pyfakefs works with Linux, Windows and MacOS.
This file provides general usage instructions for pyfakefs. There is more:

* The [Release pyfakefs API Reference](http://jmcgeheeiv.github.io/pyfakefs/release)
contains documentation for each pyfakefs class, method and function for the last version released on PyPi
contains usage documentation for pyfakefs and a description of the
most relevent classes, methods and functions for the last version released on PyPi
* The [Development pyfakefs API Reference](http://jmcgeheeiv.github.io/pyfakefs/master)
contains the same documentation for the current master branch
* The [pyfakefs Wiki](https://github.com/jmcgeheeiv/pyfakefs/wiki/Home) provides more detailed information on
Expand Down
2 changes: 1 addition & 1 deletion docs/modules.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Fake filesystem classes
-----------------------
.. autoclass:: pyfakefs.fake_filesystem.FakeFilesystem
:members: add_mount_point,
get_disk_usage, set_disk_usage, change_disk_usage,
get_disk_usage, set_disk_usage,
add_real_directory, add_real_file, add_real_paths,
create_dir, create_file, create_symlink

Expand Down
147 changes: 134 additions & 13 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,26 @@ There are several approaches to implementing tests using ``pyfakefs``.

Patch using fake_filesystem_unittest
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you are using the ``python unittest`` package, the easiest approach is to use test classes
derived from ``fake_filesystem_unittest.TestCase``.
If you are using the Python ``unittest`` package, the easiest approach is to
use test classes derived from ``fake_filesystem_unittest.TestCase``.

This allows ``pyfakefs`` to automatically find all real file functions and
modules, and stub these out with the fake file system functions and modules.
If you call ``setUpPyfakefs()`` in your ``SetUp()``, ``pyfakefs`` will
automatically find all real file functions and modules, and stub these out
with the fake file system functions and modules:

.. code:: python
from fake_filesystem_unittest import TestCase
class ExampleTestCase(TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_create_file(self):
file_path = '/test/file.txt'
self.assertFalse(os.path.exists(file_path))
self.fs.create_file(file_path)
self.assertTrue(os.path.exists(file_path))
The usage is explained in more detail in the ``pyfakefs`` wiki page
`Automatically find and patch file functions and modules <https://github.com/jmcgeheeiv/pyfakefs/wiki/Automatically-find-and-patch-file-functions-and-modules>`__
Expand Down Expand Up @@ -80,30 +95,38 @@ patching does not work for some module.
*Note for PyTest users:* if you need these arguments in ``PyTest``, you have to
use ``Patcher`` directly instead of the ``fs`` fixture. Alternatively, you can
add your own fixture with the needed parameters (see ``pytest_plugin.py``
for the implementation).
for a possible implementation).

modules_to_reload
~~~~~~~~~~~~~~~~~
This allows to pass a list of modules that shall be reloaded, thus allowing
to patch modules not imported directly.

Pyfakefs automatically patches modules only if they are imported directly, e.g:

.. code:: python
import os
import pathlib.Path
The following imports of ``os`` and ``pathlib.Path`` will not be patched by
``pyfakefs`` directly:
``pyfakefs``, however:

.. code:: python
import os as my_os
from pathlib import Path
.. note:: There is one exception to that: importing ``os.path`` like
``from os import path`` will work, because it is handled by ``pyfakefs``
(see also ``patch_path`` below).

If adding the module containing these imports to ``modules_to_reload``, they
will be correctly patched.
Ther is one exception to that: importing ``os.path`` like
``from os import path`` will works, because it is handled by ``pyfakefs``
(see also ``patch_path`` below).

modules_to_patch
~~~~~~~~~~~~~~~~
This also allows patching modules that are not patched out of the box, i
This also allows patching modules that are not patched out of the box, in
this case by adding a fake module implementation for a module name. The
argument is a dictionary of fake modules mapped to the names to be faked.
This can be used to fake modules imported as another name directly. For the
Expand All @@ -122,7 +145,9 @@ different:
with Patcher(modules_to_patch={'pathlib.Path': MyFakePath}):
test_something()
Here is an example how to implement ``MyFakePath``:
This will fake the class ``Path`` inside the module ``pathlib``, if imported
as ``Path``.
Here is an example of how to implement ``MyFakePath``:

.. code:: python
Expand All @@ -144,8 +169,8 @@ Here is an example how to implement ``MyFakePath``:
patch_path
~~~~~~~~~~
This is True by default, meaning that modules named ``path`` are patched as
``os.path``. If this clashes with another module of the same name, it can be switched
off (and imports like ``from os import path`` will not be patched).
``os.path``. If this clashes with another module of the same name, it can be
switched off (and imports like ``from os import path`` will not be patched).


additional_skip_names
Expand All @@ -159,3 +184,99 @@ use_dynamic_patch
If ``True`` (the default), dynamic patching after setup is used (for example
for modules loaded locally inside of functions).
Can be switched off if it causes unwanted side effects.

Using convenience methods
-------------------------
While ``pyfakefs`` can be used just with the standard Python file system
functions, there are few convenience methods in ``fake_filesystem`` that can
help you setting up your tests. The methods can be accessed via the
``fake_filesystem`` instance in your tests: ``Patcher.fs``, the ``fs``
fixture in PyTest, or ``TestCase.fs``.

File creation helpers
~~~~~~~~~~~~~~~~~~~~~
To create files, directories or symlinks together with all the directories
in the path, you may use ``create_file()``, ``create_dir()`` and
``create_symlink()``, respectively.

``create_file()`` also allows you to set the file mode and the file contents
together with the encoding if needed. Alternatively, you can define a file
size without contents - in this case, you will not be able to perform
standard I\O operations on the file (may be used to "fill up" the file system
with large files).

.. code:: python
from fake_filesystem_unittest import TestCase
class ExampleTestCase(TestCase):
def setUp(self):
self.setUpPyfakefs()
def test_create_file(self):
file_path = '/foo/bar/test.txt'
self.fs.create_file(file_path, contents = 'test')
with open(file_path) as f:
self.assertEqual('test', f.read())
``create_dir()`` behaves like ``os.makedirs()``, but can also be used in
Python 2.

Access to files in the real file system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you want to have read access to real files or directories , you can map
them into the fake file system using ``add_real_file()``,
``add_real_directory()`` and ``add_real_paths()``. They take a file path, a
directory path, or a list of paths, respectively, and make them accessible
from the fake file system. By default, the contents of the mapped files and
directories are read only on demand, so that mapping them is relatively
cheap. The access to the files is by default read-only, but even even if you
add them using ``read_only=False``, the files are written only in the fake
system (e.g. in memory). The real files are never changed.

.. code:: python
from fake_filesystem_unittest import TestCase
class ExampleTestCase(TestCase):
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures')
def setUp(self):
self.setUpPyfakefs()
# make the file accessible in the fake file system
self.fs.add_real_directory(self.templates_dirname)
def test_using_fixture1(self):
with open(os.path.join(self.fixture_path, 'fixture1.txt') as f:
# file contents are copied to the fake file system
# only at this point
contents = f.read()
Setting the file system size
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you need to know the file system size in your tests (for example for
testing cleanup scripts), you can set the fake file system size using
``set_disk_usage()``. By default, this sets the total size in bytes of the
root partition; if you add a path as parameter, the size will be related to
the mount point (or drive under Windows) the path is related to.
By default, the size of the fake file system is considered infinite. As soon
as you set a size, all files will occupy the space according to their size,
and you may fail to create new files if the fake file system is full.
.. code:: python
from fake_filesystem_unittest import TestCase
class ExampleTestCase(TestCase):
def setUp(self):
self.setUpPyfakefs()
self.fs.set_disk_usage(100)
def test_disk_full(self):
with open('/foo/bar.txt', 'w') as f:
self.assertRaises(OSError, f.write, 'a' * 200)
To get the file system size, you may use ``get_disk_usage()``, which is
modeled after ``shutil.disk_usage()``.
10 changes: 6 additions & 4 deletions pyfakefs/fake_scandir.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@


class DirEntry(object):
"""Emulates os.DirEntry. Note that we did not enforce keyword only arguments."""
"""Emulates os.DirEntry. Note that we did not enforce keyword only
arguments."""

def __init__(self, filesystem):
"""Initialize the dir entry with unset values.
Expand Down Expand Up @@ -239,9 +240,10 @@ def do_walk(top_dir, top_most=False):

class FakeScanDirModule(object):
"""Uses FakeFilesystem to provide a fake `scandir` module replacement.
Note:
The `scandir` function is a part of the standard `os` module since Python 3.5,
this class handled the the separate `scandir` module that is available on pypi.
.. Note:: The ``scandir`` function is a part of the standard ``os`` module
since Python 3.5. This class handles the separate ``scandir`` module
that is available on pypi.
You need a fake_filesystem to use this:
`filesystem = fake_filesystem.FakeFilesystem()`
Expand Down

0 comments on commit dac3479

Please sign in to comment.