Exemple #1
0
    def test_cors_supported_methods(self):
        foo = Service(name='foo', path='/foo', cors_enabled=True)
        foo.add_view('GET', _stub)
        self.assertIn('GET', foo.cors_supported_methods)

        foo.add_view('POST', _stub)
        self.assertIn('POST', foo.cors_supported_methods)
    def test_cors_supported_methods(self):
        foo = Service(name="foo", path="/foo", cors_enabled=True)
        foo.add_view("GET", _stub)
        self.assertIn("GET", foo.cors_supported_methods)

        foo.add_view("POST", _stub)
        self.assertIn("POST", foo.cors_supported_methods)
    def test_disabling_cors_for_one_method(self):
        foo = Service(name="foo", path="/foo", cors_enabled=True)
        foo.add_view("GET", _stub)
        self.assertIn("GET", foo.cors_supported_methods)

        foo.add_view("POST", _stub, cors_enabled=False)
        self.assertIn("GET", foo.cors_supported_methods)
        self.assertFalse("POST" in foo.cors_supported_methods)
Exemple #4
0
    def test_disabling_cors_for_one_method(self):
        foo = Service(name='foo', path='/foo', cors_enabled=True)
        foo.add_view('GET', _stub)
        self.assertIn('GET', foo.cors_supported_methods)

        foo.add_view('POST', _stub, cors_enabled=False)
        self.assertIn('GET', foo.cors_supported_methods)
        self.assertFalse('POST' in foo.cors_supported_methods)
    def test_cors_supported_origins(self):
        foo = Service(name="foo", path="/foo", cors_origins=("mozilla.org",))

        foo.add_view("GET", _stub, cors_origins=("notmyidea.org", "lolnet.org"))

        self.assertIn("mozilla.org", foo.cors_supported_origins)
        self.assertIn("notmyidea.org", foo.cors_supported_origins)
        self.assertIn("lolnet.org", foo.cors_supported_origins)
 def test_cors_headers_for_method_are_deduplicated(self):
     # defining headers in the view should work.
     service = Service("coconuts", "/migrate")
     service.cors_headers = ("X-Header-Foobar",)
     service.add_view("GET", _stub, cors_headers=("X-Header-Foobar", "X-Header-Barbaz"))
     get_headers = service.cors_supported_headers_for(method="GET")
     expected = set(["X-Header-Foobar", "X-Header-Barbaz"])
     self.assertEqual(expected, get_headers)
    def test_cors_headers_for_service_instanciation(self):
        # When definining services, it's possible to add headers. This tests
        # it is possible to list all the headers supported by a service.
        service = Service("coconuts", "/migrate", cors_headers=("X-Header-Coconut"))
        self.assertNotIn("X-Header-Coconut", service.cors_supported_headers_for())

        service.add_view("POST", _stub)
        self.assertIn("X-Header-Coconut", service.cors_supported_headers_for())
Exemple #8
0
    def test_cors_headers_for_service_instanciation(self):
        # When definining services, it's possible to add headers. This tests
        # it is possible to list all the headers supported by a service.
        service = Service('coconuts', '/migrate',
                          cors_headers=('X-Header-Coconut'))
        self.assertNotIn('X-Header-Coconut', service.cors_supported_headers)

        service.add_view('POST', _stub)
        self.assertIn('X-Header-Coconut', service.cors_supported_headers)
    def test_max_age_can_be_different_dependeing_methods(self):
        foo = Service(name="foo", path="/foo", cors_max_age=42)
        foo.add_view("GET", _stub)
        foo.add_view("POST", _stub, cors_max_age=32)
        foo.add_view("PUT", _stub, cors_max_age=7)

        self.assertEqual(foo.cors_max_age_for("GET"), 42)
        self.assertEqual(foo.cors_max_age_for("POST"), 32)
        self.assertEqual(foo.cors_max_age_for("PUT"), 7)
Exemple #10
0
 def test_cors_headers_for_method_are_deduplicated(self):
     # defining headers in the view should work.
     service = Service('coconuts', '/migrate')
     service.cors_headers = ('X-Header-Foobar',)
     service.add_view('GET', _stub,
                      cors_headers=('X-Header-Foobar', 'X-Header-Barbaz'))
     get_headers = service.cors_supported_headers_for(method='GET')
     expected = set(['X-Header-Foobar', 'X-Header-Barbaz'])
     self.assertEqual(expected, get_headers)
Exemple #11
0
    def test_max_age_can_be_different_dependeing_methods(self):
        foo = Service(name='foo', path='/foo', cors_max_age=42)
        foo.add_view('GET', _stub)
        foo.add_view('POST', _stub, cors_max_age=32)
        foo.add_view('PUT', _stub, cors_max_age=7)

        self.assertEqual(foo.cors_max_age_for('GET'), 42)
        self.assertEqual(foo.cors_max_age_for('POST'), 32)
        self.assertEqual(foo.cors_max_age_for('PUT'), 7)
Exemple #12
0
    def test_cors_supported_origins(self):
        foo = Service(
            name='foo', path='/foo', cors_origins=('mozilla.org',))

        foo.add_view('GET', _stub,
                     cors_origins=('notmyidea.org', 'lolnet.org'))

        self.assertIn('mozilla.org', foo.cors_supported_origins)
        self.assertIn('notmyidea.org', foo.cors_supported_origins)
        self.assertIn('lolnet.org', foo.cors_supported_origins)
Exemple #13
0
    def test_can_specify_a_view_decorator(self):
        def dummy_decorator(view):
            return view
        service = Service("coconuts", "/migrate", decorator=dummy_decorator)
        args = service.get_arguments({})
        self.assertEqual(args['decorator'], dummy_decorator)

        # make sure Service.decorator() still works
        @service.decorator('put')
        def dummy_view(request):
            return "data"
        self.assertTrue(any(view is dummy_view
                            for method, view, args in service.definitions))
Exemple #14
0
    def test_view_registration(self):
        # registering a new view should make it available in the list.
        # The methods list is populated
        service = Service("color", "/favorite-color")

        def view(request):
            pass
        service.add_view("post", view, validators=(_validator,))
        self.assertEquals(len(service.definitions), 1)
        method, _view, _ = service.definitions[0]

        # the view had been registered. we also test here that the method had
        # been inserted capitalized (POST instead of post)
        self.assertEquals(("POST", view), (method, _view))
Exemple #15
0
    def test_service_instanciation(self):
        service = Service("coconuts", "/migrate")
        self.assertEqual(service.name, "coconuts")
        self.assertEqual(service.path, "/migrate")
        self.assertEqual(service.renderer, Service.renderer)

        service = Service("coconuts", "/migrate", renderer="html")
        self.assertEqual(service.renderer, "html")

        # test that lists are also set
        validators = [
            lambda x: True,
        ]
        service = Service("coconuts", "/migrate", validators=validators)
        self.assertEqual(service.validators, validators)
    def test_class_parameters(self):
        # when passing a "klass" argument, it gets registered. It also tests
        # that the view argument can be a string and not a callable.
        class TemperatureCooler(object):
            def get_fresh_air(self):
                pass

        service = Service("TemperatureCooler", "/freshair", klass=TemperatureCooler)
        service.add_view("get", "get_fresh_air")

        self.assertEqual(len(service.definitions), 2)

        method, view, args = service.definitions[0]
        self.assertEqual(view, "get_fresh_air")
        self.assertEqual(args["klass"], TemperatureCooler)
Exemple #17
0
    def test_view_registration(self):
        # registering a new view should make it available in the list.
        # The methods list is populated
        service = Service("color", "/favorite-color")

        def view(request):
            pass

        service.add_view("post", view, validators=(_validator, ))
        self.assertEqual(len(service.definitions), 1)
        method, _view, _ = service.definitions[0]

        # the view had been registered. we also test here that the method had
        # been inserted capitalized (POST instead of post)
        self.assertEqual(("POST", view), (method, _view))
Exemple #18
0
    def test_imperative(self):
        service = Service("TemperatureCooler", "/freshair")

        class TemperatureCooler(object):
            """Temp class docstring"""

            def view_get(self, request):
                """Temp view docstring"""
                return "red"

        service.add_view(
            "get",
            TemperatureCooler.view_get,
            validators=(colander_validator, ),
            schema=RequestSchema())
        ret = _generate_swagger([service])
        if PY3:
            self.assertEqual(ret["tags"], [{
                'name': 'freshair',
                'description': ''
            }])
        else:
            self.assertEqual(ret["tags"], [{
                'name': 'freshair',
                'description': 'Temp class docstring'
            }])
        self.assertEqual(ret["paths"]["/freshair"]["get"]["summary"],
                         'Temp view docstring')
        params = ret["paths"]["/freshair"]["get"]['parameters']
        self.assertEqual(len(params), 3)
        self.assertEqual(
            sorted(x["in"] for x in params), ["body", "query", "query"])
        self.assertEqual(
            sorted(x["name"] for x in params), ["body", "mau", "yeah"])
        self.assertEqual([x.get("required") for x in params],
                         [True, True, None])
        self.assertEqual([x.get("type") for x in params],
                         ["string", "string", None])
        self.assertEqual([x.get("schema") for x in params],
                         [None, None, {
                             '$ref': '#/definitions/Body'
                         }])
        self.assertListEqual(
         sorted([x.get("description") for x in params], key=lambda x: x or ""),
         [None, "Defines a cornice body schema", "Defines querystring yeah"]
        )
        self.assertEqual(
            sorted(ret["definitions"]['Body']["required"]), ['bar', 'foo'])
Exemple #19
0
    def test_default_error_handler_calls_default_renderer(self):
        # Default error handler should call `render_errors` on the
        # registered renderer.
        service = Service("error service", "/error_service")

        renderer = mock.MagicMock()
        renderer.render_errors.return_value = "rendered_errors"

        request = mock.MagicMock()
        request.registry.queryUtility.return_value = renderer

        self.assertEqual(service.default_error_handler(request),
                         "rendered_errors")
        request.registry.queryUtility.assert_called_with(IRendererFactory,
                                                         name=service.renderer)
        renderer.render_errors.assert_called_with(request)
Exemple #20
0
    def test_can_specify_a_view_decorator(self):
        def dummy_decorator(view):
            return view

        service = Service("coconuts", "/migrate", decorator=dummy_decorator)
        args = service.get_arguments({})
        self.assertEqual(args['decorator'], dummy_decorator)

        # make sure Service.decorator() still works
        @service.decorator('put')
        def dummy_view(request):
            return "data"

        self.assertTrue(
            any(view is dummy_view
                for method, view, args in service.definitions))
Exemple #21
0
 def test_cors_policy_can_be_overwritten(self):
     policy = {'origins': ('foo', 'bar', 'baz')}
     foo = Service(name='foo',
                   path='/foo',
                   cors_origins=(),
                   cors_policy=policy)
     self.assertEqual(len(foo.cors_supported_origins), 0)
Exemple #22
0
    def test_decorators(self):
        service = Service("color", "/favorite-color")

        @service.get()
        def get_favorite_color(request):
            return "blue, hmm, red, hmm, aaaaaaaah"

        self.assertEquals(2, len(service.definitions))
        method, view, _ = service.definitions[0]
        self.assertEquals(("GET", get_favorite_color), (method, view))
        method, view, _ = service.definitions[1]
        self.assertEquals(("HEAD", get_favorite_color), (method, view))

        @service.post(accept='text/plain', renderer='plain')
        @service.post(accept='application/json')
        def post_favorite_color(request):
            pass

        # using multiple decorators on a resource should register them all in
        # as many different definitions in the service
        self.assertEquals(4, len(service.definitions))

        @service.patch()
        def patch_favorite_color(request):
            return ""

        method, view, _ = service.definitions[4]
        self.assertEquals("PATCH", method)
Exemple #23
0
    def test_not_instantiated(self):
        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            """
            Ice cream service
            """

            # Use GetRequestSchema and ResponseSchemas classes instead of objects
            @service.get(validators=(colander_validator, ),
                         schema=GetRequestSchema)
            def view_get(self, request):
                """Serve icecream"""
                return self.request.validated

            @service.put(validators=(colander_validator, ),
                         schema=PutRequestSchema())
            def view_put(self, request):
                """Add flavour"""
                return self.request.validated

        self.service = service
        self.swagger = CorniceSwagger([self.service])
        self.spec = self.swagger.generate()
        validate(self.spec)
Exemple #24
0
    def test_generate_spore_description(self):

        coffees = Service(name='Coffees', path='/coffee')
        coffee = Service(name='coffee', path='/coffee/{bar}/{id}')

        @coffees.post()
        def post_coffees(request):
            """Post information about the coffee"""
            return "ok"

        self._define_coffee_methods(coffee)
        self._define_coffee_methods(coffees)

        services = get_services(names=('coffee', 'Coffees'))
        spore = generate_spore_description(
                services, name="oh yeah",
                base_url="http://localhost/", version="1.0")

        # basic fields
        self.assertEqual(spore['name'], "oh yeah")
        self.assertEqual(spore['base_url'], "http://localhost/")
        self.assertEqual(spore['version'], "1.0")

        # methods
        methods = spore['methods']
        self.assertIn('get_coffees', methods)
        self.assertDictEqual(methods['get_coffees'], {
            'path': '/coffee',
            'method': 'GET',
            'formats': ['json'],
            })

        self.assertIn('post_coffees', methods)
        self.assertDictEqual(methods['post_coffees'], {
            'path': '/coffee',
            'method': 'POST',
            'formats': ['json'],
            'description': post_coffees.__doc__
            })

        self.assertIn('get_coffee', methods)
        self.assertDictEqual(methods['get_coffee'], {
            'path': '/coffee/:bar/:id',
            'method': 'GET',
            'formats': ['json'],
            'required_params': ['bar', 'id']
            })
    def test_per_method_supported_origins(self):
        foo = Service(name="foo", path="/foo", cors_origins=("mozilla.org",))
        foo.add_view("GET", _stub, cors_origins=("lolnet.org",))

        self.assertTrue("mozilla.org" in foo.cors_origins_for("GET"))
        self.assertTrue("lolnet.org" in foo.cors_origins_for("GET"))

        foo.add_view("POST", _stub)
        self.assertFalse("lolnet.org" in foo.cors_origins_for("POST"))
    def test_cors_headers_extension(self):
        # definining headers in the service and in the view
        service = Service("coconuts", "/migrate", cors_headers=("X-Header-Foobar"))
        service.add_view("POST", _stub, cors_headers=("X-Header-Barbaz"))
        self.assertIn("X-Header-Foobar", service.cors_supported_headers_for())
        self.assertIn("X-Header-Barbaz", service.cors_supported_headers_for())

        # check that adding the same header twice doesn't make bad things
        # happen
        service.add_view("POST", _stub, cors_headers=("X-Header-Foobar"))
        self.assertEqual(len(service.cors_supported_headers_for()), 2)

        # check that adding a header on a cors disabled method doesn't
        # change anything
        service.add_view("put", _stub, cors_headers=("X-Another-Header",), cors_enabled=False)

        self.assertNotIn("X-Another-Header", service.cors_supported_headers_for())
Exemple #27
0
    def test_class_parameters(self):
        # when passing a "klass" argument, it gets registered. It also tests
        # that the view argument can be a string and not a callable.
        class TemperatureCooler(object):
            def get_fresh_air(self):
                pass

        service = Service("TemperatureCooler",
                          "/freshair",
                          klass=TemperatureCooler)
        service.add_view("get", "get_fresh_air")

        self.assertEquals(len(service.definitions), 2)

        method, view, args = service.definitions[0]
        self.assertEquals(view, "get_fresh_air")
        self.assertEquals(args["klass"], TemperatureCooler)
Exemple #28
0
 def test_schemas_for(self):
     schema = validationapp.FooBarSchema
     service = Service("color", "/favorite-color")
     service.add_view("GET", lambda x: "red", schema=schema)
     self.assertEquals(len(service.schemas_for("GET")), 1)
     service.add_view("GET",
                      lambda x: "red",
                      validators=_validator,
                      schema=schema)
     self.assertEquals(len(service.schemas_for("GET")), 2)
Exemple #29
0
    def test_per_method_supported_origins(self):
        foo = Service(
            name='foo', path='/foo', cors_origins=('mozilla.org',))
        foo.add_view('GET', _stub, cors_origins=('lolnet.org',))

        self.assertTrue('mozilla.org' in foo.cors_origins_for('GET'))
        self.assertTrue('lolnet.org' in foo.cors_origins_for('GET'))

        foo.add_view('POST', _stub)
        self.assertFalse('lolnet.org' in foo.cors_origins_for('POST'))
Exemple #30
0
 def test_cors_headers_for_method(self):
     # defining headers in the view should work.
     service = Service('coconuts', '/migrate')
     service.add_view('GET', _stub, cors_headers=('X-Header-Foobar'))
     service.add_view('POST', _stub, cors_headers=('X-Header-Barbaz'))
     get_headers = service.cors_supported_headers_for(method='GET')
     self.assertNotIn('X-Header-Barbaz', get_headers)
Exemple #31
0
 def test_schemas_for(self):
     schema = validationapp.FooBarSchema
     service = Service("color", "/favorite-color")
     service.add_view("GET", lambda x: "red", schema=schema)
     self.assertEquals(len(service.schemas_for("GET")), 1)
     service.add_view("GET", lambda x: "red", validators=_validator, schema=schema)
     self.assertEquals(len(service.schemas_for("GET")), 2)
Exemple #32
0
    def test_default_validators(self):

        old_validators = Service.default_validators
        old_filters = Service.default_filters
        try:

            def custom_validator(request):
                pass

            def custom_filter(request):
                pass

            def freshair(request):
                pass

            # the default validators should be used when registering a service
            Service.default_validators = [
                custom_validator,
            ]
            Service.default_filters = [
                custom_filter,
            ]
            service = Service("TemperatureCooler", "/freshair")
            service.add_view("get", freshair)
            method, view, args = service.definitions[0]

            self.assertIn(custom_validator, args['validators'])
            self.assertIn(custom_filter, args['filters'])

            # defining a service with additional filters / validators should
            # work as well
            def another_validator(request):
                pass

            def another_filter(request):
                pass

            def groove_em_all(request):
                pass

            service2 = Service('FunkyGroovy',
                               '/funky-groovy',
                               validators=[another_validator],
                               filters=[another_filter])

            service2.add_view("get", groove_em_all)
            method, view, args = service2.definitions[0]

            self.assertIn(custom_validator, args['validators'])
            self.assertIn(another_validator, args['validators'])
            self.assertIn(custom_filter, args['filters'])
            self.assertIn(another_filter, args['filters'])
        finally:
            Service.default_validators = old_validators
            Service.default_filters = old_filters
Exemple #33
0
    def test_cors_support(self):
        self.assertFalse(Service(name='foo', path='/foo').cors_enabled)

        self.assertTrue(
            Service(name='foo', path='/foo', cors_enabled=True).cors_enabled)

        self.assertFalse(
            Service(name='foo', path='/foo', cors_enabled=False).cors_enabled)

        self.assertTrue(
            Service(name='foo', path='/foo',
                    cors_origins=('*', )).cors_enabled)

        self.assertFalse(
            Service(name='foo',
                    path='/foo',
                    cors_origins=('*'),
                    cors_enabled=False).cors_enabled)
Exemple #34
0
    def test_rxjson_spore(self):
        rx = Rx.Factory({'register_core_types': True})

        coffees = Service(name='Coffees', path='/coffee')
        coffee = Service(name='coffee', path='/coffee/{bar}/{id}')

        self._define_coffee_methods(coffee)
        self._define_coffee_methods(coffees)

        services = get_services(names=('coffee', 'Coffees'))
        spore = generate_spore_description(
                services, name="oh yeah",
                base_url="http://localhost/", version="1.0")

        with open(os.path.join(HERE, 'spore_validation.rx')) as f:
            spore_json_schema = json.loads(f.read())
            spore_schema = rx.make_schema(spore_json_schema)
            self.assertTrue(spore_schema.check(spore))
Exemple #35
0
    def test_get_services(self):
        self.assertEquals([], get_services())
        foobar = Service("Foobar", "/foobar")
        self.assertIn(foobar, get_services())

        barbaz = Service("Barbaz", "/barbaz")
        self.assertIn(barbaz, get_services())

        self.assertEquals([
            barbaz,
        ], get_services(exclude=[
            'Foobar',
        ]))
        self.assertEquals([
            foobar,
        ], get_services(names=[
            'Foobar',
        ]))
        self.assertEquals([foobar, barbaz],
                          get_services(names=['Foobar', 'Barbaz']))
Exemple #36
0
    def test_invalid_security_raises_exception(self):

        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            @service.get(api_security='basicAuth')
            def view_get(self, request):
                return service

        swagger = CorniceSwagger([service])
        self.assertRaises(CorniceSwaggerException, swagger.generate)
Exemple #37
0
    def test_default_error_handler(self):
        # If not configured otherwise, Service.default_error_handler should
        # be used to handle and render errors.
        service = Service("error service", "/error_service")

        @service.get()
        def get_error(request):
            return "error"

        method, view, args = service.definitions[0]
        self.assertEqual(args['error_handler'], service.default_error_handler)
Exemple #38
0
    def test_error_handler(self):
        error_handler = object()
        service = Service("color", "/favorite-color",
                          error_handler=error_handler)

        @service.get()
        def get_favorite_color(request):
            return "blue, hmm, red, hmm, aaaaaaaah"

        method, view, args = service.definitions[0]
        self.assertIs(args['error_handler'], error_handler)
Exemple #39
0
    def test_invalid_service_tag_raises_exception(self):

        service = Service("IceCream", "/icecream/{flavour}", tags='cold')

        class IceCream(object):
            @service.get()
            def view_get(self, request):
                return service

        swagger = CorniceSwagger([service])
        self.assertRaises(CorniceSwaggerException, swagger.generate)
Exemple #40
0
    def test_invalid_default_opid_raises_exception(self):

        service = Service("IceCream", "/icecream/{flavour}")

        @service.get()
        def view_get(self, request):
            return service

        swagger = CorniceSwagger([service])
        swagger.default_op_ids = "foo"
        self.assertRaises(CorniceSwaggerException, swagger.generate)
Exemple #41
0
    def test_cors_headers_extension(self):
        # definining headers in the service and in the view
        service = Service('coconuts', '/migrate',
                          cors_headers=('X-Header-Foobar'))
        service.add_view('POST', _stub, cors_headers=('X-Header-Barbaz'))
        self.assertIn('X-Header-Foobar', service.cors_supported_headers_for())
        self.assertIn('X-Header-Barbaz', service.cors_supported_headers_for())

        # check that adding the same header twice doesn't make bad things
        # happen
        service.add_view('POST', _stub, cors_headers=('X-Header-Foobar'),)
        self.assertEqual(len(service.cors_supported_headers_for()), 2)

        # check that adding a header on a cors disabled method doesn't
        # change anything
        service.add_view('put', _stub,
                         cors_headers=('X-Another-Header',),
                         cors_enabled=False)

        self.assertNotIn('X-Another-Header',
                         service.cors_supported_headers_for())
Exemple #42
0
    def test_multiple_views_with_different_ctypes_raises_exception(self):

        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            def view_put(self, request):
                return "red"

        service.add_view(
            "put",
            IceCream.view_put,
            validators=(colander_validator, ),
            schema=PutRequestSchema(),
            content_type='application/json',
        )
        service.add_view(
            "put",
            IceCream.view_put,
            validators=(colander_validator, ),
            schema=PutRequestSchema(),
            content_type='text/xml',
        )

        swagger = CorniceSwagger([service])
        self.assertRaises(CorniceSwaggerException, swagger.generate)
 def test_cors_headers_for_method(self):
     # defining headers in the view should work.
     service = Service("coconuts", "/migrate")
     service.add_view("GET", _stub, cors_headers=("X-Header-Foobar"))
     service.add_view("POST", _stub, cors_headers=("X-Header-Barbaz"))
     get_headers = service.cors_supported_headers_for(method="GET")
     self.assertNotIn("X-Header-Barbaz", get_headers)
Exemple #44
0
 def test_cors_headers_for_method(self):
     # defining headers in the view should work.
     service = Service('coconuts', '/migrate')
     service.add_view('GET', _stub, cors_headers=('X-Header-Foobar'))
     service.add_view('POST', _stub, cors_headers=('X-Header-Barbaz'))
     get_headers = service.cors_supported_headers_for(method='GET')
     self.assertNotIn('X-Header-Barbaz', get_headers)
Exemple #45
0
    def test_ignore_multiple_views_by_ctype(self):

        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            def view_put(self, request):
                return "red"

        service.add_view(
            "put",
            IceCream.view_put,
            validators=(colander_validator, ),
            schema=PutRequestSchema(),
            content_type='application/json',
        )
        service.add_view(
            "put",
            IceCream.view_put,
            validators=(colander_validator, ),
            schema=PutRequestSchema(),
            content_type='text/xml',
        )

        swagger = CorniceSwagger([service])
        swagger.ignore_ctypes = ['text/xml']
        spec = swagger.generate()
        self.assertEquals(
            spec['paths']['/icecream/{flavour}']['put']['consumes'],
            ['application/json'])
Exemple #46
0
def includeme(config):
    from weaver.wps.app import pywps_view

    settings = get_settings(config)
    logger = logging.getLogger(__name__)
    if not asbool(settings.get("weaver.wps", True)):
        logger.debug(
            "Weaver WPS disable. WPS KVP/XML endpoint will not be available.")
    else:
        logger.debug("Weaver WPS enabled.")
        wps_path = get_wps_path(settings)
        wps_service = Service(name="wps", path=wps_path)
        logger.debug("Adding WPS KVP/XML schemas.")
        wps_tags = [
            sd.TAG_GETCAPABILITIES, sd.TAG_DESCRIBEPROCESS, sd.TAG_EXECUTE,
            sd.TAG_WPS
        ]
        wps_service.add_view("GET",
                             pywps_view,
                             tags=wps_tags,
                             renderer=OUTPUT_FORMAT_XML,
                             schema=sd.WPSEndpoint(),
                             response_schemas=sd.wps_responses)
        wps_service.add_view("POST",
                             pywps_view,
                             tags=wps_tags,
                             renderer=OUTPUT_FORMAT_XML,
                             schema=sd.WPSEndpoint(),
                             response_schemas=sd.wps_responses)
        logger.debug("Adding WPS KVP/XML view.")
        config.add_route(**sd.service_api_route_info(wps_service, settings))
        config.add_view(pywps_view, route_name=wps_service.name)
Exemple #47
0
    def test_cors_supported_methods(self):
        foo = Service(name='foo', path='/foo', cors_enabled=True)
        foo.add_view('GET', _stub)
        self.assertIn('GET', foo.cors_supported_methods)

        foo.add_view('POST', _stub)
        self.assertIn('POST', foo.cors_supported_methods)
Exemple #48
0
    def test_view_defined_operation_id(self):

        service = Service("IceCream", "/icecream/{flavour}")

        @service.get(operation_id='serve_icecream')
        def view_get(self, request):
            return service

        swagger = CorniceSwagger([service])
        spec = swagger.generate()
        validate(spec)
        op_id = spec['paths']['/icecream/{flavour}']['get']['operationId']
        self.assertEquals(op_id, 'serve_icecream')
    def test_default_renderer(self):
        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            @service.get()
            def view_get(self, request):
                return self.request.validated

        swagger = CorniceSwagger([service])
        spec = swagger.generate()
        self.assertEquals(
            spec['paths']['/icecream/{flavour}']['get']['produces'],
            ['application/json'])
Exemple #50
0
    def test_no_ctype_no_list_with_none(self):

        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            @service.put()
            def view_put(self, request):
                return self.request.validated

        swagger = CorniceSwagger([service])
        spec = swagger.generate()
        self.assertNotIn('consumes',
                         spec['paths']['/icecream/{flavour}']['put'])
Exemple #51
0
    def test_unkown_renderer(self):

        service = Service("IceCream", "/icecream/{flavour}")

        class IceCream(object):
            @service.get(renderer='')
            def view_get(self, request):
                return self.request.validated

        swagger = CorniceSwagger([service])
        spec = swagger.generate()
        self.assertNotIn('produces',
                         spec['paths']['/icecream/{flavour}']['get'])
Exemple #52
0
    def test_disabling_cors_for_one_method(self):
        foo = Service(name='foo', path='/foo', cors_enabled=True)
        foo.add_view('GET', _stub)
        self.assertIn('GET', foo.cors_supported_methods)

        foo.add_view('POST', _stub, cors_enabled=False)
        self.assertIn('GET', foo.cors_supported_methods)
        self.assertFalse('POST' in foo.cors_supported_methods)
Exemple #53
0
    def test_default_validators(self):

        old_validators = Service.default_validators
        old_filters = Service.default_filters
        try:
            def custom_validator(request):
                pass

            def custom_filter(request):
                pass

            def freshair(request):
                pass

            # the default validators should be used when registering a service
            Service.default_validators = [custom_validator, ]
            Service.default_filters = [custom_filter, ]
            service = Service("TemperatureCooler", "/freshair")
            service.add_view("get", freshair)
            method, view, args = service.definitions[0]

            self.assertIn(custom_validator, args['validators'])
            self.assertIn(custom_filter, args['filters'])

            # defining a service with additional filters / validators should
            # work as well
            def another_validator(request):
                pass

            def another_filter(request):
                pass

            def groove_em_all(request):
                pass

            service2 = Service('FunkyGroovy', '/funky-groovy',
                               validators=[another_validator],
                               filters=[another_filter])

            service2.add_view("get", groove_em_all)
            method, view, args = service2.definitions[0]

            self.assertIn(custom_validator, args['validators'])
            self.assertIn(another_validator, args['validators'])
            self.assertIn(custom_filter, args['filters'])
            self.assertIn(another_filter, args['filters'])
        finally:
            Service.default_validators = old_validators
            Service.default_filters = old_filters
    def test_get_validators(self):
        # defining different validators for the same services, even with
        # different calls to add_view should make them available in the
        # get_validators method

        def validator(request):
            """Super validator"""
            pass

        def validator2(request):
            pass

        service = Service("/color", "/favorite-color")
        service.add_view("GET", lambda x: "ok", validators=(validator, validator))
        service.add_view("GET", lambda x: "ok", validators=(validator2))
        self.assertEqual(service.get_validators("GET"), [validator, validator2])
    def test_get_arguments(self):
        service = Service("coconuts", "/migrate")
        # not specifying anything, we should get the default values
        args = service.get_arguments({})
        for arg in Service.mandatory_arguments:
            self.assertEqual(args[arg], getattr(Service, arg, None))

        # calling this method on a configured service should use the values
        # passed at instanciation time as default values
        service = Service("coconuts", "/migrate", renderer="html")
        args = service.get_arguments({})
        self.assertEqual(args["renderer"], "html")

        # if we specify another renderer for this service, despite the fact
        # that one is already set in the instance, this one should be used
        args = service.get_arguments({"renderer": "foobar"})
        self.assertEqual(args["renderer"], "foobar")

        # test that list elements are not overwritten
        # define a validator for the needs of the test

        service = Service("vaches", "/fetchez", validators=(_validator,))
        self.assertEqual(len(service.validators), 1)
        args = service.get_arguments({"validators": (_validator2,)})

        # the list of validators didn't changed
        self.assertEqual(len(service.validators), 1)

        # but the one returned contains 2 validators
        self.assertEqual(len(args["validators"]), 2)

        # test that exclude effectively removes the items from the list of
        # validators / filters it returns, without removing it from the ones
        # registered for the service.
        service = Service("open bar", "/bar", validators=(_validator, _validator2))
        self.assertEqual(service.validators, [_validator, _validator2])

        args = service.get_arguments({"exclude": _validator2})
        self.assertEqual(args["validators"], [_validator])

        # defining some non-mandatory arguments in a service should make
        # them available on further calls to get_arguments.

        service = Service("vaches", "/fetchez", foobar="baz")
        self.assertIn("foobar", service.arguments)
        self.assertIn("foobar", service.get_arguments())
 def test_max_age_can_be_defined(self):
     foo = Service(name="foo", path="/foo", cors_max_age=42)
     foo.add_view("POST", _stub)
     self.assertEqual(foo.cors_max_age_for(), 42)
 def test_max_age_is_none_if_undefined(self):
     foo = Service(name="foo", path="/foo")
     foo.add_view("POST", _stub)
     self.assertIsNone(foo.cors_max_age_for("POST"))
 def test_method_takes_precendence_for_credential_support(self):
     foo = Service(name="foo", path="/foo", cors_credentials=True)
     foo.add_view("GET", _stub, cors_credentials=False)
     self.assertFalse(foo.cors_support_credentials_for("GET"))
 def test_per_method_credential_support(self):
     foo = Service(name="foo", path="/foo")
     foo.add_view("GET", _stub, cors_credentials=True)
     foo.add_view("POST", _stub)
     self.assertTrue(foo.cors_support_credentials_for("GET"))
     self.assertFalse(foo.cors_support_credentials_for("POST"))
 def test_credential_support_is_disabled_by_default(self):
     foo = Service(name="foo", path="/foo")
     foo.add_view("POST", _stub)
     self.assertFalse(foo.cors_support_credentials_for())