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
3
Example 1
@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
3
Example 2
@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
3
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
3
Example 4
@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)
3
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)
3
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
3
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
3
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
3
Example 9
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)
3
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
3
Example 11
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.")
3
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
3
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
3
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
3
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]
3
Example 16
@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
3
Example 17
@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]
3
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
3
Example 19
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)
3
Example 20
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)
3
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)
3
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')
3
Example 23
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)
3
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
3
Example 25
@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
3
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
3
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)
3
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
3
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)
3
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]
3
Example 31
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
3
Example 32
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)
3
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
3
Example 34
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]
3
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
3
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)
3
Example 37
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
3
Example 38
Project: status.balancedpayments.com Source File: test_setups.py
Function: test_testcase_with_missing_module
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)
3
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
3
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
3
Example 41
@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
3
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')
3
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]
3
Example 44
@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
3
Example 45
def setUp(self):
sys.modules.pop('ssl', None)
sys.modules.pop('_ssl', None)
module_stash.stash()
sys.meta_path.insert(0, ssl_blocker)
3
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)
3
Example 47
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]
3
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
3
Example 49
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']
3
Example 50
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)