How to use pyfakefs - 10 common examples

To help you get started, we’ve selected a few pyfakefs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github opencord / xos / xos / coreapi / test_backupsetwatcher.py View on Github external
if name:
        # Can't pass "name" in as an arg to MagicMock
        newmodel.name = name
    vars_dict[var_name] = newmodel
    return newmodel


class MockServer(object):
    def __init__(self):
        super(MockServer, self).__init__()

    def delayed_shutdown(self, seconds):
        pass


class TestBackupWatcher(fake_filesystem_unittest.TestCase):
    def setUp(self):
        config = os.path.abspath(
            os.path.dirname(os.path.realpath(__file__)) + "/test_config.yaml"
        )
        Config.clear()  # in case left unclean by a previous test case
        Config.init(config)

        self.mock_backup_operation = MagicMock()
        self.mock_backup_file = MagicMock()

        sys.modules["core"] = Mock()
        sys.modules["core.models"] = Mock(BackupOperation=self.mock_backup_operation,
                                          BackupFile=self.mock_backup_file)

        # needed because decorators.py imports xos.exceptions
        self.sys_path_save = sys.path
github opencord / xos / xos / coreapi / test_backupprocessor.py View on Github external
import unittest
from mock import MagicMock, patch, ANY, call
from pyfakefs import fake_filesystem_unittest
from io import open

from __builtin__ import True as builtin_True, False as builtin_False

from xosconfig import Config


def mock_make_backup(fn):
    with open(fn, "w") as backup_f:
        backup_f.write("stuff")


class TestBackupProcessor(fake_filesystem_unittest.TestCase):
    def setUp(self):
        config = os.path.abspath(
            os.path.dirname(os.path.realpath(__file__)) + "/test_config.yaml"
        )
        Config.clear()  # in case left unclean by a previous test case
        Config.init(config)

        import backupprocessor
        self.backupprocessor = backupprocessor

        self.setUpPyfakefs()

        self.processor = backupprocessor.BackupProcessor()
        self.mock_backuphandler = MagicMock(backup=MagicMock(), restore=MagicMock())

    def tearDown(self):
github kobayashi / s3monkey / s3monkey / pyfakefs / pytest_plugin.py View on Github external
"""A pytest plugin for using pyfakefs as a fixture

When pyfakefs is installed, the "fs" fixture becomes available.

:Usage:

def my_fakefs_test(fs):
    fs.create_file('/var/data/xx1.txt')
    assert os.path.exists('/var/data/xx1.txt')
"""
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher

Patcher.SKIPMODULES.add(py)  # Ignore pytest components when faking filesystem


@pytest.fixture
def fs(request):
    """ Fake filesystem. """
    patcher = Patcher()
    patcher.setUp()
    request.addfinalizer(patcher.tearDown)
    return patcher.fs
github jmcgeheeiv / pyfakefs / pyfakefs / pytest_plugin.py View on Github external
:Usage:

def my_fakefs_test(fs):
    fs.create_file('/var/data/xx1.txt')
    assert os.path.exists('/var/data/xx1.txt')
"""

import linecache
import tokenize

import py
import pytest

from pyfakefs.fake_filesystem_unittest import Patcher

Patcher.SKIPMODULES.add(pytest)
Patcher.SKIPMODULES.add(py)  # Ignore pytest components when faking filesystem

# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we skip faking the module.
# We also have to set back the cached open function in tokenize.
Patcher.SKIPMODULES.add(linecache)
Patcher.SKIPMODULES.add(tokenize)


@pytest.fixture
def fs(request):
    """ Fake filesystem. """
    if hasattr(request, 'param'):
        # pass optional parameters via @pytest.mark.parametrize
github jmcgeheeiv / pyfakefs / pyfakefs / pytest_plugin.py View on Github external
def my_fakefs_test(fs):
    fs.create_file('/var/data/xx1.txt')
    assert os.path.exists('/var/data/xx1.txt')
"""

import linecache
import tokenize

import py
import pytest

from pyfakefs.fake_filesystem_unittest import Patcher

Patcher.SKIPMODULES.add(pytest)
Patcher.SKIPMODULES.add(py)  # Ignore pytest components when faking filesystem

# The "linecache" module is used to read the test file in case of test failure
# to get traceback information before test tear down.
# In order to make sure that reading the test file is not faked,
# we skip faking the module.
# We also have to set back the cached open function in tokenize.
Patcher.SKIPMODULES.add(linecache)
Patcher.SKIPMODULES.add(tokenize)


@pytest.fixture
def fs(request):
    """ Fake filesystem. """
    if hasattr(request, 'param'):
        # pass optional parameters via @pytest.mark.parametrize
        patcher = Patcher(*request.param)
github SUSE / DeepSea / tests / unit / _modules / test_rgw.py View on Github external
import pytest
import salt.client
import os
import sys
sys.path.insert(0, 'srv/salt/_modules')
from pyfakefs import fake_filesystem, fake_filesystem_glob
from mock import patch, MagicMock
from srv.salt._modules import rgw

fs = fake_filesystem.FakeFilesystem()
f_glob = fake_filesystem_glob.FakeGlobModule(fs)
f_os = fake_filesystem.FakeOsModule(fs)
f_open = fake_filesystem.FakeFileOpen(fs)

class TestRadosgw():

    pass
github googleapis / artman / test / utils / test_github_utils.py View on Github external
@mock.patch.object(github_utils, 'open', side_effect=fake_fs.FakeFileOpen(fs))
@mock.patch('os.access', side_effect=os_module.access)
@mock.patch('os.path.isfile', side_effect=os_module.path.isfile)
@mock.patch('os.path.isdir', side_effect=os_module.path.isdir)
@mock.patch('os.listdir', side_effect=os_module.listdir)
@mock.patch('requests.patch', return_value=_PATCH_RETURN_VAL)
@mock.patch('requests.post', side_effect=_POST_SIDE_EFFECT)
@mock.patch('requests.get', side_effect=_GET_SIDE_EFFECT)
def test_github_utils_task(mock_get, mock_post, mock_patch, mock_listdir,
                           mock_isdir, mock_isfile, mock_access, mock_open):
    github_utils.push_dir_to_github('/', _USERNAME, _PASSWORD, _OWNER,
                                    _REPO, _BRANCH, _MESSAGE)
    mock_get.assert_has_calls(_EXPECTED_GET_ARGS)
    mock_post.assert_has_calls(_EXPECTED_POST_ARGS)
    mock_patch.assert_has_calls(_EXPECTED_PATCH_ARGS)
github SUSE / DeepSea / tests / unit / _modules / test_subvolume.py View on Github external
import pytest
import salt.client
import os
import sys
sys.path.insert(0, 'srv/salt/_modules')
from pyfakefs import fake_filesystem, fake_filesystem_glob
from mock import patch, MagicMock, mock
from srv.salt._modules import subvolume

fs = fake_filesystem.FakeFilesystem()
f_glob = fake_filesystem_glob.FakeGlobModule(fs)
f_os = fake_filesystem.FakeOsModule(fs)
f_open = fake_filesystem.FakeFileOpen(fs)

class Testsubvolume():

    @patch('srv.salt._modules.subvolume._btrfs')
    def test_check_mounted(self, mockb):
        mockb.return_value = [True, True]
        state, msg = subvolume.check()
        assert state == True
        assert msg == "/var/lib/ceph subvolume mounted"

    @patch('srv.salt._modules.subvolume._btrfs')
    def test_check_not_btrfs(self, mockb):
        mockb.return_value = [False, False]
        state, msg = subvolume.check()
        assert state == True
        assert msg == "/ is not btrfs"
github jmcgeheeiv / pyfakefs / tests / test_utils.py View on Github external
def setUp(self):
        self.cwd = os.getcwd()
        if not self.use_real_fs():
            self.filesystem = fake_filesystem.FakeFilesystem(
                path_separator=self.path_separator())
            self.open = fake_filesystem.FakeFileOpen(self.filesystem)
            self.os = fake_filesystem.FakeOsModule(self.filesystem)
            self.create_basepath()
        self.setUpFileSystem()
github SUSE / DeepSea / tests / unit / runners / test_push.py View on Github external
fs.CreateFile('policy.cfg_ml_commented',
              contents=('# a line comment\n'
                        'cluster-ceph/cluster/*.sls \t# with a comment'))
fs.CreateFile('policy.cfg_leading_whitespace',
              contents=(' cluster-ceph/cluster/*.sls'))
fs.CreateFile('policy.cfg_trailing_whitespace',
              contents=('cluster-ceph/cluster/*.sls '))
fs.CreateFile('policy.cfg_trailing_and_leading_whitespace',
              contents=(' cluster-ceph/cluster/*.sls '))
fs.CreateFile('policy.cfg_trailing_and_leading_whitespace_and_leading_comment',
              contents=(' #cluster-ceph/cluster/*.sls '))
fs.CreateFile('policy.cfg_trailing_and_leading_whitespace_and_trailing_comment',
              contents=(' cluster-ceph/cluster/*.sls #'))

f_glob = fake_glob.FakeGlobModule(fs)
f_os = fake_fs.FakeOsModule(fs)
f_open = fake_fs.FakeFileOpen(fs)


class TestPush():

    @patch('glob.glob', new=f_glob.glob)
    def test_parse(self):

        parsed = push._parse('{}/*.sls'.format(proposal_dir))
        assert len(parsed) == len(nodes)

        parsed = push._parse('{}/mon*.sls'.format(proposal_dir))
        assert len(parsed) == len([n for n in nodes if n.startswith('mon')])

        parsed = push._parse('{}/mon[1,2].sls'.format(proposal_dir))
        assert len(parsed) == 2