Beispiel #1
0
    def test_single_route_one_view_registered(self):
        from zope.interface import Interface
        from pyramid.registry import Registry
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IView

        registry = Registry()

        def view():
            pass

        class IMyRoute(Interface):
            pass

        registry.registerAdapter(view, (IViewClassifier, IMyRoute, Interface), IView, "")
        registry.registerUtility(IMyRoute, IRouteRequest, name="a")
        command = self._makeOne()
        route = DummyRoute("a", "/a")
        mapper = DummyMapper(route)
        command._get_mapper = lambda *arg: mapper
        L = []
        command.out = L.append
        app = DummyApp()
        app.registry = registry
        loadapp = DummyLoadApp(app)
        command.loadapp = (loadapp,)
        command.args = ("/foo/bar/myapp.ini", "myapp")
        result = command.command()
        self.assertEqual(result, None)
        self.assertEqual(len(L), 3)
        self.assertEqual(L[-1].split()[:4], ["a", "/a", "<function", "view"])
Beispiel #2
0
 def test_single_route_one_view_registered_with_factory(self):
     from zope.interface import Interface
     from pyramid.registry import Registry
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     registry = Registry()
     def view():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute(Interface):
         pass
     registry.registerAdapter(view,
                              (IViewClassifier, IMyRoute, IMyRoot),
                              IView, '')
     registry.registerUtility(IMyRoute, IRouteRequest, name='a')
     command = self._makeOne()
     def factory(request): pass
     route = dummy.DummyRoute('a', '/a', factory=factory)
     mapper = dummy.DummyMapper(route)
     command._get_mapper = lambda *arg: mapper
     L = []
     command.out = L.append
     command.bootstrap = (dummy.DummyBootstrap(registry=registry),)
     result = command.run()
     self.assertEqual(result, None)
     self.assertEqual(len(L), 3)
     self.assertEqual(L[-1].split()[:3], ['a', '/a', '<unknown>'])
Beispiel #3
0
 def test__find_view_route_multiview_no_view_registered(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IMultiView
     from pyramid.interfaces import IRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     def view1():pass
     def view2():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute1(Interface):
         pass
     class IMyRoute2(Interface):
         pass
     registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
     registry.registerUtility(IMyRoute2, IRouteRequest, name='b')
     @implementer(IMyRoot)
     class Factory(object):
         def __init__(self, request):
             pass
     registry.registerUtility(Factory, IRootFactory)
     routes = [dummy.DummyRoute('a', '/a', matchdict={}),
               dummy.DummyRoute('b', '/a', matchdict={})]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertTrue(IMultiView.providedBy(result))
Beispiel #4
0
 def setUp(self):
     self.__request = DummyRequest()
     # Must set hook_zca to false to work with uniittest_with_sqlite
     reg = Registry()
     reg.settings = {}
     reg.settings['disable.context.security'] = 'False'
     self.__config = testing.setUp(registry=reg, request=self.__request, hook_zca=False)
Beispiel #5
0
 def test__find_view_route_no_multiview(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     from pyramid.registry import Registry
     registry = Registry()
     def view():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute(Interface):
         pass
     registry.registerAdapter(view,
                              (IViewClassifier, IMyRoute, IMyRoot),
                              IView, '')
     registry.registerUtility(IMyRoute, IRouteRequest, name='a')
     @implementer(IMyRoot)
     class Factory(object):
         def __init__(self, request):
             pass
     routes = [dummy.DummyRoute('a', '/a', factory=Factory, matchdict={}),
               dummy.DummyRoute('b', '/b', factory=Factory)]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertEqual(result, view)
 def setUp(self):
     self.__request = DummyRequest()
     self.__request.matchdict['registration_id'] = 'a1-b2-c3-d4-e5'
     self.__request.headers['File-Name'] = 'dummy.zip'
     reg = Registry()
     reg.settings = {'hpz.frs.upload_base_path': '/dev/null', 'hpz.frs.file_size_limit': '1024'}
     self.__config = testing.setUp(registry=reg, request=self.__request, hook_zca=False)
Beispiel #7
0
 def test_single_route_one_view_registered(self):
     from zope.interface import Interface
     from pyramid.registry import Registry
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     registry = Registry()
     def view():pass
     class IMyRoute(Interface):
         pass
     registry.registerAdapter(view,
                              (IViewClassifier, IMyRoute, Interface),
                              IView, '')
     registry.registerUtility(IMyRoute, IRouteRequest, name='a')
     command = self._makeOne()
     route = dummy.DummyRoute('a', '/a')
     mapper = dummy.DummyMapper(route)
     command._get_mapper = lambda *arg: mapper
     L = []
     command.out = L.append
     command.bootstrap = (dummy.DummyBootstrap(registry=registry),)
     result = command.run()
     self.assertEqual(result, 0)
     self.assertEqual(len(L), 3)
     compare_to = L[-1].split()[:3]
     self.assertEqual(
         compare_to,
         ['a', '/a', 'pyramid.tests.test_scripts.test_proutes.view']
     )
Beispiel #8
0
    def setUp(self):
        cache_opts = {
            'cache.type': 'memory',
            'cache.regions': 'public.data,public.filtered_data,public.shortlived'
        }
        CacheManager(**parse_cache_config_options(cache_opts))
        self.__request = DummyRequest()
        # Must set hook_zca to false to work with uniittest_with_sqlite
        reg = Registry()
        reg.settings = {}
        reg.settings = {'extract.available_grades': '3,4,5,6,7,8,9,11',
                        'hpz.file_upload_base_url': 'http://somehost:82/files',
                        'extract.raw_data_base_dir': '/opt/edware/raw_data'}
        self.__config = testing.setUp(registry=reg, request=self.__request, hook_zca=False)
        self.__tenant_name = get_unittest_tenant_name()

        defined_roles = [(Allow, RolesConstants.AUDIT_XML_EXTRACTS, ('view', 'logout'))]
        edauth.set_roles(defined_roles)
        set_tenant_map({get_unittest_tenant_name(): 'NC'})
        # Set up context security
        dummy_session = create_test_session([RolesConstants.AUDIT_XML_EXTRACTS])
        self.__config.testing_securitypolicy(dummy_session.get_user())
        # celery settings for UT
        settings = {'extract.celery.CELERY_ALWAYS_EAGER': True}
        setup_celery(settings)
        # for UT purposes
        smarter.extracts.format.json_column_mapping = {}
        set_tenant_map({'tomcat': 'NC'})
Beispiel #9
0
    def test__find_view_traversal_multiview(self):
        from zope.interface import implementer
        from zope.interface import providedBy
        from pyramid.interfaces import IRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IMultiView
        from pyramid.traversal import DefaultRootFactory
        from pyramid.registry import Registry

        registry = Registry()

        @implementer(IMultiView)
        class View1(object):
            pass

        request = dummy.DummyRequest()
        request.path_info = '/a'
        root = DefaultRootFactory(request)
        root_iface = providedBy(root)
        view = View1()
        registry.registerAdapter(
            view, (IViewClassifier, IRequest, root_iface), IMultiView, name='a'
        )
        self._register_mapper(registry, [])
        command = self._makeOne(registry=registry)
        request = self._makeRequest('/a', registry)
        result = command._find_view(request)
        self.assertEqual(result, view)
Beispiel #10
0
 def setUp(self):
     self.__workspace = tempfile.mkdtemp()
     self.__staging = tempfile.mkdtemp()
     # setup request
     self.__request = DummyRequest()
     self.__request.method = 'POST'
     # setup settings
     # use the one for UDL
     here = os.path.abspath(os.path.dirname(__file__))
     self.gpg_home = os.path.abspath(os.path.join(here, '..', '..', '..', '..', 'config', 'gpg'))
     self.settings = {
         'smarter_score_batcher.gpg.keyserver': None,
         'smarter_score_batcher.gpg.homedir': self.gpg_home,
         'smarter_score_batcher.gpg.public_key.ca': '*****@*****.**',
         'smarter_score_batcher.gpg.public_key.cat': '*****@*****.**',
         'smarter_score_batcher.gpg.public_key.fish': '*****@*****.**',
         'smarter_score_batcher.gpg.path': 'gpg',
         'smarter_score_batcher.base_dir.working': self.__workspace,
         'smarter_score_batcher.base_dir.staging': self.__staging
     }
     # setup registr
     reg = Registry()
     reg.settings = self.settings
     self.__config = testing.setUp(registry=reg, request=self.__request, hook_zca=False)
     self._prepare_testing_files()
Beispiel #11
0
 def _makeRequest(self, **kwargs):
     """:rtype: pyramid.request.Request"""
     from pyramid.registry import Registry
     registry = Registry()
     registry.settings = {'app.timezone': 'Asia/Bangkok'}
     testing.setUp(registry=registry)
     return testing.DummyRequest(**kwargs)
Beispiel #12
0
 def test_single_route_one_view_registered_with_factory(self):
     from zope.interface import Interface
     from pyramid.registry import Registry
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     registry = Registry()
     def view():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute(Interface):
         pass
     registry.registerAdapter(view,
                              (IViewClassifier, IMyRoute, IMyRoot),
                              IView, '')
     registry.registerUtility(IMyRoute, IRouteRequest, name='a')
     command = self._makeOne()
     def factory(request): pass
     route = DummyRoute('a', '/a', factory=factory)
     mapper = DummyMapper(route)
     command._get_mapper = lambda *arg: mapper
     L = []
     command.out = L.append
     app = DummyApp()
     app.registry = registry
     loadapp = DummyLoadApp(app)
     command.loadapp = (loadapp,)
     command.args = ('/foo/bar/myapp.ini', 'myapp')
     result = command.command()
     self.assertEqual(result, None)
     self.assertEqual(len(L), 3)
     self.assertEqual(L[-1].split()[:3], ['a', '/a', '<unknown>'])
Beispiel #13
0
 def setUp(self):
     reg = Registry()
     reg.settings = {'store_type':'rdflib',
                     'debug_sparql':True}
     self.config = testing.setUp(reg)
     self.config.add_settings({'mako.directories':'plingback.sparql:templates'})
     self.config.add_renderer(None, mako_renderer_factory)
     self.config.begin()
Beispiel #14
0
def get_registry(settings):
    registry = Registry('testing')
    config = Configurator(registry=registry)
    if getattr(registry, 'settings', None) is None:
        config._set_settings(settings)
    registry.registerUtility(RoutesMapper(), IRoutesMapper)
    config.commit()
    return registry
 def test_dn_with_one_base_element(self):
     reg = Registry()
     reg.settings = {}
     reg.settings['ldap.base.dn'] = 'ou=dummy'
     self.__config = testing.setUp(registry=reg, request=DummyRequest(), hook_zca=False)
     attributes = {'dn': ['ou=dummyOrg,ou=dummy']}
     tenant = BasicIdentityParser.get_tenant_name(attributes)
     self.assertEqual(tenant[0], 'dummyorg')
Beispiel #16
0
 def test_add_settings_settings_None(self):
     from pyramid.registry import Registry
     from pyramid.interfaces import ISettings
     reg = Registry()
     config = self._makeOne(reg)
     config.add_settings(None, a=1)
     settings = reg.getUtility(ISettings)
     self.assertEqual(settings['a'], 1)
 def setUp(self):
     reg = Registry()
     reg.settings = {}
     reg.settings['session.backend.type'] = 'beaker'
     reg.settings['cache.expire'] = 10
     reg.settings['cache.regions'] = 'session'
     reg.settings['cache.type'] = 'memory'
     reg.settings['batch.user.session.timeout'] = 15
     component.provideUtility(SessionBackend(reg.settings), ISessionBackend)
Beispiel #18
0
    def test_setup_registry_debug_logger_None_default(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IDebugLogger

        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry()
        logger = reg.getUtility(IDebugLogger)
        self.assertEqual(logger.name, 'tests.test_config')
Beispiel #19
0
    def test_setup_registry_no_default_root_factory(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IRootFactory

        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry()
        config.commit()
        self.assertEqual(reg.queryUtility(IRootFactory), None)
Beispiel #20
0
def _set_local_roles(resource, new_local_roles: dict, registry: Registry):
    old_local_roles = getattr(resource, '__local_roles__', None)
    if new_local_roles == old_local_roles:
        return
    else:
        resource.__local_roles__ = new_local_roles
    event = LocalRolesModified(resource, new_local_roles, old_local_roles,
                               registry)
    registry.notify(event)
Beispiel #21
0
    def test_setup_registry_default_permission(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IDefaultPermission

        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry(default_permission='view')
        config.commit()
        self.assertEqual(reg.getUtility(IDefaultPermission), 'view')
Beispiel #22
0
    def test_setup_registry_debug_logger_name(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IDebugLogger

        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry(debug_logger='foo')
        result = reg.getUtility(IDebugLogger)
        self.assertEqual(result.name, 'foo')
Beispiel #23
0
    def test_add_settings_settings_not_yet_registered(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import ISettings

        reg = Registry()
        config = self._makeOne(reg)
        config.add_settings({"a": 1})
        settings = reg.getUtility(ISettings)
        self.assertEqual(settings["a"], 1)
Beispiel #24
0
 def _makeRegistry(self, **kw):
     """:rtype: pyramid.registry.Registry"""
     from pyramid.registry import Registry
     registry = Registry()
     registry.settings = {
         'app.timezone': 'Asia/Bangkok',
         'app.secret': 'demo',
     }
     registry.settings.update(kw)
     return registry
Beispiel #25
0
 def send_back_reference_removal_notificatons(self,
                                              references: [Reference],
                                              registry: Registry):
     """Send SheetBackReferenceRemoved to reference targets."""
     for reference in references:
         event = SheetBackReferenceRemoved(reference.target,
                                           reference.isheet,
                                           reference,
                                           registry)
         registry.notify(event)
Beispiel #26
0
    def test_setup_registry_debug_logger_non_None(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IDebugLogger

        logger = object()
        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry(debug_logger=logger)
        result = reg.getUtility(IDebugLogger)
        self.assertEqual(logger, result)
Beispiel #27
0
    def test_setup_registry_alternate_renderers(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IRendererFactory

        renderer = object()
        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry(renderers=[('yeah', renderer)])
        config.commit()
        self.assertEqual(reg.getUtility(IRendererFactory, 'yeah'), renderer)
 def setUp(self):
     self.__request = DummyRequest()
     # Must set hook_zca to false to work with uniittest_with_sqlite
     reg = Registry()
     reg.settings = {}
     reg.settings['cache.expire'] = 10
     reg.settings['cache.regions'] = 'session'
     reg.settings['cache.type'] = 'memory'
     reg.settings['batch.user.session.timeout'] = 15
     component.provideUtility(SessionBackend(reg.settings), ISessionBackend)
     self.__config = testing.setUp(registry=reg, request=self.__request, hook_zca=False)
Beispiel #29
0
 def setUp(self):
     registry = Registry()
     registry.settings = settings
     self.config = testing.setUp(registry=registry)
     # setup db
     DBSession.configure(bind=engine)
     Base.metadata.bind = engine
     Base.metadata.drop_all()
     Base.metadata.create_all()
     # setup request
     self.request = testing.DummyRequest()
Beispiel #30
0
    def test_setup_registry_authentication_policy(self):
        from pyramid.registry import Registry
        from pyramid.interfaces import IAuthenticationPolicy

        policy = object()
        reg = Registry()
        config = self._makeOne(reg)
        config.setup_registry(authentication_policy=policy)
        config.commit()
        result = reg.getUtility(IAuthenticationPolicy)
        self.assertEqual(policy, result)
 def test_single_route_one_view_registered_with_factory(self):
     from zope.interface import Interface
     from pyramid.registry import Registry
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     registry = Registry()
     def view():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute(Interface):
         pass
     registry.registerAdapter(view,
                              (IViewClassifier, IMyRoute, IMyRoot),
                              IView, '')
     registry.registerUtility(IMyRoute, IRouteRequest, name='a')
     command = self._makeOne()
     def factory(request): pass
     route = DummyRoute('a', '/a', factory=factory)
     mapper = DummyMapper(route)
     command._get_mapper = lambda *arg: mapper
     L = []
     command.out = L.append
     command.bootstrap = (DummyBootstrap(registry=registry),)
     result = command.command()
     self.assertEqual(result, None)
     self.assertEqual(len(L), 3)
     self.assertEqual(L[-1].split()[:3], ['a', '/a', '<unknown>'])
 def test__find_view_route_no_multiview(self):
     from zope.interface import Interface
     from zope.interface import implements
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     from pyramid.registry import Registry
     registry = Registry()
     def view():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute(Interface):
         pass
     registry.registerAdapter(view,
                              (IViewClassifier, IMyRoute, IMyRoot),
                              IView, '')
     registry.registerUtility(IMyRoute, IRouteRequest, name='a')
     class Factory(object):
         implements(IMyRoot)
         def __init__(self, request):
             pass
     routes = [DummyRoute('a', '/a', factory=Factory, matchdict={}),
               DummyRoute('b', '/b', factory=Factory)]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertEqual(result, view)
Beispiel #33
0
    def test_single_route_one_view_registered(self):
        from zope.interface import Interface
        from pyramid.registry import Registry
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IView
        registry = Registry()

        def view():
            pass

        class IMyRoute(Interface):
            pass

        registry.registerAdapter(view, (IViewClassifier, IMyRoute, Interface),
                                 IView, '')
        registry.registerUtility(IMyRoute, IRouteRequest, name='a')
        command = self._makeOne()
        route = dummy.DummyRoute('a', '/a')
        mapper = dummy.DummyMapper(route)
        command._get_mapper = lambda *arg: mapper
        L = []
        command.out = L.append
        command.bootstrap = (dummy.DummyBootstrap(registry=registry), )
        result = command.run()
        self.assertEqual(result, 0)
        self.assertEqual(len(L), 3)
        self.assertEqual(L[-1].split()[:4], ['a', '/a', '<function', 'view'])
 def test__find_view_route_multiview(self):
     from zope.interface import Interface
     from zope.interface import implements
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IView
     from pyramid.interfaces import IMultiView
     from pyramid.interfaces import IRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     def view1():pass
     def view2():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute1(Interface):
         pass
     class IMyRoute2(Interface):
         pass
     registry.registerAdapter(view1,
                              (IViewClassifier, IMyRoute1, IMyRoot),
                              IView, '')
     registry.registerAdapter(view2,
                              (IViewClassifier, IMyRoute2, IMyRoot),
                              IView, '')
     registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
     registry.registerUtility(IMyRoute2, IRouteRequest, name='b')
     class Factory(object):
         implements(IMyRoot)
         def __init__(self, request):
             pass
     registry.registerUtility(Factory, IRootFactory)
     routes = [DummyRoute('a', '/a', matchdict={}),
               DummyRoute('b', '/a', matchdict={})]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertTrue(IMultiView.providedBy(result))
     self.assertEqual(len(result.views), 2)
     self.assertTrue((None, view1, None) in result.views)
     self.assertTrue((None, view2, None) in result.views)
Beispiel #35
0
 def test__find_view_route_multiview_no_view_registered(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from pyramid.interfaces import IRouteRequest
     from pyramid.interfaces import IMultiView
     from pyramid.interfaces import IRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     def view1():pass
     def view2():pass
     class IMyRoot(Interface):
         pass
     class IMyRoute1(Interface):
         pass
     class IMyRoute2(Interface):
         pass
     registry.registerUtility(IMyRoute1, IRouteRequest, name='a')
     registry.registerUtility(IMyRoute2, IRouteRequest, name='b')
     @implementer(IMyRoot)
     class Factory(object):
         def __init__(self, request):
             pass
     registry.registerUtility(Factory, IRootFactory)
     routes = [dummy.DummyRoute('a', '/a', matchdict={}),
               dummy.DummyRoute('b', '/a', matchdict={})]
     self._register_mapper(registry, routes)
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertTrue(IMultiView.providedBy(result))
Beispiel #36
0
    def test_single_route_one_view_registered(self):
        from zope.interface import Interface
        from pyramid.registry import Registry
        from pyramid.interfaces import IRouteRequest
        from pyramid.interfaces import IViewClassifier
        from pyramid.interfaces import IView
        registry = Registry()

        def view():
            pass

        class IMyRoute(Interface):
            pass

        registry.registerAdapter(view, (IViewClassifier, IMyRoute, Interface),
                                 IView, '')
        registry.registerUtility(IMyRoute, IRouteRequest, name='a')
        command = self._makeOne()
        route = DummyRoute('a', '/a')
        mapper = DummyMapper(route)
        command._get_mapper = lambda *arg: mapper
        L = []
        command.out = L.append
        app = DummyApp()
        app.registry = registry
        loadapp = DummyLoadApp(app)
        command.loadapp = (loadapp, )
        command.args = ('/foo/bar/myapp.ini', 'myapp')
        result = command.command()
        self.assertEqual(result, None)
        self.assertEqual(len(L), 3)
        self.assertEqual(L[-1].split()[:4], ['a', '/a', '<function', 'view'])
 def __init__(self,
              registry=None,
              package=None,
              settings=None,
              root_factory=None,
              authentication_policy=None,
              authorization_policy=None,
              renderers=None,
              debug_logger=None,
              locale_negotiator=None,
              request_factory=None,
              response_factory=None,
              default_permission=None,
              session_factory=None,
              default_view_mapper=None,
              autocommit=False,
              exceptionresponse_view=default_exceptionresponse_view,
              route_prefix=None,
              introspection=True,
              root_package=None,
              ):
     if package is None:
         package = caller_package()
     if root_package is None:
         root_package = package
     name_resolver = DottedNameResolver(package)
     self.name_resolver = name_resolver
     self.package_name = name_resolver.get_package_name()
     self.package = name_resolver.get_package()
     self.root_package = root_package
     self.registry = registry
     self.autocommit = autocommit
     self.route_prefix = route_prefix
     self.introspection = introspection
     if registry is None:
         registry = Registry(self.package_name)
         self.registry = registry
         self.setup_registry(
             settings=settings,
             root_factory=root_factory,
             authentication_policy=authentication_policy,
             authorization_policy=authorization_policy,
             renderers=renderers,
             debug_logger=debug_logger,
             locale_negotiator=locale_negotiator,
             request_factory=request_factory,
             response_factory=response_factory,
             default_permission=default_permission,
             session_factory=session_factory,
             default_view_mapper=default_view_mapper,
             exceptionresponse_view=exceptionresponse_view,
             )
Beispiel #38
0
    def test__get_mapper(self):
        from pyramid.registry import Registry
        from pyramid.urldispatch import RoutesMapper
        command = self._makeOne()
        registry = Registry()

        class App:
            pass

        app = App()
        app.registry = registry
        result = command._get_mapper(app)
        self.assertEqual(result.__class__, RoutesMapper)
Beispiel #39
0
def test_includeme_use_celeryconfig():
    from pyramid_celery import includeme
    from pyramid_celery import celery_app
    from pyramid import testing
    from pyramid.registry import Registry
    config = testing.setUp()
    config.registry = Registry()
    config.registry.settings = {}

    includeme(config)
    config.configure_celery('tests/configs/useceleryconfig.ini')

    assert celery_app.conf['broker_url'] == 'redis://localhost:1337/0'
Beispiel #40
0
def get_social_login_mapper(registry: Registry,
                            provider_id: str) -> ISocialLoginMapper:
    """Get a named social login mapper.

    Example::

        get_social_login_mapper(registry, "facebook")

    :param registry: Pyramid registry.
    :param provider_id: Provider id of a social login mapper.
    :return: Implementation of ISocialLoginMapper.
    """
    return registry.queryUtility(ISocialLoginMapper, name=provider_id)
Beispiel #41
0
    def test_registry_is_config_registry_when_setup_is_called_after_ctor(self):
        # see https://github.com/Pylons/pyramid/issues/165
        from pyramid.registry import Registry
        from pyramid.config import Configurator

        request = self._makeOne()
        try:
            registry = Registry('this_test')
            config = Configurator(registry=registry)
            config.begin()
            self.assertTrue(request.registry is registry)
        finally:
            config.end()
 def test__find_view_traversal_multiview(self):
     from zope.interface import implements
     from zope.interface import providedBy
     from pyramid.interfaces import IRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IMultiView
     from pyramid.traversal import DefaultRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     class View1(object):
         implements(IMultiView)
     request = DummyRequest({'PATH_INFO':'/a'})
     root = DefaultRootFactory(request)
     root_iface = providedBy(root)
     view = View1()
     registry.registerAdapter(view,
                              (IViewClassifier, IRequest, root_iface),
                              IMultiView, name='a')
     self._register_mapper(registry, [])
     command = self._makeOne(registry=registry)
     result = command._find_view('/a', registry)
     self.assertEqual(result, view)
Beispiel #43
0
 def test_views_command_not_found_url_starts_without_slash(self):
     from pyramid.registry import Registry
     registry = Registry()
     command = self._makeOne(registry=registry)
     L = []
     command.out = L.append
     command._find_view = lambda arg1: None
     command.args.config_uri = '/foo/bar/myapp.ini#myapp'
     command.args.url = 'a'
     result = command.run()
     self.assertEqual(result, 0)
     self.assertEqual(L[1], 'URL = /a')
     self.assertEqual(L[3], '    Not found.')
Beispiel #44
0
    def test_setup_registry_includes_spaces(self):
        from pyramid.registry import Registry

        reg = Registry()
        config = self._makeOne(reg)
        settings = {
            'pyramid.includes':
            """tests.test_config.dummy_include tests.\
test_config.dummy_include2"""
        }
        config.setup_registry(settings=settings)
        self.assertTrue(reg.included)
        self.assertTrue(reg.also_included)
Beispiel #45
0
def get_input_widget(
    registry: Registry,
    node: ColanderNode,
    node_type: Optional[colander.SchemaType] = None,
) -> Optional[InputWidget]:
    node_type = node_type or node.typ
    converter: Optional[InputConverter] = registry.queryAdapter(
        node_type, interfaces.ISchemaNodeToInputWidget)
    if converter:
        widget = converter(registry, node, node_type)
        if widget:
            widget = _try_convert_to_select_input(registry, widget, node)
        return widget
 def setUp(self):
     # delete all user_session before test
     mappings = {('Allow', 'TEACHER', ('view', 'logout', 'default')),
                 ('Allow', 'SYSTEM_ADMINISTRATOR', ('view', 'logout')),
                 ('Allow', 'DATA_LOADER', ('view', 'logout')),
                 ('Allow', 'NONE', ('logout'))}
     Roles.set_roles(mappings)
     set_tenant_map({get_unittest_tenant_name(): 'NC'})
     self.__request = DummyRequest()
     reg = Registry()
     reg.settings = {}
     reg.settings['session.backend.type'] = 'beaker'
     reg.settings['cache.expire'] = 10
     reg.settings['cache.regions'] = 'session'
     reg.settings['cache.type'] = 'memory'
     reg.settings['ldap.base.dn'] = 'ou=environment,dc=edwdc,dc=net'
     reg.settings['batch.user.session.timeout'] = 15
     component.provideUtility(SessionBackend(reg.settings), ISessionBackend)
     # Must set hook_zca to false to work with uniittest_with_sqlite
     self.__config = testing.setUp(registry=reg,
                                   request=self.__request,
                                   hook_zca=False)
Beispiel #47
0
 def test__find_view_no_match_multiview_registered(self):
     from zope.interface import implementer
     from zope.interface import providedBy
     from pyramid.interfaces import IRequest
     from pyramid.interfaces import IViewClassifier
     from pyramid.interfaces import IMultiView
     from pyramid.traversal import DefaultRootFactory
     from pyramid.registry import Registry
     registry = Registry()
     @implementer(IMultiView)
     class View1(object):
         pass
     request = dummy.DummyRequest({'PATH_INFO':'/a'})
     root = DefaultRootFactory(request)
     root_iface = providedBy(root)
     registry.registerAdapter(View1(),
                              (IViewClassifier, IRequest, root_iface),
                              IMultiView)
     self._register_mapper(registry, [])
     command = self._makeOne(registry=registry)
     result = command._find_view('/x', registry)
     self.assertEqual(result, None)
Beispiel #48
0
 def test_it_with_settings_passed_explicit_registry(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     from pyramid.registry import Registry
     registry = Registry()
     try:
         self._callFUT(registry=registry,
                       hook_zca=False,
                       settings=dict(a=1))
         self.assertEqual(registry.settings['a'], 1)
     finally:
         getSiteManager.reset()
         manager.clear()
Beispiel #49
0
def test_celery_imports():
    from pyramid_celery import includeme, celery_app
    from pyramid import testing
    from pyramid.registry import Registry
    config = testing.setUp()
    config.registry = Registry()
    config.registry.settings = {}

    includeme(config)
    config.configure_celery('tests/configs/imports.ini')

    assert celery_app.conf['CELERY_IMPORTS'] == [
        'myapp.tasks', 'otherapp.tasks'
    ]
Beispiel #50
0
    def test_registration_valid_url(self, persist_patch):
        reg = Registry()
        reg.settings = {'hpz.frs.download_base_url': 'http://blah/download'}
        self.__config = testing.setUp(registry=reg,
                                      request=self.__request,
                                      hook_zca=False)

        persist_patch.return_value = None

        self.__request.method = 'PUT'
        self.__request.json_body = {'uid': '1234', 'email': '*****@*****.**'}

        response = put_file_registration_service(None, self.__request)

        self.assertEqual(response.status_code, 200)

        response_json = json.loads(str(response.body, encoding='UTF-8'))

        self.assertTrue('url' in response_json)
        self.assertTrue('registration_id' in response_json)
        registration_id = response_json['registration_id']
        self.assertEqual('http://blah/files/' + registration_id,
                         response_json['url'])
Beispiel #51
0
def create_user(dbsession: Session,
                registry: Registry,
                email: str = EMAIL,
                password: str = PASSWORD,
                admin: bool = False) -> User:
    """A helper function to create normal and admin users for tests.

    Example:

    .. code-block:: python

        import transaction
        from websauna.tests.utils import create_user


        def test_some_stuff(dbsession, registry):

            with transaction.manager:
                u = create_user(registry)
                # Do stuff with new user



    :param email: User's email address. If inot given use unit testing default.

    :param password: Password as plain text. If not given use unit testing default.

    :param admin: If True run :py:class:`websauna.system.user.usermixin.SiteCreator` login and set the user to admin group.
    """

    user = User(email=email)

    if password:
        hasher = registry.getUtility(IPasswordHasher)
        user.hashed_password = hasher.hash_password(password)

    user.user_registration_source = "dummy"
    dbsession.add(user)
    dbsession.flush()
    user.username = user.generate_username()
    user.activated_at = now()

    assert user.can_login()

    # First user, make it admin
    if admin:
        site_creator = get_site_creator(registry)
        site_creator.init_empty_site(dbsession, user)

    return user
def test_push_no_renderer(dbsession: Session, user_id):
    """Create a new activity, but we do not have renderer for it yet."""

    request = make_dummy_request(dbsession, Registry())

    with transaction.manager:
        u = dbsession.query(User).get(user_id)

        # This will trigger email on transaction commit
        a = create_activity(request, "demo_msg", {}, uuid4(), u)

        channel = Email(request)
        with pytest.raises(NoRendererRegistered):
            channel.push_notification(a)
Beispiel #53
0
    def test_setup_registry_tweens(self):
        from pyramid.interfaces import ITweens
        from pyramid.registry import Registry

        reg = Registry()
        config = self._makeOne(reg)
        settings = {'pyramid.tweens': 'tests.test_config.dummy_tween_factory'}
        config.setup_registry(settings=settings)
        config.commit()
        tweens = config.registry.getUtility(ITweens)
        self.assertEqual(
            tweens.explicit,
            [('tests.test_config.dummy_tween_factory', dummy_tween_factory)],
        )
Beispiel #54
0
 def test_rest_view(self):
     from arguxserver.views import MainViews
     #request = testing.DummyRequest(params={'host':'a','items':'b'},path='/argux/rest/1.0/host/a')
     r = request.Request.blank(path='/argux/rest/1.0/a/b')
     r.registry = Registry()
     r.registry.settings = {}
     r.registry.settings['dao'] = dao.DAO()
     r.matchdict = {
         'host': 'localhost',
         'item': 'NONE',
         'action': 'details'
     }
     v = MainViews(r)
     info = v.item_details()
Beispiel #55
0
    def __init__(self, registry: Registry):
        """Create a new instance.

        :param registry: used to retrieve and configure the mailer
        """
        self.registry = registry
        settings = registry.settings
        self.use_mail_queue = asbool(
            settings.get('adhocracy.use_mail_queue', False))
        logger.debug('Messenger will use mail queue: %s', self.use_mail_queue)
        self.abuse_handler_mail = settings.get('adhocracy.abuse_handler_mail')
        self.site_name = settings.get('adhocracy.site_name', 'Adhocracy')
        self.frontend_url = settings.get('adhocracy.frontend_url',
                                         'http://localhost:6551')
        self.mailer = registry.getUtility(IMailer)
Beispiel #56
0
    def test_single_route_no_views_registered(self):
        from zope.interface import Interface
        from pyramid.registry import Registry
        from pyramid.interfaces import IRouteRequest
        registry = Registry()

        def view():
            pass

        class IMyRoute(Interface):
            pass

        registry.registerUtility(IMyRoute, IRouteRequest, name='a')
        command = self._makeOne()
        route = dummy.DummyRoute('a', '/a')
        mapper = dummy.DummyMapper(route)
        command._get_mapper = lambda *arg: mapper
        L = []
        command.out = L.append
        command.bootstrap = (dummy.DummyBootstrap(registry=registry), )
        result = command.run()
        self.assertEqual(result, None)
        self.assertEqual(len(L), 3)
        self.assertEqual(L[-1].split()[:3], ['a', '/a', 'None'])
Beispiel #57
0
def open_pyramid_request(
        registry: Registry,
        path='http://localhost') -> ContextManager[PyramidRequest]:
    request_factory = registry.queryUtility(IRequestFactory, default=Request)
    request: PyramidRequest = request_factory.blank(path)
    request.registry = registry
    apply_request_extensions(request)
    get_pyramid_root(request)
    context = RequestContext(request)
    context.begin()
    try:
        yield request
    finally:
        request._process_finished_callbacks()
        context.end()
Beispiel #58
0
 def test_del_registry(self):
     # see https://github.com/Pylons/pyramid/issues/165
     from pyramid.registry import Registry
     from pyramid.config import Configurator
     request = self._makeOne()
     request.registry = 'abc'
     self.assertEqual(request.registry, 'abc')
     del request.registry
     try:
         registry = Registry('this_test')
         config = Configurator(registry=registry)
         config.begin()
         self.assertTrue(request.registry is registry)
     finally:
         config.end()
Beispiel #59
0
    def test_include_me(self):
        from pyramid.config import Configurator
        from pyramid.registry import Registry
        from pyramid.interfaces import ISessionFactory
        from pyramid_nacl_session import includeme

        settings = {"session.secret": self.default_secret}
        reg = Registry()
        config = Configurator(reg)
        config.add_settings(settings)
        config.include(includeme)
        config.commit()
        factory = self._makeOne()
        self.assertIs(type(config.registry.getUtility(ISessionFactory)),
                      type(factory))
    def setUp(self):
        cache_opts = {
            'cache.type': 'memory',
            'cache.regions': 'public.shortlived'
        }
        CacheManager(**parse_cache_config_options(cache_opts))
        self.__request = DummyRequest()
        # Must set hook_zca to false to work with uniittest_with_sqlite
        reg = Registry()
        # Set up defined roles
        self.__tenant_name = get_unittest_tenant_name()
        set_tenant_map({self.__tenant_name: "NC"})
        self.__temp_dir = tempfile.mkdtemp()
        reg.settings = {}
        reg.settings['pdf.report_base_dir'] = self.__temp_dir
        self.__config = testing.setUp(registry=reg,
                                      request=self.__request,
                                      hook_zca=False)

        defined_roles = [(Allow, RolesConstants.PII, ('view', 'logout'))]
        edauth.set_roles(defined_roles)
        # Set up context security
        dummy_session = create_test_session([RolesConstants.PII])
        dummy_session.set_user_context([
            RoleRelation(RolesConstants.PII, self.__tenant_name, 'NC', '228',
                         '242'),
            RoleRelation(RolesConstants.PII, self.__tenant_name, 'NC', '229',
                         '939')
        ])
        self.__config.testing_securitypolicy(dummy_session.get_user())

        # celery settings for UT
        settings = {'services.celery.CELERY_ALWAYS_EAGER': True}
        self.__request.matchdict[Constants.REPORT] = 'indivStudentReport.html'
        self.__request.cookies = {'edware': '123'}
        setup_celery(settings)