• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python moves.reload_module函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中six.moves.reload_module函数的典型用法代码示例。如果您正苦于以下问题:Python reload_module函数的具体用法?Python reload_module怎么用?Python reload_module使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了reload_module函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: tearDown

    def tearDown(self):
        super(RbacHorizonTests, self).tearDown()
        # Restore our settings
        settings.HORIZON_CONFIG['default_dashboard'] = self.old_default_dash
        settings.HORIZON_CONFIG['dashboards'] = self.old_dashboards
        # Destroy our singleton and re-create it.
        base.HorizonSite._instance = None
        del base.Horizon
        base.Horizon = base.HorizonSite()
        # Reload the convenience references to Horizon stored in __init__
        moves.reload_module(import_module("horizon"))

        # Reset Cats and Dogs default_panel to default values
        Cats.default_panel = 'kittens'
        Dogs.default_panel = 'puppies'

        # Re-register our original dashboards and panels.
        # This is necessary because autodiscovery only works on the first
        # import, and calling reload introduces innumerable additional
        # problems. Manual re-registration is the only good way for testing.
        self._discovered_dashboards.remove(Cats)
        self._discovered_dashboards.remove(Dogs)
        for dash in self._discovered_dashboards:
            base.Horizon.register(dash)
            for panel in self._discovered_panels[dash]:
                dash.register(panel)
开发者ID:infraredgirl,项目名称:horizon,代码行数:26,代码来源:base.py


示例2: verify

def verify(request_type, success_url=None, failure_url=None, **kwargs):
    """
    Call the verify view function. All kwargs not specified above will be passed
    as GET or POST arguments.
    """
    if request_type == 'get':
        request = factory.get('/browserid/verify', kwargs)
    else:
        request = factory.post('/browserid/verify', kwargs)

    # Patch settings prior to importing verify
    patches = {'BROWSERID_CREATE_USER': True, 'SITE_URL': 'http://testserver'}
    if success_url is not None:
        patches['LOGIN_REDIRECT_URL'] = success_url
    if failure_url is not None:
        patches['LOGIN_REDIRECT_URL_FAILURE'] = failure_url

    # We need to reload verify for the setting changes to take effect.
    with patch_settings(**patches):
        reload_module(views)
        verify_view = views.Verify.as_view()
        with patch.object(auth, 'login'):
            response = verify_view(request)

    return response
开发者ID:Ahmed-Saeed,项目名称:django-browserid,代码行数:25,代码来源:test_views.py


示例3: fin

 def fin():
     monkeypatch.undo()
     reload_module(sherpa)
     reload_module(plot)
     reload_module(astro_plot)
     reload_module(sherpa.all)
     reload_module(sherpa.astro.all)  # These are required because otherwise Python will not match imported classes.
开发者ID:mirca,项目名称:sherpa,代码行数:7,代码来源:conftest.py


示例4: test_channel

def test_channel(sol):
    config.update(
        {
            'Re': 8000.,
            'nu': 1./8000.,              # Viscosity
            'dt': 0.001,                 # Time step
            'T': 0.01,                   # End time
            'L': [2, 2*pi, 4*pi/3.],
            'M': [7, 5, 2],
            'eps': 1e-7
        }, "channel"
    )

    solver = get_solver(regression_test=regression_test,
                        mesh="channel",
                        parse_args=[sol])
    context = solver.get_context()
    initialize(solver, context)
    set_Source(**context)
    solve(solver, context)

    config.params.dealias = '3/2-rule'
    config.params.optimization = 'cython'
    reload_module(solver) # Need to reload to enable optimization
    initialize(solver, context)
    solve(solver, context)

    config.params.dealias_cheb = True
    config.params.checkpoint = 5
    config.params.write_result = 2
    initialize(solver, context)
    solve(solver, context)
开发者ID:spectralDNS,项目名称:spectralDNS,代码行数:32,代码来源:test_channel.py


示例5: setUp

 def setUp(self):
     reload_module(local)
     self.tmpdir = tempfile.mkdtemp()
     self.key_file = os.path.join(self.tmpdir, 'key')
     self.patcher = mock.patch('secretcrypt.local._key_dir')
     mock_key_dir = self.patcher.start()
     mock_key_dir.return_value = self.tmpdir
开发者ID:Zemanta,项目名称:py-secretcrypt,代码行数:7,代码来源:test_local.py


示例6: test_all_public_methods_are_traced

    def test_all_public_methods_are_traced(self):
        profiler_opts.set_defaults(conf.CONF)
        self.config(enabled=True,
                    group='profiler')

        classes = [
            'magnum.conductor.api.API',
            'magnum.conductor.api.ListenerAPI',
            'magnum.conductor.handlers.ca_conductor.Handler',
            'magnum.conductor.handlers.cluster_conductor.Handler',
            'magnum.conductor.handlers.conductor_listener.Handler',
            'magnum.conductor.handlers.indirection_api.Handler',
            'magnum.service.periodic.MagnumPeriodicTasks',
        ]
        for clsname in classes:
            # give the metaclass and trace_cls() decorator a chance to patch
            # methods of the classes above
            six.reload_module(
                importutils.import_module(clsname.rsplit('.', 1)[0]))
            cls = importutils.import_class(clsname)

            for attr, obj in cls.__dict__.items():
                # only public methods are traced
                if attr.startswith('_'):
                    continue
                # only checks callables
                if not (inspect.ismethod(obj) or inspect.isfunction(obj)):
                    continue
                # osprofiler skips static methods
                if isinstance(obj, staticmethod):
                    continue

                self.assertTrue(getattr(obj, '__traced__', False), obj)
开发者ID:openstack,项目名称:magnum,代码行数:33,代码来源:test_profiler.py


示例7: testHalfDuplexCallWedged

 def testHalfDuplexCallWedged(self):
   import protoc_plugin_test_pb2 as test_pb2  # pylint: disable=g-import-not-at-top
   moves.reload_module(test_pb2)
   condition = threading.Condition()
   wait_cell = [False]
   @contextlib.contextmanager
   def wait():  # pylint: disable=invalid-name
     # Where's Python 3's 'nonlocal' statement when you need it?
     with condition:
       wait_cell[0] = True
     yield
     with condition:
       wait_cell[0] = False
       condition.notify_all()
   def half_duplex_request_iterator():
     request = test_pb2.StreamingOutputCallRequest()
     request.response_parameters.add(size=1, interval_us=0)
     yield request
     with condition:
       while wait_cell[0]:
         condition.wait()
   with _CreateService(test_pb2) as (methods, stub):
     with wait():
       responses = stub.HalfDuplexCall(
           half_duplex_request_iterator(), test_constants.SHORT_TIMEOUT)
       # half-duplex waits for the client to send all info
       with self.assertRaises(face.ExpirationError):
         next(responses)
开发者ID:WeiZhang555,项目名称:grpc,代码行数:28,代码来源:beta_python_plugin_test.py


示例8: _test_enforce_network_driver_types_create

    def _test_enforce_network_driver_types_create(
            self,
            network_driver_type,
            network_driver_config_dict,
            coe='kubernetes',
            assert_raised=False):

        @v.enforce_network_driver_types_create()
        def test(self, baymodel):
            pass

        for key, val in network_driver_config_dict.items():
            cfg.CONF.set_override(key, val, 'baymodel')
        baymodel = mock.MagicMock()
        baymodel.name = 'test_baymodel'
        baymodel.network_driver = network_driver_type
        baymodel.coe = coe

        # Reload the validator module so that baymodel configs are
        # re-evaluated.
        reload_module(v)
        validator = v.K8sValidator
        validator.supported_drivers = ['flannel', 'type1', 'type2']

        if assert_raised:
            self.assertRaises(exception.InvalidParameterValue,
                              test, self, baymodel)
        else:
            test(self, baymodel)
        return baymodel
开发者ID:coreypobrien,项目名称:magnum,代码行数:30,代码来源:test_validation.py


示例9: test_schema_local

def test_schema_local():
    def __test(ns_key):

        # Get the schema
        schema = jams.schema.namespace(ns_key)

        # Make sure it has the correct properties
        valid_keys = set(['time', 'duration', 'value', 'confidence'])
        for key in schema['properties']:
            assert key in valid_keys

        for key in ['time', 'duration']:
            assert key in schema['properties']

    os.environ['JAMS_SCHEMA_DIR'] = resource_filename(jams.__name__, 
                                                      os.path.join('tests',
                                                                   'fixtures',
                                                                   'schema'))

    # Namespace should not exist yet
    test_ns = 'testing_tag_upper'
    yield raises(NamespaceError)(__test), test_ns

    reload_module(jams)

    # Now it should
    yield __test, test_ns
    
    del os.environ['JAMS_SCHEMA_DIR']
开发者ID:beckgom,项目名称:jams,代码行数:29,代码来源:schema_test.py


示例10: setUp

    def setUp(self):
        super(OAuth2RequiredDecoratorTest, self).setUp()
        self.save_settings = copy.deepcopy(django.conf.settings)

        reload_module(oauth2client.contrib.django_util)
        self.user = User.objects.create_user(
            username='bill', email='[email protected]', password='hunter2')
开发者ID:pk-codebox-evo,项目名称:google-oauth2client,代码行数:7,代码来源:test_decorators.py


示例11: generate_hierarchy_from_module

def generate_hierarchy_from_module(module):
    from .case import is_testcase_subclass

    if isinstance(module, str):
        module = importlib.import_module(module)
    logger.debug("reload %s", module)
    reload_module(module)

    children = []

    for attr_name in dir(module):
        obj = getattr(module, attr_name)
        if is_testcase_subclass(obj) and not inspect.isabstract(obj):
            case_hierarchy = generate_hierarchy_from_testcase_class(obj)
            if case_hierarchy["children"]:
                children.append(case_hierarchy)

    imp_loader = pkgutil.get_loader(module)
    if imp_loader.is_package(module.__name__):
        for module_loader, sub_module_name, is_pkg in pkgutil.iter_modules(path=module.__path__):
            sub_suite_module = importlib.import_module(module.__name__ + "." + sub_module_name)
            sub_suite_hierarchy = generate_hierarchy_from_module(sub_suite_module)
            if sub_suite_hierarchy["children"]:
                children.append(sub_suite_hierarchy)

    return {"id": module.__name__, "name": module.__name__.rpartition(".")[2], "children": children}
开发者ID:yaleyang,项目名称:ngta,代码行数:26,代码来源:util.py


示例12: test_NS2D

def test_NS2D(args):
    config.update(
        {
            'nu': 0.01,
            'dt': 0.05,
            'T': 10
        }, 'doublyperiodic')
    solver = get_solver(regression_test=regression_test,
                        mesh='doublyperiodic',
                        parse_args=args)
    context = solver.get_context()
    initialize(solver, **context)
    solve(solver, context)

    config.params.dealias = '3/2-rule'
    initialize(solver, **context)
    solve(solver, context)

    config.params.dealias = '2/3-rule'
    config.params.optimization = 'cython'
    reload_module(solver)
    initialize(solver, **context)
    solve(solver, context)

    config.params.write_result = 1
    config.params.checkpoint = 1
    config.params.dt = 0.01
    config.params.t = 0.0
    config.params.tstep = 0
    config.params.T = 0.04
    solver.regression_test = lambda c: None
    initialize(solver, **context)
    solve(solver, context)
开发者ID:spectralDNS,项目名称:spectralDNS,代码行数:33,代码来源:test_NS2D.py


示例13: setup_sdk_imports

def setup_sdk_imports():
    """Sets up appengine SDK third-party imports."""
    if six.PY3:
        return

    if 'GAE_SDK_PATH' not in os.environ:
        return

    sys.path.insert(0, os.environ['GAE_SDK_PATH'])

    if 'google' in sys.modules:
        # Some packages, such as protobuf, clobber the google
        # namespace package. This prevents that.
        try:
            reload_module(sys.modules['google'])
        except ImportError:
            pass

    # This sets up google-provided libraries.
    import dev_appserver
    dev_appserver.fix_sys_path()

    # Fixes timezone and other os-level items.
    import google.appengine.tools.os_compat
    (google.appengine.tools.os_compat)
开发者ID:tmatsuo,项目名称:python-repo-tools,代码行数:25,代码来源:appengine.py


示例14: _test_enforce_volume_driver_types_update

    def _test_enforce_volume_driver_types_update(
            self,
            mock_get_resource,
            mock_pecan_request,
            volume_driver_type,
            op,
            assert_raised=False):

        @v.enforce_volume_driver_types_update()
        def test(self, baymodel_ident, patch):
            pass

        baymodel_ident = 'test_uuid_or_name'
        patch = [{'path': '/volume_driver', 'value': volume_driver_type,
                  'op': op}]
        context = mock_pecan_request.context
        baymodel = obj_utils.get_test_baymodel(context,
                                               uuid=baymodel_ident,
                                               coe='kubernetes')
        mock_get_resource.return_value = baymodel

        # Reload the validator module so that baymodel configs are
        # re-evaluated.
        reload_module(v)
        validator = v.K8sValidator
        validator.supported_volume_driver = ['cinder']

        if assert_raised:
            self.assertRaises(exception.InvalidParameterValue,
                              test, self, baymodel_ident, patch)
        else:
            test(self, baymodel_ident, patch)
            mock_get_resource.assert_called_once_with(
                'BayModel', baymodel_ident)
开发者ID:baikai,项目名称:magnum,代码行数:34,代码来源:test_validation.py


示例15: _set_bedtools_path

def _set_bedtools_path(path=""):
    old_path = settings._bedtools_path
    settings._bedtools_path = path
    if old_path != path:
        reload_module(bedtool)
        reload_module(pybedtools)
        return True
开发者ID:daler,项目名称:pybedtools,代码行数:7,代码来源:paths.py


示例16: run

    def run(self):
        ''' run command '''
        # find the files that call generate
        generate_files = find_files('roles',
                                    ['inventory',
                                     'test',
                                     'playbooks'],
                                    None,
                                    'generate.py$')

        if len(generate_files) < 1:
            print('Did not find any code generation.  Please verify module code generation.')  # noqa: E501
            raise SystemExit(1)

        errors = False
        for gen in generate_files:
            print('Checking generated module code: {0}'.format(gen))
            try:
                sys.path.insert(0, os.path.dirname(gen))
                # we are importing dynamically.  This isn't in
                # the python path.
                # pylint: disable=import-error
                import generate
                reload_module(generate)
                generate.verify()
            except generate.GenerateAnsibleException as gae:
                print(gae.args)
                errors = True

        if errors:
            print('Found errors while generating module code.')
            raise SystemExit(1)

        print('\nAll generate scripts passed.\n')
开发者ID:ingvagabund,项目名称:openshift-ansible,代码行数:34,代码来源:setup.py


示例17: test_case_action_note_created_on_successful_action

    def test_case_action_note_created_on_successful_action(self):
        """
        If the action is successful, a case action note should be created.
        """
        with self.settings(PODS=[{'label': 'success_pod'}]):
            from casepro.pods import registry
            reload_module(registry)

        response = self.url_post_json(
            'unicef', reverse('perform_pod_action', args=('0',)), {
                'case_id': self.case.id,
                'action': {
                    'type': 'foo',
                    'payload': {'foo': 'bar'},
                },
            })

        self.assertEqual(response.status_code, 200)

        message = 'Type foo Params {"foo": "bar"}'
        self.assertEqual(response.json, {
            'success': True,
            'payload': {
                'message': message
            }
        })

        [caseaction] = CaseAction.objects.all()
        self.assertEqual(
            caseaction.note,
            "%s %s" % (self.admin.username, message))
开发者ID:xkmato,项目名称:casepro,代码行数:31,代码来源:test_views.py


示例18: tearDown

    def tearDown(self):
        """Clean ups"""
        if self.logger_patcher:
            self.logger_patcher.stop()

        self.module_patcher.stop()
        reload_module(actionlogger)
开发者ID:pywinauto,项目名称:pywinauto,代码行数:7,代码来源:test_actionlogger.py


示例19: tearDown

 def tearDown(self):
     if hasattr(conf.settings, 'DDF_DEFAULT_DATA_FIXTURE'): del conf.settings.DDF_DEFAULT_DATA_FIXTURE
     if hasattr(conf.settings, 'DDF_FILL_NULLABLE_FIELDS'): del conf.settings.DDF_FILL_NULLABLE_FIELDS
     if hasattr(conf.settings, 'DDF_IGNORE_FIELDS'): del conf.settings.DDF_IGNORE_FIELDS
     if hasattr(conf.settings, 'DDF_NUMBER_OF_LAPS'): del conf.settings.DDF_NUMBER_OF_LAPS
     if hasattr(conf.settings, 'DDF_VALIDATE_MODELS'): del conf.settings.DDF_VALIDATE_MODELS
     reload_module(conf)
开发者ID:PSU-OIT-ARC,项目名称:django-dynamic-fixture,代码行数:7,代码来源:test_global_settings.py


示例20: test_create_new_task

    def test_create_new_task(self):
        """Test a basic export."""
        self.import_course_tarball(self.repo)
        resources = LearningResource.objects.filter(
            course__repository__id=self.repo.id).all()
        for resource in resources:
            self.create_learning_resource_export(self.repo.slug, {
                "id": resource.id
            })

        # Skip first one to test that it's excluded from export.
        task_id = self.create_learning_resource_export_task(
            self.repo.slug,
            {"ids": [r.id for r in resources[1:]]}
        )['id']

        result = self.get_learning_resource_export_tasks(
            self.repo.slug)['results'][0]
        self.assertEqual(task_id, result['id'])
        self.assertEqual("success", result['status'])
        self.assertTrue(result['url'].startswith(
            "/media/resource_exports/test_exports.tar"))

        with self.settings(
            DEFAULT_FILE_STORAGE='storages.backends.s3boto.S3BotoStorage'
        ):
            # change the default file storage to S3
            reload_module(ui.urls)
            # the view is not available any more
            resp = self.client.get(result['url'])
            self.assertEqual(resp.status_code, HTTP_404_NOT_FOUND)

        # Update for change in file storage.
        reload_module(ui.urls)

        resp = self.client.get(result['url'])
        self.assertEqual(HTTP_200_OK, resp.status_code)

        tempdir = mkdtemp()

        def make_path(resource):
            """Create a path that should exist for a resource."""
            type_name = resource.learning_resource_type.name
            return os.path.join(
                tempdir, type_name, "{id}_{url_name}.xml".format(
                    id=resource.id,
                    url_name=slugify(resource.url_name)[:200],
                )
            )
        try:
            fakefile = BytesIO(b"".join(resp.streaming_content))
            with tarfile.open(fileobj=fakefile, mode="r:gz") as tar:
                tar.extractall(path=tempdir)

            self.assertFalse(os.path.isfile(make_path(resources[0])))
            assert_resource_directory(self, resources[1:], tempdir)

        finally:
            rmtree(tempdir)
开发者ID:jetej,项目名称:lore,代码行数:59,代码来源:test_export.py



注:本文中的six.moves.reload_module函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python moves.shlex_quote函数代码示例发布时间:2022-05-27
下一篇:
Python moves.reduce函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap