How to use the pyfakefs.fake_filesystem_unittest function in pyfakefs

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 airbnb / streamalert / tests / unit / streamalert / shared / test_config.py View on Github external
def get_mock_lambda_context(func_name, milliseconds=100):
    """Helper function to create a fake context object using Mock"""
    arn = 'arn:aws:lambda:us-east-1:123456789012:function:{}:development'
    context = Mock(
        invoked_function_arn=(arn.format(func_name)),
        function_name=func_name,
        function_version='production',
        get_remaining_time_in_millis=Mock(return_value=milliseconds)
    )

    return context


class TestConfigLoading(fake_filesystem_unittest.TestCase):
    """Test config loading logic with a mocked filesystem."""
    # pylint: disable=protected-access

    def setUp(self):
        self.setUpPyfakefs()

        config_data = basic_streamalert_config()

        mock_cluster_contents = '{"data_sources": {}, "modules": {"streamalert": {"foo": "bar"}}}'

        # Add config files which should be loaded
        self.fs.create_file('conf/clusters/prod.json', contents=mock_cluster_contents)
        self.fs.create_file('conf/clusters/dev.json', contents=mock_cluster_contents)
        self.fs.create_file('conf/global.json', contents='{}')
        self.fs.create_file('conf/lambda.json', contents='{}')
        self.fs.create_file('conf/logs.json', contents='{}')
github LD250 / jenkins-cli-python / tests / test_cli.py View on Github external
host_from_file = 'http://low.priority.com'
        username = 'username'
        password = 'password'
        read_settings_from_file.return_value = {'host': host_from_file, 'username': username, 'password': password}
        JenkinsCli.auth()
        patched_init.assert_called_once_with(host_from_file, username, password, socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()

        host = 'http://localhost:5055'
        JenkinsCli.auth(host=host)
        patched_init.assert_called_once_with(host, username, password, socket._GLOBAL_DEFAULT_TIMEOUT)
        patched_init.reset_mock()


class TestCliFileUsing(fake_filesystem_unittest.TestCase):
    HOME_FILE_CONTENT = ("host =https://jenkins.host.com\n"
                         "username=   username\n"
                         "some weird settings = value = value")

    LOCAL_FILE_CONTENT = ("host=http://jenkins.localhosthost.ua\n"
                          "username=Denys\n"
                          "password=myPassword\n"
                          "other_setting=some_value")

    def setUp(self):
        self.setUpPyfakefs()

    def test_read_settings_from_file(self):
        current_folder = os.getcwd()
        local_folder_filename = os.path.join(current_folder, JenkinsCli.SETTINGS_FILE_NAME)
        home_folder_filename = os.path.join(os.path.expanduser("~"), JenkinsCli.SETTINGS_FILE_NAME)
github ccbrown / needy / tests / unit / test_project.py View on Github external
import os
from pyfakefs import fake_filesystem_unittest

from needy.platforms import host_platform
from needy.project import Project, ProjectDefinition
from needy.target import Target


class ProjectTest(fake_filesystem_unittest.TestCase):
    def setUp(self):
        self.setUpPyfakefs()

    def test_pre_build_creating_output_directories(self):
        project = Project(ProjectDefinition(Target(host_platform()()), '.'), None)
        project.pre_build(os.path.join('build', 'out'))
        self.assertTrue(os.path.isdir(os.path.join('build', 'out', 'include')))
        self.assertTrue(os.path.isdir(os.path.join('build', 'out', 'lib')))
github creativeprojects / resticprofile / tests / test_filesearch.py View on Github external
import os
from pathlib import Path
import unittest
from pyfakefs import fake_filesystem_unittest

from resticprofile.filesearch import FileSearch, find_configuration_file, get_default_configuration_locations

TEST_FILE = 'test.conf'


class TestFileSearch(fake_filesystem_unittest.TestCase):

    def setUp(self):
        self.setUpPyfakefs()
        os.makedirs(str(Path().home()), exist_ok=True)
        for path in get_default_configuration_locations():
            os.makedirs(path)

    def create_file(self, filename: str):
        with open(filename, 'w') as filehandle:
            filehandle.write("Fake configuration file for testing")

    def test_no_configuration_file(self):
        filepath = find_configuration_file(TEST_FILE)
        self.assertIs(None, filepath)

    def test_configuration_file_in_home_folder(self):
github ThoughtWorksInc / aws_role_credentials / tests / test_actions.py View on Github external
with mock.patch('os.environ') as mock_env:
            mock_env.copy.return_value = {}

            Actions.exec_with_credentials('un-south-1',
                                          'echo hello', token)

            mock_popen.assert_called_with(['echo', 'hello'],
                                          env={'AWS_ACCESS_KEY_ID': 'TEST_ACCESS_KEY',
                                               'AWS_DEFAULT_REGION': 'un-south-1',
                                               'AWS_SECRET_ACCESS_KEY': 'TEST_SECRET_KEY',
                                               'AWS_SESSION_TOKEN': 'TEST_TOKEN'},
                                          shell=False)


class TestConfigActions(fake_filesystem_unittest.TestCase):
    TEST_FILE = "/test/file"

    def setUp(self):
        self.setUpPyfakefs()
        os.mkdir('/test')

    def tearDown(self):
        pass

    def test_credentials_are_generated_from_token(self):
        token = Struct({'credentials':
                        Struct({'access_key': 'SAML_ACCESS_KEY',
                                'secret_key': 'SAML_SECRET_KEY',
                                'session_token': 'SAML_TOKEN',
                                'expiration': 'TEST_EXPIRATION'})})
github cloud4rpi / cloud4rpi / test / test_sensors.py View on Github external
sys.path.insert(0, path.join(root, 'examples/raspberrypi'))

from ds18b20 import DS18b20, InvalidW1Address
import rpi


sensor_10 = \
    '2d 00 4d 46 ff ff 08 10 fe : crc=fe YES' '\n' \
    '2d 00 4d 46 ff ff 08 10 fe : t=22250'

sensor_28 = \
    '2d 00 4d 46 ff ff 08 10 fe : crc=fe YES' '\n' \
    '2d 00 4d 46 ff ff 08 10 fe : t=28250'


class TestDs18b20Sensors(ffut.TestCase):
    def setUp(self):
        self.setUpPyfakefs()
        self.setUpSensors()

    def setUpSensors(self):
        self.setUpSensor('10-000802824e58', sensor_10)
        self.setUpSensor('28-000802824e58', sensor_28)

    def setUpSensor(self, address, content):
        self.fs.CreateFile(
            '/sys/bus/w1/devices/{0}/w1_slave'.format(address),
            contents=content
        )

    def testFindDSSensors(self):
        sensors = DS18b20.find_all()
github ThoughtWorksInc / aws_role_credentials / tests / test_acceptance.py View on Github external
if sys.version_info < (2, 7):
    import unittest2 as unittest
else:
    import unittest

from pyfakefs import fake_filesystem_unittest
import six

from os.path import expanduser
from mock import MagicMock
from tests.helper import saml_assertion, read_config_file, Struct
from aws_role_credentials import cli
from six.moves import StringIO


class TestAcceptance(fake_filesystem_unittest.TestCase):
    HOME = expanduser('~/')
    TEST_FILE = os.path.join(HOME, '.aws/credentials')

    def setUp(self):
        self.patcher = mock.patch('aws_role_credentials.cli.configurelogging')
        self.patcher.start()

        self.setUpPyfakefs()
        if not os.path.exists(self.HOME):
            os.makedirs(self.HOME)

    def tearDown(self):
        self.patcher.stop()
        pass

    @mock.patch('aws_role_credentials.actions.boto.sts')