sys.modules.pop

Here are the examples of the python api sys.modules.pop taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

84 Examples 7

Page 1 Selected Page 2

Example 1

Project: firefox-flicks Source File: test_compression.py
Function: test_no_bz2
    @mask_modules('bz2')
    def test_no_bz2(self):
        c = sys.modules.pop('kombu.compression')
        try:
            import kombu.compression
            self.assertFalse(hasattr(kombu.compression, 'bz2'))
        finally:
            if c is not None:
                sys.modules['kombu.compression'] = c

Example 2

Project: make.mozilla.org Source File: test_transport_amqplib.py
Function: test_import_no_ssl
    @mask_modules("ssl")
    def test_import_no_ssl(self):
        pm = sys.modules.pop("kombu.transport.amqplib")
        try:
            from kombu.transport.amqplib import SSLError
            self.assertEqual(SSLError.__module__, "kombu.transport.amqplib")
        finally:
            if pm is not None:
                sys.modules["kombu.transport.amqplib"] = pm

Example 3

Project: kombu Source File: test_pyamqp.py
    @mock.mask_modules('ssl')
    def test_import_no_ssl(self):
        pm = sys.modules.pop('amqp.connection')
        try:
            from amqp.connection import SSLError
            assert SSLError.__module__ == 'amqp.connection'
        finally:
            if pm is not None:
                sys.modules['amqp.connection'] = pm

Example 4

Project: librosa Source File: test_cache.py
Function: test_cache_enabled
@with_setup(cache_construct, cache_teardown)
def test_cache_enabled():

    sys.modules.pop('librosa.cache', None)
    import librosa.cache
    librosa.cache.clear()

    func_cache = librosa.cache(level=-10)(func)

    # The cache should be active now
    assert func_cache != func

    # issue three calls to func
    y = func(5)

    for i in range(3):
        assert np.allclose(func_cache(5), y)

Example 5

Project: PipelineConstructionSet Source File: test_general.py
    def setUp(self):
        cmds.file(new=1, f=1)
        if cmds.pluginInfo('Fur', q=1, loaded=1):
            cmds.unloadPlugin('Fur')
            cmds.file(new=1, f=1)
        # Currently, PyNode classes for node types defined in 'default'
        # plugins are always created when pymel starts up, even if the plugin
        # wasn't loaded... so we need to make sure we delete 'FurGlobals' if it
        # was made
        if 'FurGlobals' in nt.__dict__:
            del nt.__dict__['FurGlobals']
        if 'FurGlobals' in nt.__class__.__dict__:
            delattr(nt.__class__, 'FurGlobals')
        # Also, 'unload' pymel.all if present - if it's there, it will cause
        # any new PyNodes to skip lazy loading
        sys.modules.pop('pymel.all', None)

Example 6

Project: abusehelper Source File: config.py
def _load_config_module(abspath, module_name="<config>"):
    with open(abspath, "r") as module_file:
        old_module = sys.modules.pop(module_name, None)
        try:
            module = imp.load_source(module_name, abspath, module_file)
        finally:
            if old_module is not None:
                sys.modules[module_name] = old_module
            else:
                sys.modules.pop(module_name, None)
    return module

Example 7

Project: make.mozilla.org Source File: test_redis.py
    def test_redis_None_if_redis_not_installed(self):
        prev = sys.modules.pop("celery.backends.redis")
        try:
            with mask_modules("redis"):
                from celery.backends.redis import redis
                self.assertIsNone(redis)
        finally:
            sys.modules["celery.backends.redis"] = prev

Example 8

Project: scrapyd Source File: test_dont_load_settings.py
    def test_modules_that_shouldnt_load_settings(self):
        sys.modules.pop('scrapy.conf', None)
        for m in self.SETTINGS_SAFE_MODULES:
            __import__(m)
            assert 'scrapy.conf' not in sys.modules, \
                "Module %r must not cause the scrapy.conf module to be loaded" % m

Example 9

Project: mysql-connector-python Source File: test_examples.py
Function: test_engines
    def test_engines(self):
        """examples/engines.py"""
        try:
            import examples.engines as example
        except:
            self.fail()
        output = self._exec_main(example)

        # Can't check output as it might be different per MySQL instance
        # We check only if MyISAM is present
        found = False
        for line in output:
            if line.find('MyISAM') > -1:
                found = True
                break

        self.assertTrue(found, 'MyISAM engine not found in output')

        sys.modules.pop('examples.engine', None)

Example 10

Project: beets Source File: test_logging.py
    def tearDown(self):
        self.unload_plugins()
        self.teardown_beets()
        del beetsplug.dummy
        sys.modules.pop('beetsplug.dummy')
        self.DummyModule.DummyPlugin.listeners = None
        self.DummyModule.DummyPlugin._raw_listeners = None

Example 11

Project: mythbox Source File: test_timehelpers.py
Function: test_deprecated
    def test_deprecated(self):
        """
        Importing L{twisted.test.time_helpers} causes a deprecation warning
        to be emitted.
        """
        # Make sure we're really importing it
        sys.modules.pop('twisted.test.time_helpers', None)
        import twisted.test.time_helpers
        warnings = self.flushWarnings(
            offendingFunctions=[self.test_deprecated])
        self.assertEquals(warnings[0]['category'], DeprecationWarning)
        self.assertEquals(
            warnings[0]['message'],
            "twisted.test.time_helpers is deprecated since Twisted 10.0.  "
            "See twisted.internet.task.Clock instead.")

Example 12

Project: mayavi Source File: test_no_ui_toolkit.py
    def setUp(self):
        self.orig_tk = ETSConfig.toolkit
        ETSConfig._toolkit = 'null'

        # Import something from Pyface to force any potential imports
        # from a UI toolkit.  Why did I pick Pyface? Well, adder_node
        # imports ImageResource and this seems to trigger some UI
        # toolkit import and this makes life difficult as far as the
        # testing goes.  Forcing the issue here should let us test
        # safely since the Pyface imports will be done.
        from pyface.api import GUI

        # Remove any references to wx and Qt
        saved = {}
        for mod in ['wx', 'PyQt4', 'PySide']:
            saved[mod] = sys.modules.pop(mod, None)
        self.saved = saved

Example 13

Project: TrustRouter Source File: benchmark.py
def decimal_using_bytecode(seconds, repeat):
    """Bytecode w/ source: decimal"""
    name = 'decimal'
    py_compile.compile(decimal.__file__)
    for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
                        seconds=seconds):
        yield result

Example 14

Project: firefox-flicks Source File: test_eventlet.py
    def test_aaa_is_patched(self):
        raise SkipTest("side effects")
        monkey_patched = []
        prev_monkey_patch = self.eventlet.monkey_patch
        self.eventlet.monkey_patch = lambda: monkey_patched.append(True)
        prev_eventlet = sys.modules.pop('celery.concurrency.eventlet', None)
        os.environ.pop('EVENTLET_NOPATCH')
        try:
            import celery.concurrency.eventlet  # noqa
            self.assertTrue(monkey_patched)
        finally:
            sys.modules['celery.concurrency.eventlet'] = prev_eventlet
            os.environ['EVENTLET_NOPATCH'] = 'yes'
            self.eventlet.monkey_patch = prev_monkey_patch

Example 15

Project: status.balancedpayments.com Source File: test_loader.py
    def test_loadTestsFromNames__module_not_loaded(self):
        # We're going to try to load this module as a side-effect, so it
        # better not be loaded before we try.
        #
        module_name = 'unittest2.test.dummy'
        sys.modules.pop(module_name, None)

        loader = unittest2.TestLoader()
        try:
            suite = loader.loadTestsFromNames([module_name])

            self.assertIsInstance(suite, loader.suiteClass)
            self.assertEqual(list(suite), [unittest2.TestSuite()])

            # module should now be loaded, thanks to loadTestsFromName()
            self.assertIn(module_name, sys.modules)
        finally:
            if module_name in sys.modules:
                del sys.modules[module_name]

Example 16

Project: firefox-flicks Source File: test_pyamqp.py
Function: test_import_no_ssl
    @mask_modules('ssl')
    def test_import_no_ssl(self):
        pm = sys.modules.pop('amqp.connection')
        try:
            from amqp.connection import SSLError
            self.assertEqual(SSLError.__module__, 'amqp.connection')
        finally:
            if pm is not None:
                sys.modules['amqp.connection'] = pm

Example 17

Project: brython Source File: test_import.py
Function: ready_to_import
@contextlib.contextmanager
def _ready_to_import(name=None, source=""):
    # sets up a temporary directory and removes it
    # creates the module file
    # temporarily clears the module from sys.modules (if any)
    # reverts or removes the module when cleaning up
    name = name or "spam"
    with script_helper.temp_dir() as tempdir:
        path = script_helper.make_script(tempdir, name, source)
        old_module = sys.modules.pop(name, None)
        try:
            sys.path.insert(0, tempdir)
            yield name, path
            sys.path.remove(tempdir)
        finally:
            if old_module is not None:
                sys.modules[name] = old_module
            elif name in sys.modules:
                del sys.modules[name]

Example 18

Project: make.mozilla.org Source File: test_serialization.py
    def test_no_cpickle(self):
        prev = sys.modules.pop("celery.utils.serialization", None)
        try:
            with mask_modules("cPickle"):
                from celery.utils.serialization import pickle
                import pickle as orig_pickle
                self.assertIs(pickle.dumps, orig_pickle.dumps)
        finally:
            sys.modules["celery.utils.serialization"] = prev

Example 19

Project: pymo Source File: test_setups.py
Function: test_testcase_with_missing_module
    def test_testcase_with_missing_module(self):
        class Test(unittest.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass
        Test.__module__ = 'Module'
        sys.modules.pop('Module', None)

        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 2)

Example 20

Project: mysql-connector-python Source File: test_examples.py
Function: test_dates
    def test_dates(self):
        """examples/dates.py"""
        try:
            import examples.dates as example
        except Exception as err:
            self.fail(err)
        output = example.main(self.config)
        exp = ['  1 | 1977-06-14 | 1977-06-14 21:10:00 | 21:10:00 |',
               '  2 |       None |                None |  0:00:00 |',
               '  3 |       None |                None |  0:00:00 |']
        self.assertEqual(output, exp)

        example.DATA.append(('0000-00-00', None, '00:00:00'),)
        self.assertRaises(mysql.connector.errors.IntegrityError,
                          example.main, self.config)

        sys.modules.pop('examples.dates', None)

Example 21

Project: cgstudiomap Source File: test_setups.py
    def test_testcase_with_missing_module(self):
        class Test(unittest2.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass
        Test.__module__ = 'Module'
        sys.modules.pop('Module', None)

        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 2)

Example 22

Project: nzbToMedia Source File: test_path.py
    @pytest.fixture
    def feign_linux(self, monkeypatch):
        monkeypatch.setattr("platform.system", lambda: "Linux")
        monkeypatch.setattr("sys.platform", "linux")
        monkeypatch.setattr("os.pathsep", ":")
        # remove any existing import of appdirs, as it sets up some
        # state during import.
        sys.modules.pop('appdirs')

Example 23

Project: Eventlet Source File: patcher.py
Function: original
def original(modname):
    mod = _originals.get(modname)
    if mod is None:
        # re-import the "pure" module and store it in the global _originals
        # dict; be sure to restore whatever module had that name already
        current_mod = sys.modules.pop(modname, None)
        try:
            real_mod = __import__(modname, {}, {}, modname.split('.')[:-1])
            _originals[modname] = real_mod
        finally:
            if current_mod is not None:
                sys.modules[modname] = current_mod
    return _originals.get(modname)

Example 24

Project: gargoyle Source File: tests.py
    def setUp(self):
        self.old_gargoyle_helpers = sys.modules.pop('gargoyle.helpers')
        del gargoyle.helpers

        self.old_json = sys.modules.pop('json')
        sys.modules['json'] = None

Example 25

Project: gunicorn Source File: gtornado.py
Function: set_up
    @classmethod
    def setup(cls):
        web = sys.modules.pop("tornado.web")
        old_clear = web.RequestHandler.clear

        def clear(self):
            old_clear(self)
            if not "Gunicorn" in self._headers["Server"]:
                self._headers["Server"] += " (Gunicorn/%s)" % gversion
        web.RequestHandler.clear = clear
        sys.modules["tornado.web"] = web

Example 26

Project: hy Source File: importer.py
def import_file_to_module(module_name, fpath):
    """Import content from fpath and puts it into a Python module.

    Returns the module."""
    try:
        _ast = import_file_to_ast(fpath, module_name)
        mod = imp.new_module(module_name)
        mod.__file__ = fpath
        eval(ast_compile(_ast, fpath, "exec"), mod.__dict__)
    except (HyTypeError, LexException) as e:
        if e.source is None:
            with open(fpath, 'rt') as fp:
                e.source = fp.read()
            e.filename = fpath
        raise
    except Exception:
        sys.modules.pop(module_name, None)
        raise
    return mod

Example 27

Project: errbot Source File: slack_tests.py
    def setUp(self):
        # make up a config.
        tempdir = mkdtemp()
        # reset the config every time
        sys.modules.pop('errbot.config-template', None)
        __import__('errbot.config-template')
        config = sys.modules['errbot.config-template']
        bot_config_defaults(config)
        config.BOT_DATA_DIR = tempdir
        config.BOT_LOG_FILE = os.path.join(tempdir, 'log.txt')
        config.BOT_EXTRA_PLUGIN_DIR = []
        config.BOT_LOG_LEVEL = logging.DEBUG
        config.BOT_IDENTITY = {'username': 'err@localhost', 'token': '___'}
        config.BOT_ASYNC = False
        config.BOT_PREFIX = '!'
        config.CHATROOM_FN = 'blah'

        self.slack = TestSlackBackend(config)

Example 28

Project: TrustRouter Source File: benchmark.py
def source_using_bytecode(seconds, repeat):
    """Bytecode w/ source: simple"""
    name = '__importlib_test_benchmark__'
    with source_util.create_modules(name) as mapping:
        py_compile.compile(mapping[name])
        assert os.path.exists(imp.cache_from_source(mapping[name]))
        for result in bench(name, lambda: sys.modules.pop(name), repeat=repeat,
                            seconds=seconds):
            yield result

Example 29

Project: librosa Source File: test_cache.py
def test_cache_disabled():

    os.environ.pop('LIBROSA_CACHE_DIR', None)
    sys.modules.pop('librosa.cache', None)
    import librosa.cache

    func_cache = librosa.cache(level=-10)(func)

    # When there's no cache directory in the environment,
    # librosa.cache is a no-op.
    eq_(func, func_cache)

Example 30

Project: status.balancedpayments.com Source File: test_loader.py
    def test_loadTestsFromName__module_not_loaded(self):
        # We're going to try to load this module as a side-effect, so it
        # better not be loaded before we try.
        #
        module_name = 'unittest2.test.dummy'
        sys.modules.pop(module_name, None)

        loader = unittest2.TestLoader()
        try:
            suite = loader.loadTestsFromName(module_name)

            self.assertIsInstance(suite, loader.suiteClass)
            self.assertEqual(list(suite), [])

            # module should now be loaded, thanks to loadTestsFromName()
            self.assertIn(module_name, sys.modules)
        finally:
            if module_name in sys.modules:
                del sys.modules[module_name]

Example 31

Project: firefox-flicks Source File: test_loaders.py
Function: test_on_worker_init
    def test_on_worker_init(self):
        prev, self.app.conf.CELERY_IMPORTS = (
            self.app.conf.CELERY_IMPORTS, ('subprocess', ))
        try:
            sys.modules.pop('subprocess', None)
            self.loader.init_worker()
            self.assertIn('subprocess', sys.modules)
        finally:
            self.app.conf.CELERY_IMPORTS = prev

Example 32

Project: QSTK Source File: util.py
Function: cleanup_tmp_dir
def cleanup_tmp_dir(tmp_dir):
    os.unlink(os.path.join(tmp_dir, 'epydoc_test.py'))
    try: os.unlink(os.path.join(tmp_dir, 'epydoc_test.pyc'))
    except OSError: pass
    os.rmdir(tmp_dir)
    sys.modules.pop('epydoc_test', None)

Example 33

Project: firefox-flicks Source File: test_gevent.py
    def test_is_patched(self):
        with mock_module(*gevent_modules):
            monkey_patched = []
            import gevent
            from gevent import monkey
            gevent.version_info = (1, 0, 0)
            prev_monkey_patch = monkey.patch_all
            monkey.patch_all = lambda: monkey_patched.append(True)
            prev_gevent = sys.modules.pop('celery.concurrency.gevent', None)
            os.environ.pop('GEVENT_NOPATCH')
            try:
                import celery.concurrency.gevent  # noqa
                self.assertTrue(monkey_patched)
            finally:
                sys.modules['celery.concurrency.gevent'] = prev_gevent
                os.environ['GEVENT_NOPATCH'] = 'yes'
                monkey.patch_all = prev_monkey_patch

Example 34

Project: pymo Source File: test_loader.py
Function: test_loadtestsfromnames_module_not_loaded
    def test_loadTestsFromNames__module_not_loaded(self):
        # We're going to try to load this module as a side-effect, so it
        # better not be loaded before we try.
        #
        module_name = 'unittest.test.dummy'
        sys.modules.pop(module_name, None)

        loader = unittest.TestLoader()
        try:
            suite = loader.loadTestsFromNames([module_name])

            self.assertIsInstance(suite, loader.suiteClass)
            self.assertEqual(list(suite), [unittest.TestSuite()])

            # module should now be loaded, thanks to loadTestsFromName()
            self.assertIn(module_name, sys.modules)
        finally:
            if module_name in sys.modules:
                del sys.modules[module_name]

Example 35

Project: firefox-flicks Source File: test_utils.py
    @skip_if_module('__pypy__')
    def test_uuid_without_ctypes(self):
        old_utils = sys.modules.pop('kombu.utils')

        @mask_modules('ctypes')
        def with_ctypes_masked():
            from kombu.utils import ctypes, uuid

            self.assertIsNone(ctypes)
            tid = uuid()
            self.assertTrue(tid)
            self.assertIsInstance(tid, basestring)

        try:
            with_ctypes_masked()
        finally:
            sys.modules['celery.utils'] = old_utils

Example 36

Project: brython Source File: test_imp.py
    def test_with_deleted_parent(self):
        # see #18681
        from html import parser
        html = sys.modules.pop('html')
        def cleanup():
            sys.modules['html'] = html
        self.addCleanup(cleanup)
        with self.assertRaisesRegex(ImportError, 'html'):
            imp.reload(parser)

Example 37

Project: make.mozilla.org Source File: test_database.py
Function: test_pickle_hack_for_sqla_05
    def test_pickle_hack_for_sqla_05(self):
        import sqlalchemy as sa
        from celery.db import session
        prev_base = session.ResultModelBase
        prev_ver, sa.__version__ = sa.__version__, "0.5.0"
        prev_models = sys.modules.pop("celery.db.models", None)
        try:
            from sqlalchemy.ext.declarative import declarative_base
            session.ResultModelBase = declarative_base()
            from celery.db.dfd042c7 import PickleType as Type1
            from celery.db.models import PickleType as Type2
            self.assertIs(Type1, Type2)
        finally:
            sys.modules["celery.db.models"] = prev_models
            sa.__version__ = prev_ver
            session.ResultModelBase = prev_base

Example 38

Project: status.balancedpayments.com Source File: test_setups.py
Function: test_testcase_with_missing_module
    def test_testcase_with_missing_module(self):
        class Test(unittest2.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass
        Test.__module__ = 'Module'
        sys.modules.pop('Module', None)
        
        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 2)

Example 39

Project: make.mozilla.org Source File: test_concurrency_eventlet.py
    def test_is_patched(self):
        monkey_patched = []
        prev_monkey_patch = self.eventlet.monkey_patch
        self.eventlet.monkey_patch = lambda: monkey_patched.append(True)
        prev_eventlet = sys.modules.pop("celery.concurrency.eventlet", None)
        os.environ.pop("EVENTLET_NOPATCH")
        try:
            import celery.concurrency.eventlet  # noqa
            self.assertTrue(monkey_patched)
        finally:
            sys.modules["celery.concurrency.eventlet"] = prev_eventlet
            os.environ["EVENTLET_NOPATCH"] = "yes"
            self.eventlet.monkey_patch = prev_monkey_patch

Example 40

Project: kombu Source File: test_compression.py
    @mock.mask_modules('bz2')
    def test_no_bz2(self):
        c = sys.modules.pop('kombu.compression')
        try:
            import kombu.compression
            assert not hasattr(kombu.compression, 'bz2')
        finally:
            if c is not None:
                sys.modules['kombu.compression'] = c

Example 41

Project: make.mozilla.org Source File: test_compression.py
Function: test_no_bz2
    @mask_modules("bz2")
    def test_no_bz2(self):
        c = sys.modules.pop("kombu.compression")
        try:
            import kombu.compression
            self.assertFalse(hasattr(kombu.compression, "bz2"))
        finally:
            if c is not None:
                sys.modules["kombu.compression"] = c

Example 42

Project: astroid Source File: unittest_manager.py
    def test_namespace_package_pth_support(self):
        pth = 'foogle_fax-0.12.5-py2.7-nspkg.pth'
        site.addpackage(resources.RESOURCE_PATH, pth, [])
        # pylint: disable=no-member; can't infer _namespace_packages, created at runtime.
        pkg_resources._namespace_packages['foogle'] = []

        try:
            module = self.manager.ast_from_module_name('foogle.fax')
            submodule = next(module.igetattr('a'))
            value = next(submodule.igetattr('x'))
            self.assertIsInstance(value, astroid.Const)
            with self.assertRaises(exceptions.AstroidImportError):
                self.manager.ast_from_module_name('foogle.moogle')
        finally:
            del pkg_resources._namespace_packages['foogle']
            sys.modules.pop('foogle')

Example 43

Project: iot-utilities Source File: __init__.py
@contextlib.contextmanager
def _ready_to_import(name=None, source=""):
    # sets up a temporary directory and removes it
    # creates the module file
    # temporarily clears the module from sys.modules (if any)
    # reverts or removes the module when cleaning up
    name = name or "spam"
    with temp_dir() as tempdir:
        path = script_helper.make_script(tempdir, name, source)
        old_module = sys.modules.pop(name, None)
        try:
            sys.path.insert(0, tempdir)
            yield name, path
            sys.path.remove(tempdir)
        finally:
            if old_module is not None:
                sys.modules[name] = old_module
            elif name in sys.modules:
                del sys.modules[name]

Example 44

Project: kombu Source File: test_encoding.py
Function: clean_encoding
@contextmanager
def clean_encoding():
    old_encoding = sys.modules.pop('kombu.utils.encoding', None)
    import kombu.utils.encoding
    try:
        yield kombu.utils.encoding
    finally:
        if old_encoding:
            sys.modules['kombu.utils.encoding'] = old_encoding

Example 45

Project: urllib3 Source File: test_no_ssl.py
Function: set_up
    def setUp(self):
        sys.modules.pop('ssl', None)
        sys.modules.pop('_ssl', None)

        module_stash.stash()
        sys.meta_path.insert(0, ssl_blocker)

Example 46

Project: GAE-Bulk-Mailer Source File: loaders.py
    @internalcode
    def load(self, environment, name, globals=None):
        key = self.get_template_key(name)
        module = '%s.%s' % (self.package_name, key)
        mod = getattr(self.module, module, None)
        if mod is None:
            try:
                mod = __import__(module, None, None, ['root'])
            except ImportError:
                raise TemplateNotFound(name)

            # remove the entry from sys.modules, we only want the attribute
            # on the module object we have stored on the loader.
            sys.modules.pop(module, None)

        return environment.template_class.from_module_dict(
            environment, mod.__dict__, globals)

Example 47

Project: pymo Source File: test_loader.py
Function: test_loadtestsfromname_module_not_loaded
    def test_loadTestsFromName__module_not_loaded(self):
        # We're going to try to load this module as a side-effect, so it
        # better not be loaded before we try.
        #
        module_name = 'unittest.test.dummy'
        sys.modules.pop(module_name, None)

        loader = unittest.TestLoader()
        try:
            suite = loader.loadTestsFromName(module_name)

            self.assertIsInstance(suite, loader.suiteClass)
            self.assertEqual(list(suite), [])

            # module should now be loaded, thanks to loadTestsFromName()
            self.assertIn(module_name, sys.modules)
        finally:
            if module_name in sys.modules:
                del sys.modules[module_name]

Example 48

Project: slimit Source File: test_cmd.py
    def test_main_stdin_stdout(self):
        # slimit.minifier should be deleted from sys.modules in order
        # to have a proper reference to sys.stdin and sys.stdou when
        # 'main' definition is evaluated during module import
        old_module = None
        try:
            old_module = sys.modules.pop('slimit.minifier')
        except KeyError:
            pass

        with redirected_input_output(
            input='function foo() { var local = 5; }') as out:
            from slimit.minifier import main
            main(['-m'])

        self.assertEqual('function foo(){var a=5;}', out.getvalue())
        if old_module is not None:
            sys.modules['slimit.minifier'] = old_module

Example 49

Project: trigger Source File: mock_redis.py
Function: install
def install():
    """Install into sys.modules as the Redis module"""
    for mod in ('redis', 'utils.mock_redis'):
        sys.modules.pop(mod, None)
    __import__('utils.mock_redis')
    sys.modules['redis'] = sys.modules['utils.mock_redis']

Example 50

Project: protorpc Source File: protojson_test.py
Function: set_up
  def setUp(self):
    """Save original import function."""
    self.simplejson = sys.modules.pop('simplejson', None)
    self.json = sys.modules.pop('json', None)
    self.original_import = self.get_import()
    def block_all_jsons(name, *args, **kwargs):
      if 'json' in name:
        if name in sys.modules:
          module = sys.modules[name]
          module.name = name
          return module
        raise ImportError('Unable to find %s' % name)
      else:
        return self.original_import(name, *args, **kwargs)
    self.set_import(block_all_jsons)
See More Examples - Go to Next Page
Page 1 Selected Page 2