示例#1
0
    def __init__(self,
                 additional_skip_names=None,
                 modules_to_reload=None,
                 modules_to_patch=None,
                 allow_root_user=True,
                 use_known_patches=True):
        """For a description of the arguments, see TestCase.__init__"""

        if not allow_root_user:
            # set non-root IDs even if the real user is root
            set_uid(1)
            set_gid(1)

        self._skipNames = self.SKIPNAMES.copy()
        # save the original open function for use in pytest plugin
        self.original_open = open
        self.fake_open = None

        if additional_skip_names is not None:
            skip_names = [
                m.__name__ if inspect.ismodule(m) else m
                for m in additional_skip_names
            ]
            self._skipNames.update(skip_names)

        self._fake_module_classes = {}
        self._class_modules = {}
        self._init_fake_module_classes()

        self.modules_to_reload = modules_to_reload or []

        if use_known_patches:
            modules_to_patch = modules_to_patch or {}
            modules_to_patch.update(get_modules_to_patch())
            self._class_modules.update(get_classes_to_patch())
            self._fake_module_classes.update(get_fake_module_classes())

        if modules_to_patch is not None:
            for name, fake_module in modules_to_patch.items():
                self._fake_module_classes[name] = fake_module

        self._fake_module_functions = {}
        self._init_fake_module_functions()

        # Attributes set by _refresh()
        self._modules = {}
        self._fct_modules = {}
        self._def_functions = []
        self._open_functions = {}
        self._stubs = None
        self.fs = None
        self.fake_modules = {}
        self._dyn_patcher = None

        # _isStale is set by tearDown(), reset by _refresh()
        self._isStale = True
        self._patching = False
示例#2
0
def test_update_inits(testdata, etas_file, force, file_exists):
    with Patcher(additional_skip_names=['pkgutil']) as patcher:
        set_uid(0)  # Set to root user for write permission

        fs = patcher.fs

        fs.add_real_file(testdata / 'nonmem/pheno.mod', target_path='run1.mod')
        fs.add_real_file(testdata / 'nonmem/pheno.phi', target_path='run1.phi')
        fs.add_real_file(testdata / 'nonmem/pheno.ext', target_path='run1.ext')
        fs.add_real_file(testdata / 'nonmem/pheno.dta',
                         target_path='pheno.dta')

        with open('run1.mod', 'a') as f:
            f.write(etas_file)

        model = Model('run1.mod')
        update_inits(model, force)
        model.update_source()

        assert ('$ETAS FILE=run1_input.phi' in str(model)) is file_exists
        assert (os.path.isfile('run1_input.phi')) is file_exists
    def __init__(self,
                 additional_skip_names=None,
                 modules_to_reload=None,
                 modules_to_patch=None,
                 allow_root_user=True):
        """For a description of the arguments, see TestCase.__init__"""

        if not allow_root_user:
            # set non-root IDs even if the real user is root
            set_uid(1)
            set_gid(1)

        self._skipNames = self.SKIPNAMES.copy()
        # save the original open function for use in pytest plugin
        self.original_open = open
        self.fake_open = None

        if additional_skip_names is not None:
            skip_names = [
                m.__name__ if inspect.ismodule(m) else m
                for m in additional_skip_names
            ]
            self._skipNames.update(skip_names)

        self.modules_to_reload = [tempfile]
        if modules_to_reload is not None:
            self.modules_to_reload.extend(modules_to_reload)

        # Attributes set by _findModules()

        # IMPORTANT TESTING NOTE: Whenever you add a new module below, test
        # it by adding an attribute in fixtures/module_with_attributes.py
        # and a test in fake_filesystem_unittest_test.py, class
        # TestAttributesWithFakeModuleNames.
        self._fake_module_classes = {
            'os': fake_filesystem.FakeOsModule,
            'shutil': fake_filesystem_shutil.FakeShutilModule,
            'io': fake_filesystem.FakeIoModule,
        }
        if IS_PY2 or IS_PYPY:
            # in Python 2 io.open, the module is referenced as _io
            self._fake_module_classes['_io'] = fake_filesystem.FakeIoModule

        # class modules maps class names against a list of modules they can
        # be contained in - this allows for alternative modules like
        # `pathlib` and `pathlib2`
        self._class_modules = {}
        if pathlib:
            self._class_modules['Path'] = []
            if pathlib:
                self._fake_module_classes[
                    'pathlib'] = fake_pathlib.FakePathlibModule
                self._class_modules['Path'].append('pathlib')
            if pathlib2:
                self._fake_module_classes[
                    'pathlib2'] = fake_pathlib.FakePathlibModule
                self._class_modules['Path'].append('pathlib2')
            self._fake_module_classes[
                'Path'] = fake_pathlib.FakePathlibPathModule
        if use_scandir:
            self._fake_module_classes[
                'scandir'] = fake_scandir.FakeScanDirModule

        if modules_to_patch is not None:
            for name, fake_module in modules_to_patch.items():
                self._fake_module_classes[name] = fake_module

        # handle patching function imported separately like
        # `from os import stat`
        # each patched function name has to be looked up separately
        self._fake_module_functions = {}
        for mod_name, fake_module in self._fake_module_classes.items():
            if (hasattr(fake_module, 'dir')
                    and inspect.isfunction(fake_module.dir)):
                for fct_name in fake_module.dir():
                    module_attr = (getattr(fake_module, fct_name), mod_name)
                    self._fake_module_functions.setdefault(
                        fct_name, {})[mod_name] = module_attr
                    if mod_name == 'os':
                        self._fake_module_functions.setdefault(
                            fct_name, {})[OS_MODULE] = module_attr

        # special handling for functions in os.path
        fake_module = fake_filesystem.FakePathModule
        for fct_name in fake_module.dir():
            module_attr = (getattr(fake_module, fct_name), PATH_MODULE)
            self._fake_module_functions.setdefault(
                fct_name, {})['genericpath'] = module_attr
            self._fake_module_functions.setdefault(
                fct_name, {})[PATH_MODULE] = module_attr

        # Attributes set by _refresh()
        self._modules = {}
        self._fct_modules = {}
        self._open_functions = {}
        self._stubs = None
        self.fs = None
        self.fake_modules = {}
        self._dyn_patcher = None

        # _isStale is set by tearDown(), reset by _refresh()
        self._isStale = True
        self._patching = False
示例#4
0
    def __init__(self,
                 additional_skip_names=None,
                 modules_to_reload=None,
                 modules_to_patch=None,
                 allow_root_user=True,
                 use_known_patches=True,
                 patch_open_code=PatchMode.OFF,
                 patch_default_args=False,
                 use_cache=True):
        """
        Args:
            additional_skip_names: names of modules inside of which no module
                replacement shall be performed, in addition to the names in
                :py:attr:`fake_filesystem_unittest.Patcher.SKIPNAMES`.
                Instead of the module names, the modules themselves
                may be used.
            modules_to_reload: A list of modules that need to be reloaded
                to be patched dynamically; may be needed if the module
                imports file system modules under an alias

                .. caution:: Reloading modules may have unwanted side effects.
            modules_to_patch: A dictionary of fake modules mapped to the
                fully qualified patched module names. Can be used to add
                patching of modules not provided by `pyfakefs`.
            allow_root_user: If True (default), if the test is run as root
                user, the user in the fake file system is also considered a
                root user, otherwise it is always considered a regular user.
            use_known_patches: If True (the default), some patches for commonly
                used packages are applied which make them usable with pyfakefs.
            patch_open_code: If True, `io.open_code` is patched. The default
                is not to patch it, as it mostly is used to load compiled
                modules that are not in the fake file system.
            patch_default_args: If True, default arguments are checked for
                file system functions, which are patched. This check is
                expansive, so it is off by default.
            use_cache: If True (default), patched and non-patched modules are
                cached between tests for performance reasons. As this is a new
                feature, this argument allows to turn it off in case it
                causes any problems.
        """

        if not allow_root_user:
            # set non-root IDs even if the real user is root
            set_uid(1)
            set_gid(1)

        self._skip_names = self.SKIPNAMES.copy()
        # save the original open function for use in pytest plugin
        self.original_open = open
        self.patch_open_code = patch_open_code

        if additional_skip_names is not None:
            skip_names = [
                m.__name__ if inspect.ismodule(m) else m
                for m in additional_skip_names
            ]
            self._skip_names.update(skip_names)

        self._fake_module_classes = {}
        self._unfaked_module_classes = {}
        self._class_modules = {}
        self._init_fake_module_classes()

        # reload tempfile under posix to patch default argument
        self.modules_to_reload = [] if sys.platform == 'win32' else [tempfile]
        if modules_to_reload is not None:
            self.modules_to_reload.extend(modules_to_reload)
        self.patch_default_args = patch_default_args
        self.use_cache = use_cache

        if use_known_patches:
            modules_to_patch = modules_to_patch or {}
            modules_to_patch.update(get_modules_to_patch())
            self._class_modules.update(get_classes_to_patch())
            self._fake_module_classes.update(get_fake_module_classes())

        if modules_to_patch is not None:
            for name, fake_module in modules_to_patch.items():
                self._fake_module_classes[name] = fake_module
        patched_module_names = set(modules_to_patch)
        clear_cache = not use_cache
        if use_cache:
            if patched_module_names != self.PATCHED_MODULE_NAMES:
                self.__class__.PATCHED_MODULE_NAMES = patched_module_names
                clear_cache = True
            if self._skip_names != self.ADDITIONAL_SKIP_NAMES:
                self.__class__.ADDITIONAL_SKIP_NAMES = self._skip_names
                clear_cache = True
            if patch_default_args != self.PATCH_DEFAULT_ARGS:
                self.__class__.PATCH_DEFAULT_ARGS = patch_default_args
                clear_cache = True

        if clear_cache:
            self.clear_cache()
        self._fake_module_functions = {}
        self._init_fake_module_functions()

        # Attributes set by _refresh()
        self._stubs = None
        self.fs = None
        self.fake_modules = {}
        self.unfaked_modules = {}

        # _isStale is set by tearDown(), reset by _refresh()
        self._isStale = True
        self._dyn_patcher = None
        self._patching = False
示例#5
0
def mock_io_iter(fs):
    fake_filesystem.set_uid(1000)
    fake_filesystem.set_gid(1000)
    yield IOIter('/foo', block_size=2)
    def __init__(self,
                 additional_skip_names=None,
                 modules_to_reload=None,
                 modules_to_patch=None,
                 allow_root_user=True,
                 use_known_patches=True,
                 patch_open_code=PatchMode.OFF):
        """
        Args:
            additional_skip_names: names of modules inside of which no module
                replacement shall be performed, in addition to the names in
                :py:attr:`fake_filesystem_unittest.Patcher.SKIPNAMES`.
                Instead of the module names, the modules themselves
                may be used.
            modules_to_reload: A list of modules that need to be reloaded
                to be patched dynamically; may be needed if the module
                imports file system modules under an alias

                .. caution:: Reloading modules may have unwanted side effects.
            modules_to_patch: A dictionary of fake modules mapped to the
                fully qualified patched module names. Can be used to add
                patching of modules not provided by `pyfakefs`.
            allow_root_user: If True (default), if the test is run as root
                user, the user in the fake file system is also considered a
                root user, otherwise it is always considered a regular user.
            use_known_patches: If True (the default), some patches for commonly
                used packages are applied which make them usable with pyfakefs.
            patch_open_code: If True, `io.open_code` is patched. The default
                is not to patch it, as it mostly is used to load compiled
                modules that are not in the fake file system.
        """

        if not allow_root_user:
            # set non-root IDs even if the real user is root
            set_uid(1)
            set_gid(1)

        self._skip_names = self.SKIPNAMES.copy()
        # save the original open function for use in pytest plugin
        self.original_open = open
        self.fake_open = None
        self.patch_open_code = patch_open_code

        if additional_skip_names is not None:
            skip_names = [
                m.__name__ if inspect.ismodule(m) else m
                for m in additional_skip_names
            ]
            self._skip_names.update(skip_names)

        self._fake_module_classes = {}
        self._unfaked_module_classes = {}
        self._class_modules = {}
        self._init_fake_module_classes()

        self.modules_to_reload = modules_to_reload or []

        if use_known_patches:
            modules_to_patch = modules_to_patch or {}
            modules_to_patch.update(get_modules_to_patch())
            self._class_modules.update(get_classes_to_patch())
            self._fake_module_classes.update(get_fake_module_classes())

        if modules_to_patch is not None:
            for name, fake_module in modules_to_patch.items():
                self._fake_module_classes[name] = fake_module

        self._fake_module_functions = {}
        self._init_fake_module_functions()

        # Attributes set by _refresh()
        self._modules = {}
        self._skipped_modules = {}
        self._fct_modules = {}
        self._def_functions = []
        self._open_functions = {}
        self._stubs = None
        self.fs = None
        self.fake_modules = {}
        self.unfaked_modules = {}
        self._dyn_patcher = None

        # _isStale is set by tearDown(), reset by _refresh()
        self._isStale = True
        self._patching = False