def test_disabled_cache(self): reload_module(utils) # re-import with patched settings request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('') user_agent = get_user_agent(request) self.assertIsInstance(user_agent, UserAgent) self.assertIsNone(cache.get(get_cache_key(iphone_ua_string)))
def reload(self): try: invalidate_caches() reload_module(self.module) self.register_handlers() except: tyk.log_error( "Reload error:" )
def test_reload(self): # The site module tries to set attributes # on all the modules that are loaded (specifically, __file__). # If gevent.signal is loaded, and is our compatibility shim, # this used to fail on Python 2: sys.modules['gevent.signal'] has no # __loader__ attribute, so site.py's main() function tries to do # gevent.signal.__file__ = os.path.abspath(gevent.signal.__file__), which # used to not be allowed. (Under Python 3, __loader__ is present so this # doesn't happen). See # https://github.com/gevent/gevent/issues/805 import gevent.signal # make sure it's in sys.modules pylint:disable=redefined-outer-name assert gevent.signal import site if greentest.PY34: from importlib import reload as reload_module elif greentest.PY3: from imp import reload as reload_module else: # builtin on py2 reload_module = reload # pylint:disable=undefined-variable try: reload_module(site) except TypeError: assert greentest.PY36 assert greentest.RUNNING_ON_CI import sys for m in set(sys.modules.values()): try: if m.__cached__ is None: print("Module has None __cached__", m) except AttributeError: continue
def test_reload(self): # The site module tries to set attributes # on all the modules that are loaded (specifically, __file__). # If gevent.signal is loaded, and is our compatibility shim, # this used to fail on Python 2: sys.modules['gevent.signal'] has no # __loader__ attribute, so site.py's main() function tries to do # gevent.signal.__file__ = os.path.abspath(gevent.signal.__file__), which # used to not be allowed. (Under Python 3, __loader__ is present so this # doesn't happen). See # https://github.com/gevent/gevent/issues/805 # This fails on Python 3.5 under linux (travis CI) but not # locally on macOS with (for both libuv and libev cffi); sometimes it # failed with libuv on Python 3.6 too, but not always: # AttributeError: cffi library 'gevent.libuv._corecffi' has no function, # constant or global variable named '__loader__' # which in turn leads to: # SystemError: <built-in function getattr> returned a result with an error set # It's not safe to continue after a SystemError, so we just skip the test there. # As of Jan 2018 with CFFI 1.11.2 this happens reliably on macOS 3.6 and 3.7 # as well. # See https://bitbucket.org/cffi/cffi/issues/352/systemerror-returned-a-result-with-an # This is fixed in 1.11.3 import gevent.signal # make sure it's in sys.modules pylint:disable=redefined-outer-name assert gevent.signal import site if greentest.PY3: from importlib import reload as reload_module else: # builtin on py2 reload_module = reload # pylint:disable=undefined-variable try: reload_module(site) except TypeError: # Non-CFFI on Travis triggers this, for some reason, # but only on 3.6, not 3.4 or 3.5, and not yet on 3.7. # The only module seen to trigger this is __main__, i.e., this module. # This is hard to trigger in a virtualenv since it appears they # install their own site.py, different from the one that ships with # Python 3.6., and at least the version I have doesn't mess with # __cached__ assert greentest.PY36 import sys for m in set(sys.modules.values()): try: if m.__cached__ is None: print("Module has None __cached__", m, file=sys.stderr) except AttributeError: continue
def test_custom_cache(self): reload_module(utils) # re-import with patched settings request = RequestFactory(HTTP_USER_AGENT=iphone_ua_string).get('') user_agent = get_user_agent(request) self.assertIsInstance(user_agent, UserAgent) self.assertIsNone(cache.get(get_cache_key(iphone_ua_string))) self.assertIsInstance(utils.cache.get(get_cache_key(iphone_ua_string)), UserAgent)
def test(header, **more_options): assert isinstance(header, str) with open("temp.h", "w") as f: f.write(header) options = ctypesgen.options.get_default_options() options.headers = ["temp.h"] for opt, val in more_options.items(): setattr(options, opt, val) if redirect_stdout: # Redirect output sys.stdout = io.StringIO() # Step 1: Parse descriptions = ctypesgen.parser.parse(options.headers, options) # Step 2: Process ctypesgen.processor.process(descriptions, options) # Step 3: Print printer = None if options.output_language.startswith("py"): ctypesgen.printer_python.WrapperPrinter("temp.py", options, descriptions) # Load the module we have just produced module = __import__("temp") # import twice, this hack ensure that "temp" is force loaded # (there *must* be a better way to do this) reload_module(module) retval = module elif options.output_language == "json": # for ease and consistency with test results, we are going to cheat by # resetting the anonymous tag number ctypesgen.ctypedescs.last_tagnum = 0 ctypesgen.printer_json.WrapperPrinter("temp.json", options, descriptions) with open("temp.json") as f: JSON = json.load(f) retval = JSON else: raise RuntimeError("No such output language `" + options.output_language + "'") if redirect_stdout: # Un-redirect output output = sys.stdout.getvalue() sys.stdout.close() sys.stdout = sys.__stdout__ else: output = "" return retval, output
def _do_package_pre_config(package_name, config_file): if not config_file: return reload = False config_path = "providers.{}.{}".format(package_name, config_file.strip(".py")) if config_path in sys.modules: reload = True module = __import__(config_path, fromlist=[""]) if reload: reload_module(module)
def maybe_reload_module(self, fullname: str) -> None: """ Reload the module if it already is loaded into :attr:`sys.modules` and add the module to the list of reloaded modules in this call :param fullname: FQN of the module to reload """ if fullname in sys.modules and (self.max_depth is None or len( self.module_stack) < self.max_depth): self.reloaded_modules_in_last_call.append(fullname) reload_module(sys.modules[fullname]) # pylint: disable=no-member
def test_widget_with_default_settings(self): """ Test the widget with default settings which is defined in django settings file """ zoom = 15 default_map_center = [51.5073509, -0.12775829999] widget_settings = { "GooglePointFieldWidget": ( ("zoom", zoom), ("mapCenterLocation", default_map_center), ) } with override_settings(MAP_WIDGETS=widget_settings): reload_module(mw_widgets) widget = mw_widgets.GooglePointFieldWidget() self.assertEqual(hasattr(widget, "settings"), True) self.assertEqual(hasattr(widget, "settings_namespace"), True) self.assertEqual(isinstance(widget.media, django_forms.Media), True) # test `map_options` method options_str = widget.map_options() options = json.loads(options_str) self.assertEqual(options.get("zoom"), zoom) self.assertEqual(options.get("mapCenterLocation"), default_map_center) # test render with Point object value point = Point(-104.9903, 39.7392, srid=DJANGO_DEFAULT_SRID_VALUE) widget_html_elem_id = "id_location" widget_html_elem_name = "location" result = widget.render(name=widget_html_elem_name, value=point, attrs={'id': widget_html_elem_id}) self.assertIn(widget.serialize(point), result) self.assertIn( get_textarea_html(widget_html_elem_id, widget_html_elem_name, point), result) self.assertIn(escapejs(options_str), result) # test render with serialized data value result = widget.render(name=widget_html_elem_name, value=widget.serialize(point)) self.assertIn(widget.serialize(point), result) # test widget `attrs` param w = mw_widgets.GooglePointFieldWidget(attrs={"max-height": 600}) self.assertIn("max-height", w.attrs) # test widget render `attrs` param with `None` value self.assertIn( widget_html_elem_name, w.render(name=widget_html_elem_name, value=None, attrs=None))
def test_context_manager_with_unmocked_readline(self): from certbot._internal.display import completer reload_module(completer) original_completer = readline.get_completer() original_delims = readline.get_completer_delims() with completer.Completer(): pass self.assertEqual(readline.get_completer(), original_completer) self.assertEqual(readline.get_completer_delims(), original_delims)
def reload_wraper(module): if issix: module2reload = module elif python_version() == (3, 3): module2reload = module.__name__ elif python_version() >= (3, 4): module2reload = module else: raise ImportManagerException( "Unknow action to do to reload module %r" % module.__name__) reload_module(module2reload)
def on_query(self,origin,message,**kw): """Reaguje na !reload do query tak, že znovu načte eventy a příkazy. Nefunguje?""" if message==COMMANDPREFIX+"reload": try: reload_module(command) except SyntaxError: traceback.print_exc() self.msg(origin,"Syntax error v seznamu příkazů. Detaily v konzoli.") for module_name in filter(lambda x: not x.startswith('_'), dir(command)): try: reload_module(getattr(command,module_name)) except SyntaxError: traceback.print_exc() self.msg(origin,"Syntax error v příkazu "+module_name+". Detaily v konzoli.") events.unload(self) try: reload_module(events) except SyntaxError: traceback.print_exc() self.msg(origin,"Syntax error v seznamu eventů. Detaily v konzoli.") for module_name in filter(lambda x: not x.startswith('_'), dir(events)): try: reload_module(getattr(events,module_name)) except SyntaxError: traceback.print_exc() self.msg(origin,"Syntax error v eventu "+module_name+". Detaily v konzoli.") except BaseException: pass events.load(self)
def test_urlconf(self): "The admin api urls should not be registered when OSCARAPI_BLOCK_ADMIN_API_ACCESS is True" with self.settings(OSCARAPI_BLOCK_ADMIN_API_ACCESS=False): urlpattern_names = [url.name for url in urls.urlpatterns] for pattern in urls.admin_urlpatterns: self.assertIn(pattern.name, urlpattern_names) with self.settings(OSCARAPI_BLOCK_ADMIN_API_ACCESS=True): reload_module(urls) urlpattern_names = [url.name for url in urls.urlpatterns] for pattern in urls.admin_urlpatterns: self.assertNotIn(pattern.name, urlpattern_names)
def reload_package(self): """ Reloads the whole package (except for this module), in an order that does not cause errors. """ self.python_editor.terminal.stop() self.python_editor.deleteLater() del self.python_editor # reload modules in the order # that they were loaded in for name in PYTHON_EDITOR_MODULES: mod = sys.modules.get(name) if mod is None: continue path = mod.__file__ if path.endswith('.pyc'): path = path.replace('.pyc', '.py') if not os.path.isfile(path): continue with open(path, 'r') as f: data = f.read() if '\x00' in data: msg = 'Cannot load {0} due to Null bytes. Path:\n{1}' print(msg.format(mod, path)) continue try: code = compile(data, mod.__file__, 'exec') except SyntaxError: # This message only shows in terminal # if this environment variable is set: # PYTHONEDITOR_CAPTURE_STARTUP_STREAMS error = traceback.format_exc() msg = 'Could not reload due to the following error:' def print_error(): print(msg) print(error) QTimer.singleShot(100, print_error) continue try: reload_module(mod) except ImportError: msg = 'could not reload {0}: {1}' print(msg.format(name, mod)) QTimer.singleShot(1, self.buildUI) QTimer.singleShot(10, self.set_editor_focus)
def test_widget_with_custom_settings(self): """ Test the widget with custom settings which is updated by `settings` parameter """ zoom = 18 map_size = "300x300" thumbnail_size = "75x75" widget_settings = { "GOOGLE_MAP_API_KEY": GOOGLE_MAP_API_KEY, } with override_settings(MAP_WIDGETS=widget_settings): reload_module(mw_widgets) widget = mw_widgets.GoogleStaticOverlayMapWidget( zoom=zoom, size=map_size, thumbnail_size=thumbnail_size) settings = widget.map_settings # test `map_settings` method self.assertEqual(settings.get("zoom"), zoom) self.assertEqual(settings.get("size"), map_size) # test render point = Point(-105.9903, 38.7392) widget_html_elem_id = "id_location" widget_html_elem_name = "location" result = widget.render(name=widget_html_elem_name, value=point, attrs={'id': widget_html_elem_id}) map_image_url = widget.get_image_url(point) self.assertIn(GOOGLE_MAP_API_KEY, map_image_url) self.assertIn(html_escape(map_image_url), result) # test map_image_url res = urlopen(map_image_url) self.assertEqual(res.getcode(), 200) if hasattr(res.info(), 'type'): self.assertEqual(res.info().type, "image/png") else: self.assertEqual(res.info().get_content_type(), "image/png") # test thumbnail_image_url thumbnail_url = widget.get_thumbnail_url(point) res = urlopen(thumbnail_url) self.assertEqual(res.getcode(), 200) if hasattr(res.info(), 'type'): self.assertEqual(res.info().type, "image/png") else: self.assertEqual(res.info().get_content_type(), "image/png")
def setup(self): """ Application setup method. This method wraps all ``_setup`` actons in one call. It is called before ``self.run()``, allowing the application to be setup but not executed (possibly letting the developer perform other actions before full execution). All handlers should be instantiated and callable after setup is complete. """ LOG.debug(f"now setting up the '{self._meta.label}' application") if self._meta.bootstrap is not None: LOG.debug(f"importing bootstrap code from {self._meta.bootstrap}") if (self._meta.bootstrap not in sys.modules or self._loaded_bootstrap is None): __import__(self._meta.bootstrap, globals(), locals(), [], 0) if hasattr(sys.modules[self._meta.bootstrap], "load"): sys.modules[self._meta.bootstrap].load(self) self._loaded_bootstrap = sys.modules[self._meta.bootstrap] else: reload_module(self._loaded_bootstrap) for _result in self.hook.run("pre_setup", self): pass # pragma: nocover self._setup_extension_handler() self._setup_signals() self._setup_config_handler() self._setup_mail_handler() self._setup_cache_handler() self._setup_log_handler() self._setup_plugin_handler() self._setup_arg_handler() self._setup_output_handler() self._setup_template_handler() self._setup_controllers() self._setup_plot_handler() for hook_spec in self.__retry_hooks__: self.hook.register(*hook_spec) for _result in self.hook.run("post_setup", self): pass
def test_widget_with_default_settings(self): """ Test the widget with default settings which is defined in django settings file """ zoom = 13 map_size = "200x200" widget_settings = { "GoogleStaticMapWidget": ( ("zoom", zoom), ("size", map_size), ), "GOOGLE_MAP_API_KEY": GOOGLE_MAP_API_KEY, } with override_settings(MAP_WIDGETS=widget_settings): reload_module(mw_widgets) widget = mw_widgets.GoogleStaticMapWidget() settings = widget.map_settings # test `map_settings` method self.assertEqual(settings.get("zoom"), zoom) self.assertEqual(settings.get("size"), map_size) # test render point = Point(-105.9903, 38.7392) widget_html_elem_id = "id_location" widget_html_elem_name = "location" result = widget.render(name=widget_html_elem_name, value=point, attrs={'id': widget_html_elem_id}) map_image_url = widget.get_image_url(point) self.assertIn(GOOGLE_MAP_API_KEY, map_image_url) self.assertIn(html_escape(map_image_url), result) # test map_image_url res = urlopen(map_image_url) self.assertEqual(res.getcode(), 200) if hasattr(res.info(), 'type'): self.assertEqual(res.info().type, "image/png") else: self.assertEqual(res.info().get_content_type(), "image/png") # test map_image_url with `None` value result = widget.render(name=widget_html_elem_name, value=None, attrs={'id': widget_html_elem_id}) map_image_url = widget.get_image_url(None) self.assertIn(map_image_url, result)
def _init_providers(self): sys.path.append(g.ADDON_USERDATA_PATH) try: if g.ADDON_USERDATA_PATH not in sys.path: sys.path.append(g.ADDON_USERDATA_PATH) providers = importlib.import_module("providers") else: providers = reload_module(importlib.import_module("providers")) except ValueError: g.notification(g.ADDON_NAME, g.get_language_string(30465)) g.log('No providers installed', 'warning') return providers_dict = providers.get_relevant(self.language) torrent_providers = providers_dict['torrent'] hoster_providers = providers_dict['hosters'] adaptive_providers = providers_dict['adaptive'] hoster_providers, torrent_providers = self._remove_duplicate_providers(torrent_providers, hoster_providers) self.hoster_domains = resolver.Resolver.get_hoster_list() self.torrent_providers = torrent_providers self.hoster_providers = hoster_providers self.adaptive_providers = adaptive_providers self.host_domains = OrderedDict.fromkeys([host[0].lower() for provider in self.hoster_domains['premium'] for host in self.hoster_domains['premium'][provider]]) self.host_names = OrderedDict.fromkeys([host[1].lower() for provider in self.hoster_domains['premium'] for host in self.hoster_domains['premium'][provider]])
def _try_add_providers_path(self): try: if g.ADDON_USERDATA_PATH not in sys.path: sys.path.append(g.ADDON_USERDATA_PATH) return importlib.import_module("providers") else: return reload_module(importlib.import_module("providers")) except ImportError: g.log("Providers folder appears to be missing")
def test_search_with_nonstandard_search_param(self): with override_settings(REST_FRAMEWORK={'SEARCH_PARAM': 'query'}): reload_module(filters) class SearchListView(generics.ListAPIView): queryset = SearchFilterModel.objects.all() serializer_class = SearchFilterSerializer filter_backends = (filters.SearchFilter,) search_fields = ('title', 'text') view = SearchListView.as_view() request = factory.get('/', {'query': 'b'}) response = view(request) assert response.data == [ {'id': 1, 'title': 'z', 'text': 'abc'}, {'id': 2, 'title': 'zz', 'text': 'bcd'} ] reload_module(filters)
def import_class_from_module(name): try: _module = reload_module(import_module(name)) except ImportError: from ika.logger import logger logger.exception(f'Missing module!: {name}') else: _, cls = inspect.getmembers(_module, lambda member: inspect.isclass(member) and member.__module__ == name)[0] return cls
def test_reload(self): # The site module tries to set attributes # on all the modules that are loaded (specifically, __file__). # If gevent.signal is loaded, and is our compatibility shim, # this used to fail on Python 2: sys.modules['gevent.signal'] has no # __loader__ attribute, so site.py's main() function tries to do # gevent.signal.__file__ = os.path.abspath(gevent.signal.__file__), which # used to not be allowed. (Under Python 3, __loader__ is present so this # doesn't happen). See # https://github.com/gevent/gevent/issues/805 # This fails on Python 3.6 under linux (travis CI) but not # locally on macOS with: # AttributeError: cffi library 'gevent.libuv._corecffi' has no function, # constant or global variable named '__loader__' # which in turn leads to: # SystemError: <built-in function getattr> returned a result with an error set import gevent.signal # make sure it's in sys.modules pylint:disable=redefined-outer-name assert gevent.signal import site if greentest.PY34: from importlib import reload as reload_module elif greentest.PY3: from imp import reload as reload_module else: # builtin on py2 reload_module = reload # pylint:disable=undefined-variable try: reload_module(site) except TypeError: assert greentest.PY36 assert greentest.RUNNING_ON_CI import sys for m in set(sys.modules.values()): try: if m.__cached__ is None: print("Module has None __cached__", m) except AttributeError: continue
def test_ordering_with_nonstandard_ordering_param(self): with override_settings(REST_FRAMEWORK={'ORDERING_PARAM': 'order'}): reload_module(filters) class OrderingListView(generics.ListAPIView): queryset = OrderingFilterModel.objects.all() serializer_class = OrderingFilterSerializer filter_backends = (filters.OrderingFilter,) ordering = ('title',) ordering_fields = ('text',) view = OrderingListView.as_view() request = factory.get('/', {'order': 'text'}) response = view(request) assert response.data == [ {'id': 1, 'title': 'zyx', 'text': 'abc'}, {'id': 2, 'title': 'yxw', 'text': 'bcd'}, {'id': 3, 'title': 'xwv', 'text': 'cde'}, ] reload_module(filters)
def test(header, **more_options): assert isinstance(header, str) with open("temp.h", "w") as f: f.write(header) options = ctypesgen.options.get_default_options() options.headers = ["temp.h"] for opt in more_options: setattr(options, opt, more_options[opt]) if redirect_stdout: # Redirect output sys.stdout = io.StringIO() # Step 1: Parse descriptions = ctypesgen.parser.parse(options.headers, options) # Step 2: Process ctypesgen.processor.process(descriptions, options) # Step 3: Print ctypesgen.printer.WrapperPrinter("temp.py", options, descriptions) if redirect_stdout: # Un-redirect output output = sys.stdout.getvalue() sys.stdout.close() sys.stdout = sys.__stdout__ else: output = '' # Load the module we have just produced module = __import__("temp") reload_module( module ) # import twice, this hack ensure that "temp" is force loaded (there *must* be a better way to do this) return module, output
def test_middleware(self): # For test coverage. import crum reload_module(crum) # Test anonymous user. self.assertEqual(get_current_user(), None) url = reverse('test_app:index') response = self.client.get(url) response_content = response.content.decode('utf-8') self.assertEqual(response.status_code, 200) self.assertEqual(response_content, 'AnonymousUser') self.assertEqual(get_current_user(), None) # Test logged in user. self.client.login(username=self.user.username, password=self.user_password) response = self.client.get(url) response_content = response.content.decode('utf-8') self.assertEqual(response.status_code, 200) self.assertEqual(response_content, text_type(self.user)) self.assertEqual(get_current_user(), None) # Test impersonate context manager. with impersonate(self.user): self.assertEqual(get_current_user(), self.user) self.assertEqual(get_current_user(), None) # Test impersonate(None) within view requested by logged in user. self.client.login(username=self.user.username, password=self.user_password) response = self.client.get(url + '?impersonate=1') response_content = response.content.decode('utf-8') self.assertEqual(response.status_code, 200) self.assertEqual(response_content, text_type(None)) self.assertEqual(get_current_user(), None) # Test when request raises exception. try: response = self.client.get(url + '?raise=1') except RuntimeError: response = None self.assertEqual(response, None) self.assertEqual(get_current_user(), None)
def reload_napp_module(self, username, napp_name, napp_file): """Reload a NApp Module.""" mod_name = '.'.join(['napps', username, napp_name, napp_file]) try: napp_module = import_module(mod_name) except ModuleNotFoundError as err: self.log.error("Module '%s' not found", mod_name) raise try: napp_module = reload_module(napp_module) except ImportError as err: self.log.error("Error reloading NApp '%s/%s': %s", username, napp_name, err) raise
def test_reload(self): # The site module tries to set attributes # on all the modules that are loaded (specifically, __file__). # If gevent.signal is loaded, and is our compatibility shim, # this used to fail on Python 2: sys.modules['gevent.signal'] has no # __loader__ attribute, so site.py's main() function tries to do # gevent.signal.__file__ = os.path.abspath(gevent.signal.__file__), which # used to not be allowed. (Under Python 3, __loader__ is present so this # doesn't happen). See # https://github.com/gevent/gevent/issues/805 import gevent.signal # make sure it's in sys.modules pylint:disable=redefined-outer-name assert gevent.signal import site if greentest.PY34: from importlib import reload as reload_module elif greentest.PY3: from imp import reload as reload_module else: # builtin on py2 reload_module = reload # pylint:disable=undefined-variable reload_module(site)
def reload_napp_module(self, username, napp_name, napp_file): """Reload a NApp Module.""" mod_name = '.'.join(['napps', username, napp_name, napp_file]) try: napp_module = import_module(mod_name) except ModuleNotFoundError: self.log.error("Module '%s' not found", mod_name) raise try: napp_module = reload_module(napp_module) except ImportError as err: self.log.error("Error reloading NApp '%s/%s': %s", username, napp_name, err) raise
def test(header, **more_options): assert isinstance(header, str) with open("temp.h", "w") as f: f.write(header) options = ctypesgen.options.get_default_options() options.headers = ["temp.h"] for opt in more_options: setattr(options, opt, more_options[opt]) if redirect_stdout: # Redirect output sys.stdout = io.StringIO() # Step 1: Parse descriptions = ctypesgen.parser.parse(options.headers, options) # Step 2: Process ctypesgen.processor.process(descriptions, options) # Step 3: Print ctypesgen.printer.WrapperPrinter("temp.py", options, descriptions) if redirect_stdout: # Un-redirect output output = sys.stdout.getvalue() sys.stdout.close() sys.stdout = sys.__stdout__ else: output = '' # Load the module we have just produced module = __import__("temp") reload_module(module) # import twice, this hack ensure that "temp" is force loaded (there *must* be a better way to do this) return module, output
def test_python_no_c_extension_with_environment_variable(): from importlib import reload as reload_module import pyrsistent._pvector import pyrsistent import os os.environ['PYRSISTENT_NO_C_EXTENSION'] = 'TRUE' reload_module(pyrsistent._pvector) reload_module(pyrsistent) assert type(pyrsistent.pvector()) is pyrsistent._pvector.PythonPVector del os.environ['PYRSISTENT_NO_C_EXTENSION'] reload_module(pyrsistent._pvector) reload_module(pyrsistent)
def lock_and_call(callback, path_to_lock): """ Grab a lock on path_to_lock from a foreign process then execute the callback. :param callable callback: object to call after acquiring the lock :param str path_to_lock: path to file or directory to lock """ # Reload certbot.util module to reset internal _LOCKS dictionary. reload_module(util) emit_event = Event() receive_event = Event() process = Process(target=_handle_lock, args=(emit_event, receive_event, path_to_lock)) process.start() # Wait confirmation that lock is acquired assert receive_event.wait(timeout=10), 'Timeout while waiting to acquire the lock.' # Execute the callback callback() # Trigger unlock from foreign process emit_event.set() # Wait for process termination process.join(timeout=10) assert process.exitcode == 0
def load_module(self, module_name, hard_reload=True): if module_name in self.__modules: active_module = self.__modules[module_name] if hard_reload: if hasattr(active_module, 'on_module_unload'): try: active_module.on_module_unload() except: Logger.error() try: active_module = reload_module(active_module) except Exception as e: Logger.info( f'Problem reloading module \'{module_name}\': {str(e)}') self.__modules[module_name] = active_module else: # module not yet loaded try: active_module = import_module(module_name) except Exception as e: Logger.info( f'Problem loading module \'{module_name}\': {str(e)}')
def reload_napp(self, username, napp_name): """Reload a NApp.""" self.unload_napp(username, napp_name) mod_name = '.'.join(['napps', username, napp_name, 'main']) try: napp_module = import_module(mod_name) except ModuleNotFoundError as err: self.log.error("Module '%s' not found", mod_name) return 400 try: napp_module = reload_module(napp_module) self.log.info("NApp '%s/%s' successfully reloaded", username, napp_name) except ImportError as err: self.log.error("Error reloading NApp '%s/%s': %s", username, napp_name, err) return 400 self.load_napp(username, napp_name) return 200
def setUp(self): super().setUp() # reset global state from other tests import certbot.util reload_module(certbot.util)
def _reload_hack(self, fullname): m = sys.modules.get(fullname) if not m: return reload_module(m)
def _load(self): """ Loads the module and returns it. If it is already loaded returns `None`. Returns ------- lib : `None` or `lib` """ state = self._state if state == EXTENSION_STATE_UNDEFINED: spec = self._spec lib = sys.modules.get(spec.name, None) if lib is None: # lib is not imported yet, nice lib = module_from_spec(spec) added_variable_names = self._added_variable_names if self._extend_default_variables: for name, value in EXTENSION_LOADER._default_variables.items( ): setattr(lib, name, value) added_variable_names.append(name) default_variables = self._default_variables if default_variables is not None: for name, value in default_variables.items(): setattr(lib, name, value) added_variable_names.append(name) if self._take_snapshot: snapshot_old = take_snapshot() spec.loader.exec_module(lib) sys.modules[spec.name] = lib if self._take_snapshot: snapshot_new = take_snapshot() self._snapshot_difference = calculate_snapshot_difference( snapshot_old, snapshot_new) self._lib = lib self._state = EXTENSION_STATE_LOADED return lib if state == EXTENSION_STATE_LOADED: # return None -> already loaded return None if state == EXTENSION_STATE_UNLOADED: # reload lib = self._lib added_variable_names = self._added_variable_names if self._extend_default_variables: for name, value in EXTENSION_LOADER._default_variables.items(): setattr(lib, name, value) added_variable_names.append(name) default_variables = self._default_variables if default_variables is not None: for name, value in default_variables.items(): setattr(lib, name, value) added_variable_names.append(name) if self._take_snapshot: snapshot_old = take_snapshot() reload_module(lib) if self._take_snapshot: snapshot_new = take_snapshot() self._snapshot_difference = calculate_snapshot_difference( snapshot_old, snapshot_new) self._state = EXTENSION_STATE_LOADED return lib
def setUp(self): reload_module(cli)
("BGL_draw_visualiser", True), ("presets", True), ("pie_menu_template", True), ("icons", True), ) #mods = [__import__("%s.%s" % (__name__, name), {}, {}, name) for name in submod_names] # use importlib for imports from importlib import import_module, reload as reload_module # dictionary of utilities modules utilities = {} for name in utilities_names: mod = import_module("%s.%s" % (__package__, name)) if reload_flag: print("RELOAD", mod) reload_module(mod) utilities[name] = mod SubAddon = getattr(utilities["subaddon"], "SubAddon") draw = getattr(utilities["subaddon"], "draw") create_addon_prefs = getattr(utilities["subaddon"], "create_addon_prefs") handle_registration = getattr(utilities["subaddon"], "handle_registration") import bpy from rna_keymap_ui import draw_kmi from bpy.types import AddonPreferences from bpy.props import StringProperty, BoolProperty, IntProperty from bpy.utils import register_class, unregister_class addons = {}
def reload_module_if_blok_is_reloading(module): from anyblok.environment import EnvironmentManager if EnvironmentManager.get('reload', default=False): reload_module(module)