def test_websocket_bad_origin(): settings = {'origins': 'http://good'} with testConfig(settings=settings) as config: config.include('h.streamer') req = DummyRequest(headers={'Origin': 'http://bad'}) res = websocket(req) assert res.code == 403
def test_it_another_request_type(self): """ on /foo/craete, success redirect is /foo/list """ from pyramid.testing import testConfig from zope.interface import Interface class IAPIRequest(Interface): pass with testConfig(autocommit=False) as config: config.include("mokehehe.workflow") config.add_route("foo.list", "/foo/list") config.add_route("foo.create", "/foo/create") config.add_route("foo.api.list", "/api/foo/list") with config.get_workflow().sub(IAfterModelCreate) as goto: goto("foo.create", "foo.list") goto("foo.create", "foo.api.list", request_type=IAPIRequest) config.commit() ### on request time. api request request2 = self._makeRequest(config) class route: name = "foo.create" request2.matched_route = route from zope.interface import directlyProvides directlyProvides(request2, IAPIRequest) ##on tweens result = request2.workflow[IAfterModelCreate].route_path() self.assertEqual(result, "/api/foo/list")
def test_register_models(self): with testing.testConfig() as config: config.include('c2cgeoform.routes') class MyModel: __tablename__ = 'mytable' register_models(config, [('mytable', MyModel)]) register_routes(config, multi_application=False) request = testing.DummyRequest(environ={'PATH_INFO': '/mytable'}) routes_mapper = config.registry.queryUtility(IRoutesMapper) info = routes_mapper(request) match, route = info['match'], info['route'] self.assertEqual('c2cgeoform_index', route.name) self.assertEqual('mytable', match['table']) # We should have the single application in request.c2cgeoform_application application = get_application(request) self.assertTrue(isinstance(application, Application)) self.assertEqual('mytable', application.tables()[0]['key']) self.assertEqual( 'http://example.com/table', request.route_url('c2cgeoform_index', table='table'))
def views(redis, session): request = DummyRequest() with testing.testConfig(request=request) as config: config.include("pyramid_chameleon") setattr(request, "db_session", session) setattr(request.registry, "redis_client", redis) yield ContentViews(request)
def test_form_not_submitted(self): from pyramid.testing import testConfig class DummyRenderer(object): def __init__(self, macros): self.macros = macros def implementation(self): return self request = testing.DummyRequest() request.sdiapi = DummySDIAPI() context = testing.DummyResource() form, reset = object(), object() renderer = DummyRenderer({ 'login-form': form, 'password-reset-link': reset }) with testConfig() as config: config.testing_add_renderer( 'substanced.sdi.views:templates/login.pt', renderer) result = self._callFUT(context, request) self.assertEqual(result['url'], '/mgmt_path') self.assertEqual(result['came_from'], 'http://example.com') self.assertEqual(result['login'], '') self.assertEqual(result['password'], '') self.assertTrue(result['login_template'] is renderer) self.assertEqual(request.session['sdi.came_from'], 'http://example.com')
def views(self, map_config, redis, session): request = DummyRequest() with testing.testConfig(request=request) as config: config.include('pyramid_chameleon') setattr(request, 'db_session', session) setattr(request.registry, 'redis_client', redis) yield ContentViews(request)
def test_not_match(self): with testing.testConfig() as config: self._config(config, 'app') pred = ApplicationRoutePredicate(config, 'anything') context = {'match': {'application': 'not_registered_application'}} request = testing.DummyRequest() self.assertFalse(pred(context, request))
def pyramid_config(pyramid_request): """ Return a test Pyramid config (Configurator) object. The returned Configurator uses the dummy request from the pyramid_request fixture above. """ with testing.testConfig(request=pyramid_request, settings=TEST_SETTINGS) as config: config.include("pyramid_jinja2") config.include("pyramid_services") config.include("pyramid_tm") config.include("lms.sentry") config.include("lms.models") config.include("lms.db") config.include("lms.routes") config.add_static_view(name="export", path="lms:static/export") config.add_static_view(name="static", path="lms:static") config.action(None, configure_jinja2_assets, args=(config, )) apply_request_extensions(pyramid_request) yield config
def test_functional_using_assetspec(self): from ..._compat import u renderer = self._makeOne(()) with testing.testConfig() as config: config.include('pyramid_chameleon') result = renderer('substanced.widget.tests:fixtures/test.pt') self.assertEqual(result.strip(), u('<div>Test</div>'))
def test_get_rev_links_with_switched_storage(self): # If we have a model that was loaded from elasticsearch # but the datastore is now database, we need to be sure # to get the rev links from the database. from pyramid.testing import ( DummyRequest, testConfig, ) from ..esstorage import ( CachedModel, PickStorage, ) model = CachedModel({'_source': {'uuid': 'dummy'}}) model2 = Mock() read = Mock() write = Mock() write.get_by_uuid.return_value = model2 storage = PickStorage(read, write) request = DummyRequest() request.datastore = 'database' with testConfig(request=request): storage.get_rev_links(model, 'rel') assert write.get_rev_links.called_once rev_links_model = write.get_rev_links.call_args[0][0] assert rev_links_model is model2
def test_get_macro_without_name(self): request = testing.DummyRequest() inst = self._makeOne(request) with testing.testConfig() as config: config.include('pyramid_chameleon') macro = inst.get_macro('substanced.sdi.views:templates/master.pt') self.assertTrue(macro.macros)
def test_openapi_view() -> None: """Test registration a an openapi view.""" with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as document: document.write(MINIMAL_DOCUMENT) document.seek(0) config.pyramid_openapi3_spec(document.name, route="/foo.yaml", route_name="foo_api_spec") config.add_route("foo", "/foo") view_func = lambda *arg: "bar" # noqa: E731 config.add_view(openapi=True, renderer="json", view=view_func, route_name="foo") request_interface = config.registry.queryUtility(IRouteRequest, name="foo") view = config.registry.adapters.registered( (IViewClassifier, request_interface, Interface), IView, name="") request = DummyRequest(config=config, content_type="text/html") apply_request_extensions(request) request.matched_route = DummyRoute(name="foo", pattern="/foo") context = None response = view(context, request) assert response.json == "bar"
def pyramid_config(pyramid_request): """ Return a test Pyramid config (Configurator) object. The returned Configurator uses the dummy request from the pyramid_request fixture above. """ # Settings that will end up in pyramid_request.registry.settings. settings = { 'lti_server': 'http://TEST_LTI_SERVER.com', 'sqlalchemy.url': TEST_DATABASE_URL, 'client_origin': 'http://TEST_H_SERVER.is', 'via_url': 'http://TEST_VIA_SERVER.is', } with testing.testConfig(request=pyramid_request, settings=settings) as config: config.include('pyramid_services') config.include('lti.db') apply_request_extensions(pyramid_request) # auth_data_svc = mock.create_autospec(auth_data.AuthDataService, instance=True) # auth_data_svc.get_canvas_server.return_value = 'https://TEST_CANVAS_SERVER.com' # auth_data_svc.get_lti_secret.return_value = 'TEST_CLIENT_SECRET' # auth_data_svc.get_lti_token.return_value = 'TEST_OAUTH_ACCESS_TOKEN' # auth_data_svc.get_lti_refresh_token.return_value = 'TEST_OAUTH_REFRESH_TOKEN' # config.register_service(auth_data_svc, name='auth_data') yield config
def test_register_routes_with_factory() -> None: """Test registration routes with root_factory.""" with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as tempdoc: tempdoc.write( b"""\ openapi: "3.0.0" info: version: "1.0.0" title: Foo API paths: /foo: x-pyramid-route-name: foo x-pyramid-root-factory: pyramid_openapi3.tests.test_routes.dummy_factory get: responses: 200: description: A foo """ ) tempdoc.seek(0) config.pyramid_openapi3_spec(tempdoc.name) config.pyramid_openapi3_register_routes() config.make_wsgi_app()
def test_add_spec_view() -> None: """Test registration of a view that serves the openapi document.""" with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as document: document.write(MINIMAL_DOCUMENT) document.seek(0) config.pyramid_openapi3_spec(document.name, route="/foo.yaml", route_name="foo_api_spec") # assert settings openapi_settings = config.registry.settings["pyramid_openapi3"] assert openapi_settings["filepath"] == document.name assert openapi_settings["spec_route_name"] == "foo_api_spec" assert openapi_settings["spec"].info.title == "Foo API" assert isinstance(openapi_settings["request_validator"], RequestValidator) assert isinstance(openapi_settings["response_validator"], ResponseValidator) # assert route mapper = config.registry.getUtility(IRoutesMapper) routes = mapper.get_routes() assert routes[0].name == "foo_api_spec" assert routes[0].path == "/foo.yaml" # assert view request = config.registry.queryUtility(IRouteRequest, name="foo_api_spec") view = config.registry.adapters.registered( (IViewClassifier, request, Interface), IView, name="") assert view(request=None, context=None).body == MINIMAL_DOCUMENT
def test_subscriber_predicate(settings): """Test that the ``asset_request`` subscriber predicate. It should correctly match asset requests when its value is ``True``, and other requests when ``False``. """ mock1 = Mock() mock2 = Mock() with testConfig(settings=settings) as config: config.include(assets) config.add_subscriber(mock1, DummyEvent, asset_request=False) config.add_subscriber(mock2, DummyEvent, asset_request=True) request1 = DummyRequest('/') request1.matched_route = None pattern = config.get_webassets_env().url + '*subpath' request2 = DummyRequest(config.get_webassets_env().url + '/t.png') request2.matched_route = Route('__' + pattern, pattern) event1 = DummyEvent(request1) event2 = DummyEvent(request2) config.registry.notify(event1) config.registry.notify(event2) mock1.assert_called_onceventwith(event1) mock2.assert_called_onceventwith(event2)
def test_echo(): with testConfig() as config: config.add_route('echo', '/echo/{name}') req = DummyRequest(path='/echo/hello') resp = echo(req) assert resp.body == 'hello'
def test_subscriber_predicate(settings): """Test that the ``asset_request`` subscriber predicate. It should correctly match asset requests when its value is ``True``, and other requests when ``False``. """ mock1 = Mock() mock2 = Mock() with testConfig(settings=settings) as config: # pylint: disable=attribute-defined-outside-init config.include(assets) config.add_subscriber(mock1, DummyEvent, asset_request=False) config.add_subscriber(mock2, DummyEvent, asset_request=True) request1 = DummyRequest('/') request1.matched_route = None pattern = config.get_webassets_env().url + '*subpath' request2 = DummyRequest(config.get_webassets_env().url + '/t.png') request2.matched_route = Route('__' + pattern, pattern) event1 = DummyEvent(request1) event2 = DummyEvent(request2) config.registry.notify(event1) config.registry.notify(event2) mock1.assert_called_onceventwith(event1) mock2.assert_called_onceventwith(event2)
def test_route_with_all(self): from c2cgeoportal_geoportal.views.dynamic import DynamicView with testConfig( settings=self._get_settings( { "test": { "routes": { "XTest": { "name": "route_with_all", "kw": {"key1": "v1", "key2": "v2"}, "elements": ["s1", "s2"], "params": {"test": "value"}, } } } } ) ) as config: config.add_static_view(name="static", path="/etc/geomapfish/static") config.add_route("base", "/", static=True) config.add_route("test", "/test") config.add_route("route_with_all", "/test/{key1}/{key2}") request = DummyRequest({"interface": "test"}) request.get_organization_interface = lambda interface: interface dynamic = DynamicView(request).dynamic() assert "XTest" in dynamic["constants"], dynamic assert dynamic["constants"]["XTest"] == "http://example.com/test/v1/v2/s1/s2?test=value"
def test_view_notfound(self): with testing.testConfig(): request = testing.DummyRequest() request.matchdict['prefix'] = 'aaaa' request.matchdict['name'] = 'nonexistent-image.jpg' with self.assertRaises(HTTPNotFound): ImageView(request)()
def test_alternate_homepage(self, config): request = DummyRequest() with testing.testConfig(request=request) as config: assert not configure_content(config, enable=False) res = empty_homepage_view(request) assert res.content_type == 'text/html' assert b'It works' in res.body
def test_init_with_debug(capsys, mock_timestamper): logger = structlog.get_logger() # Configure pyramid app settings = {'logging.level': 'DEBUG'} with pyramid_testing.testConfig(settings=settings) as config: config.include(includeme) # Create some log messages logger.info('info msg') logger.debug('debug msg') logger.error('error msg') # Check for results captured = capsys.readouterr() expected = ( "event='logging configuration initialized' logger='press.logging'" " level='info' timestamp='round and round'" "\n" "event='debug logging enabled' logger='press.logging'" " level='debug' timestamp='round and round'" "\n" "event='info msg' logger='tests.unit.test_logging'" " level='info' timestamp='round and round'" "\n" "event='debug msg' logger='tests.unit.test_logging'" " level='debug' timestamp='round and round'" "\n" "event='error msg' logger='tests.unit.test_logging'" " level='error' timestamp='round and round'" "\n" ) assert captured.out == expected assert captured.err == ''
def test_route_with_keywords(self): from c2cgeoportal_geoportal.views.dynamic import DynamicView with testConfig(settings=self._get_settings({ "test": { "routes": { "XTest": { "name": "route_with_keywords", "kw": { "key1": "v1", "key2": "v2" } } } } })) as config: config.add_static_view(name="static", path="/etc/geomapfish/static") config.add_route("test", "/test") config.add_route("route_with_keywords", "/test/{key1}/{key2}") request = DummyRequest({"interface": "test"}) dynamic = DynamicView(request).dynamic() assert "XTest" in dynamic["constants"], dynamic assert dynamic["constants"]["XTest"] == "http://example.com/test/v1/v2"
def test_policy_selected_event(self): from pyramid.testing import testConfig from pyramid_multiauth import MultiAuthPolicySelected policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] policy = MultiAuthenticationPolicy(policies) # Simulate loading from config: policies[0]._pyramid_multiauth_name = "name" with testConfig() as config: request = DummyRequest() selected_policy = [] def track_policy(event): selected_policy.append(event) config.add_subscriber(track_policy, MultiAuthPolicySelected) self.assertEquals(policy.authenticated_userid(request), "test2") self.assertEquals(selected_policy[0].policy, policies[0]) self.assertEquals(selected_policy[0].policy_name, "name") self.assertEquals(selected_policy[0].userid, "test2") self.assertEquals(selected_policy[0].request, request) self.assertEquals(len(selected_policy), 1) # Effective principals also triggers an event when groupfinder # is provided. policy_with_group = MultiAuthenticationPolicy( policies, lambda u, r: ['foo']) policy_with_group.effective_principals(request) self.assertEquals(len(selected_policy), 2)
def test_main_template(self): self.config.testing_securitypolicy(permissive=False) request = testing.DummyRequest() inst = self._makeOne(request) with testing.testConfig() as config: config.include('pyramid_chameleon') self.assertTrue(inst.main_template)
def test_url_segment_not_match(self): with testing.testConfig() as config: self._config(config, 'app', url_segment='some_segment_url') pred = ApplicationRoutePredicate(config, 'anything') context = {'match': {'application': 'app'}} request = testing.DummyRequest() self.assertFalse(pred(context, request))
def test_policy_selected_event(self): from pyramid.testing import testConfig from pyramid_multiauth import MultiAuthPolicySelected policies = [TestAuthnPolicy2(), TestAuthnPolicy3()] policy = MultiAuthenticationPolicy(policies) # Simulate loading from config: policies[0]._pyramid_multiauth_name = "name" with testConfig() as config: request = DummyRequest() selected_policy = [] def track_policy(event): selected_policy.append(event) config.add_subscriber(track_policy, MultiAuthPolicySelected) self.assertEquals(policy.authenticated_userid(request), "test2") self.assertEquals(selected_policy[0].policy, policies[0]) self.assertEquals(selected_policy[0].policy_name, "name") self.assertEquals(selected_policy[0].userid, "test2") self.assertEquals(selected_policy[0].request, request) self.assertEquals(len(selected_policy), 1) # Effective principals also triggers an event when groupfinder # is provided. policy_with_group = MultiAuthenticationPolicy(policies, lambda u, r: ['foo']) policy_with_group.effective_principals(request) self.assertEquals(len(selected_policy), 2)
def test_includeme_with_usage(db_settings, db_wipe): # Initialize a table to ensure table reflection is working. conn_str = db_settings['db.common.url'] with psycopg2.connect(conn_str) as conn: with conn.cursor() as cur: cur.execute("CREATE TABLE smurfs (" " name TEXT PRIMARY KEY," " role TEXT," " tastiness INTEGER);") conn.commit() # Call the target function request = testing.DummyRequest() with testing.testConfig(request=request, settings=db_settings) as config: includeme(config) # The request doesn't yet have the added methods and I'm not sure # how to make the test request have those, so we'll call them # directly instead. We aren't testing the framework's # add_request_method anyhow. # Check the engines definitions # ... looking for the unnamed util lookup assert str(get_db_engine(request).url) == db_settings['db.common.url'] # ... looking for the named util lookup expected_url = db_settings['db.readonly.url'] assert str(get_db_engine(request, 'readonly').url) == expected_url with pytest.raises(ComponentLookupError): get_db_engine(request, 'foobar') # Check the tables definition assert hasattr(db_tables(request), 'smurfs')
def test_form_submitted_success_w_locator_adapter(self): from pyramid.testing import testConfig from zope.interface import Interface from ....interfaces import IUserLocator from ....testing import make_site request = testing.DummyRequest() request.params['form.submitted'] = True request.params['login'] = '******' request.params['password'] = '******' request.sdiapi = DummySDIAPI() request.params['csrf_token'] = request.session.get_csrf_token() context = make_site() user = DummyUser(1) user.__oid__ = 2 locator = DummyLocator(user) def _locator(context, request): return locator with testConfig() as config: config.testing_add_renderer( 'substanced.sdi.views:templates/login.pt') config.registry.registerAdapter(_locator, (Interface, Interface), IUserLocator) result = self._callFUT(context, request) self.assertEqual(result.location, 'http://example.com') self.assertTrue(result.headers) self.assertTrue('sdi.came_from' not in request.session)
def test_it(): from pyramid.testing import testConfig with testConfig() as config: config.include("stringexchange") config.add_route("hello", "/") def hello_view(context, request): from pyramid.response import Response js = request.string_exchange.publisher("js") response = Response(""" <html><head>{}</head><body></body></html> """.format(request.string_exchange.subscribe("js"))) js.publish('<script src="my.js></script>"') assert "my.js" not in response.text return response config.add_view(hello_view, route_name="hello") # request time router = _makeRouter(config) request = _makeRequest(config, path="/") response = router.handle_request(request) assert "my.js" in response.text
def test_it(self): from pyramid.testing import testConfig from mokehehe.viewobject import Mapper, parse_get, viewobject_method def todict(v): return {"value": v} with testConfig() as config: class Ob(object): def __call__(self, message): return message * 2 @viewobject_method def nihongo(self): return "hai" config.include("mokehehe.viewobject") config.add_route("hello", "/") MOb = config.add_mapped_viewobject(Mapper(parse_get, todict), Ob) self.assertIsNotNone(MOb) config.add_view(MOb, route_name="hello", renderer="json") config.add_view(MOb, route_name="hello", request_type=INihongoRequest, attr="nihongo", renderer="json") config.commit() result = self.callView(config, "/hello", GET={"message": "hello"}) self.assertEqual(result.body.decode("utf-8"), u'{"value": "hellohello"}') result = self.callView(config, "/hello", iface=INihongoRequest, GET={}) self.assertEqual(result.body.decode("utf-8"), u'{"value": "hai"}')
def test_logging(self): """Test that the includeme function loads the logging config.""" from .main import includeme with testing.testConfig(settings=self.settings) as config: includeme(config) # Set up the loggers root = logging.getLogger() local = logging.getLogger('pyramid_sawing.tests') # Try logging... root_log_msg = 'O⋮o' root.error(root_log_msg) local_log_msg = '>,<' local.info(local_log_msg) global logio logio.seek(self.logio_position) log_lines = logio.readlines() self.assertEqual(len(log_lines), 2) log_lines = [l.rstrip('\n') for l in log_lines] # Check the root message... parsed_root_msg = log_lines[0].split(';.;') self.assertEqual(parsed_root_msg, ['ERROR', root_log_msg]) parsed_local_msg = log_lines[1].split(';.;') self.assertEqual(parsed_local_msg, ['INFO ', socket.gethostname(), local_log_msg])
def test_main_template(self): self.config.testing_securitypolicy(permissive=False) request = testing.DummyRequest() inst = self._makeOne(request) with testing.testConfig() as config: config.include("pyramid_chameleon") self.assertTrue(inst.main_template)
def test_get_macro_with_name(self): request = testing.DummyRequest() inst = self._makeOne(request) with testing.testConfig() as config: config.include("pyramid_chameleon") macro = inst.get_macro("substanced.sdi.views:templates/master.pt", "main") self.assertTrue(macro.include)
def test_add_spec_view_directory_already_defined() -> None: """Test that creating a spec more than once raises an Exception.""" with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as document: document.write(MINIMAL_DOCUMENT) document.seek(0) config.pyramid_openapi3_spec(document.name, route="/foo", route_name="foo_api_spec") with tempfile.TemporaryDirectory() as directory: spec_name = os.path.join(directory, "openapi.yaml") spec_paths_name = os.path.join(directory, "paths.yaml") with open(spec_name, "wb") as f: f.write(SPLIT_DOCUMENT) with open(spec_paths_name, "wb") as f: f.write(SPLIT_DOCUMENT_PATHS) with pytest.raises( ConfigurationError, match= ("Spec has already been configured. You may only call " "pyramid_openapi3_spec or pyramid_openapi3_spec_directory once" ), ): config.pyramid_openapi3_spec_directory( spec_name, route="/foo.yaml", route_name="foo_api_spec")
def test_multiple(self): from pyramid.testing import testConfig class model: name = "model" class model2: name = "model2" def resource_factory(target): return target def create_route_name(target, fullname): return "{}.{}".format(fullname, target.name) def create_path(target, fullname): return "/{}/{}".format(fullname.replace(".", "/"), target.name) def myview(context, request): return "ok" with testConfig() as config: config.include("mokehehe.registering") builder = config.registering_builder("foo", resource_factory=resource_factory) with builder.sub("bar", route_name_craete=create_route_name, path_create=create_path) as view_builder: view_builder.build(view=myview).update(renderer="json") ## call builder(model) builder(model2) self.assertEqual(len(config.get_routes_mapper().get_routes()), 2)
def test_route_with_all(self): from c2cgeoportal_geoportal.views.dynamic import DynamicView with testConfig(settings=self._get_settings({ 'test': { 'routes': { 'XTest': { 'name': 'route_with_all', 'kw': { 'key1': 'v1', 'key2': 'v2', }, 'elements': ['s1', 's2'], 'params': { 'test': 'value' } } } } })) as config: config.add_static_view(name='static', path='/etc/geomapfish/static') config.add_route('test', '/test') config.add_route('route_with_all', '/test/{key1}/{key2}') request = DummyRequest({'interface': 'test'}) dynamic = DynamicView(request).dynamic() assert 'XTest' in dynamic['constants'], dynamic assert dynamic['constants'][ 'XTest'] == 'http://example.com/test/v1/v2/s1/s2?test=value'
def test_openapi_view_validate_HTTPExceptions(): """Test that raised HTTPExceptions are validated against the spec. I.e. create a dummy view that raises 403 Forbidden. The openapi integration should re-raise it as InvalidResponse because 403 is not on the list of responses in MINIMAL_DOCUMENT. """ with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as document: document.write(MINIMAL_DOCUMENT) document.seek(0) config.pyramid_openapi3_spec( document.name, route="/foo.yaml", route_name="foo_api_spec" ) config.add_route("foo", "/foo") view = lambda *arg: (_ for _ in ()).throw( # noqa: E731 exception_response(403, json_body="Forbidden") ) config.add_view(openapi=True, renderer="json", view=view, route_name="foo") request_interface = config.registry.queryUtility(IRouteRequest, name="foo") view = config.registry.adapters.registered( (IViewClassifier, request_interface, Interface), IView, name="" ) request = DummyRequest(config=config) request.matched_route = DummyRoute(name="foo", pattern="/foo") with pytest.raises(InvalidResponse) as exc: view(request=request, context=None) assert str(exc.value) == "Unknown response http status: 403"
def test_stop_run(self): with testing.testConfig() as config: config.add_route('api_stop_run', '/api/stop_run') self.assertEqual(stop_run(self.request), '{}') self.assertEqual( self.request.rundb.get_run( self.request.json_body['run_id'])['stop_reason'], 'travis')
def test_logging_a_request(self): request = Request.blank('/foo') request.environ.update({ 'HTTP_VERSION': '1.1', 'REMOTE_ADDR': '127.0.0.1', }) response = mock.Mock() response.status = '404 Not Found' response.headers = {'content-length': 0} handler = mock.Mock(return_value=response) config_kwargs = {'request': request, 'settings': self.settings} with testing.testConfig(**config_kwargs) as config: request.registry = config.registry tween = self.make_one(handler=handler, registry=config.registry) tween(request) global logio logio.seek(self.logio_position) log_lines = logio.readlines() self.assertEqual(len(log_lines), 1) log_lines = [l.rstrip('\n') for l in log_lines] log_line = log_lines[0] self.assertEqual( log_line, '127.0.0.1 - - [asctime] "GET http://localhost:80/foo 1.1" 404 Not Found 0 "-" "-"')
def test_reply_notification_content(): """ The reply notification should have a subject, and both plain and html bodies. """ with testConfig() as config: config.include('pyramid_chameleon') annotation = create_annotation() request = DummyRequest() with patch('h.auth.local.models.User') as mock_user: user = Mock(email='acct:parent@testdomain') mock_user.get_by_username.return_value = user notification = notifier.ReplyTemplate.generate_notification( request, annotation, {}) assert notification['status'] assert notification['recipients'] == ['acct:parent@testdomain'] assert 'testuser has just left a reply to your annotation on' in \ notification['text'] assert '<a href="http://example.com/u/testuser">testuser</a> '\ 'has just left a reply to your annotation on' \ in notification['html'] assert notification['subject'] == \ 'testuser has replied to your annotation\n'
def test_csa_founder_signup(customer_mock, charge_mock, post): with testing.testConfig() as config: config.add_route('signup_success', '/success') request = testing.DummyRequest(post=post) request.registry.settings['stripe.api_key'] = 'api_key' with pytest.raises(HTTPFound): csa_founder_signup(request)
def test_integer_user_id(self): # userids can apparently be integers as well from pyramid.request import Request with testing.testConfig() as config: config.testing_securitypolicy(userid=42) request = Request.blank('/') msg = self._callFUT(request) self.assertTrue('42' in msg)
def test_non_ascii_bytes_in_userid(self): from pyramid.request import Request byte_str = b'\xe6\xbc\xa2' with testing.testConfig() as config: config.testing_securitypolicy(userid=byte_str) request = Request.blank('/') msg = self._callFUT(request) self.assertTrue(repr(byte_str) in msg, msg)
def pyramid_config(db_settings): """Preset the discoverable settings, where the pyramid application may want to define these itself, rather than have cnx-db discover them. """ with testing.testConfig(settings=db_settings) as config: yield config
def test_get_client_not_ok(): mock_factory = MagicMock() mock_factory.return_value = None settings = {'h.client_id': '1234'} with testing.testConfig(settings=settings) as config: registry = config.registry registry.registerUtility(mock_factory, interfaces.IClientFactory) request = testing.DummyRequest(registry=config.registry) assert lib.get_client(request, '9876') is None
def pyramid_config(pyramid_settings, pyramid_request): """Pyramid configurator object.""" with testing.testConfig(request=pyramid_request, settings=pyramid_settings) as config: # Include pyramid_services so it's easy to set up fake services in tests config.include('pyramid_services') apply_request_extensions(pyramid_request) yield config
def test_get_client_ok(): mock_factory = MagicMock() settings = {'h.client_id': '1234'} with testing.testConfig(settings=settings) as config: registry = config.registry registry.registerUtility(mock_factory, interfaces.IClientFactory) request = testing.DummyRequest(registry=config.registry) lib.get_client(request, '4321') mock_factory.assert_called_with('4321')
def test_create_users(self): with testing.testConfig() as config: config.add_route('login', '/login') config.add_route('signup', '/signup') print(signup(self.request)) userc= {} userc['cpu_hours'] = 12345 userc['username'] = '******' self.request.userdb.user_cache.insert(userc)
def test_async_traversed_length(self): with testing.testConfig() as config: config.add_traverser(AsyncioTraverser) resource = DummyResource('root', None) resource.add_child('cat', DummyResource) out = self.loop.run_until_complete( spawn_greenlet(traverse, resource, ['cat']), ) self.assertEqual(len(out['traversed']), 1)
def test_async_root(self): with testing.testConfig() as config: config.add_traverser(AsyncioTraverser) resource = DummyResource('root', None) resource.add_child('cat', DummyResource) out = self.loop.run_until_complete( spawn_greenlet(traverse, resource, ['']), ) self.assertTrue(out.get('root') == out.get('context'))
def test_call_directive_manytimes(self): from pyramid.testing import testConfig with testConfig() as config: config.include("mokehehe.registering") builder = config.registering_builder("foo", resource_factory=object()) builder2 = config.registering_builder("foo", resource_factory=object()) self.assertEqual(builder2, builder)
def test_missing_both__exception(self): from pyramid.testing import testConfig from pyramid.exceptions import ConfigurationError with testConfig(autocommit=False) as config: config.include("mokehehe.workflow") config.get_workflow().register(IAfterModelCreate, "foo.create", "foo.list") with self.assertRaisesRegex(ConfigurationError, "route name"): config.commit()
def test_reify_it(): from pyramid.testing import testConfig with testConfig() as config: config.include("stringexchange") # request time request = _makeRequest(config, path="/") assert request.string_exchange == request.string_exchange