Example #1
0
class TestResource(TestCase):

    def setUp(self):
        from pyramid.renderers import JSONP
        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):

        self.assertEquals(
                self.app.get("/users").json,
                {'users': [1, 2]})

        self.assertEquals(
                self.app.get("/users/1").json,
                {'name': 'gawel'})
        resp = self.app.get("/users/1?callback=test")
        self.assertEquals(resp.body,
                'test({"name": "gawel"})', resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEquals(
                self.app.post("/users",
                    headers={'Accept': 'text/json'},
                    params=json.dumps({'test': 'yeah'})).json,
                {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)
    
    def test_head_and_patch(self):
        self.app.head("/users", status=200)
        self.app.head("/users/1", status=200)
        
        self.assertEquals(
                self.patch("/users", status=200).json,
                {'test': 'yeah'})
        self.assertEquals(
                self.patch("/users/1", status=200).json,
                {'test': 'yeah'})
Example #2
0
class TestResource(TestCase):
    def setUp(self):
        from pyramid.renderers import JSONP
        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):

        self.assertEquals(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEquals(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")
        self.assertEquals(resp.body, b'test({"name": "gawel"})', resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEquals(
            self.app.post("/users",
                          headers={
                              'Accept': 'text/json'
                          },
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users", status=200)
        self.app.head("/users/1", status=200)

        self.assertEquals(
            self.patch("/users", status=200).json, {'test': 'yeah'})

        self.assertEquals(
            self.patch("/users/1", status=200).json, {'test': 'yeah'})
Example #3
0
class TestResource(TestCase):

    def setUp(self):
        from pyramid.renderers import JSONP
        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):

        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")
        self.assertEqual(resp.body, b'test({"name": "gawel"})', resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users", headers={'Accept': 'text/json'},
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(
            self.patch("/users").json,
            {'test': 'yeah'})

        self.assertEqual(
            self.patch("/users/1").json,
            {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('collection_user_service'))  # service must exist

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    if validationapp.COLANDER:
        def test_schema_on_resource(self):
            User.schema = CorniceSchema.from_colander(
                    validationapp.FooBarSchema)
            result = self.patch("/users/1", status=400).json
            self.assertEquals(
                [(e['name'], e['description']) for e in result['errors']], [
                    ('foo', 'foo is missing'),
                    ('bar', 'bar is missing'),
                    ('yeah', 'yeah is missing'),
                ])
class TestResource(TestCase):

    def setUp(self):
        from pyramid.renderers import JSONP

        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.authz_policy = ACLAuthorizationPolicy()
        self.config.set_authorization_policy(self.authz_policy)

        self.authn_policy = AuthTktAuthenticationPolicy('$3kr1t')
        self.config.set_authentication_policy(self.authn_policy)

        add_view(ThingImp.collection_get, permission='read')
        thing_resource = add_resource(
            ThingImp, collection_path='/thing', path='/thing/{id}',
            name='thing_service')

        add_view(UserImp.get, renderer='json')
        add_view(UserImp.get, renderer='jsonp')
        add_view(UserImp.collection_post, renderer='json', accept='text/json')
        user_resource = add_resource(
            UserImp, collection_path='/users', path='/users/{id}',
            name='user_service', factory=dummy_factory)

        self.config.add_cornice_resource(thing_resource)
        self.config.add_cornice_resource(user_resource)
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):
        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")

        self.assertIn(b'test({"name": "gawel"})', resp.body, msg=resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users", headers={'Accept': 'text/json'},
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(
            self.patch("/users").json,
            {'test': 'yeah'})

        self.assertEqual(
            self.patch("/users/1").json,
            {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        # service must exist
        self.assert_(route_url('collection_user_service'))

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    def test_acl_support_unauthenticated_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_unauthenticated_forbidden_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        with mock.patch.object(self.authn_policy, 'authenticated_userid', return_value=None):
            result = self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_authenticated_allowed_thing_get(self):
        with mock.patch.object(self.authn_policy, 'unauthenticated_userid', return_value='alice'):
            with mock.patch.object(self.authn_policy, 'authenticated_userid', return_value='alice'):
                result = self.app.get('/thing', status=HTTPOk.code)
                self.assertEqual("yay", result.json)
Example #5
0
class TestResource(TestCase):

    def setUp(self):
        from pyramid.renderers import JSONP

        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.authz_policy = ACLAuthorizationPolicy()
        self.config.set_authorization_policy(self.authz_policy)

        self.authn_policy = AuthTktAuthenticationPolicy('$3kr1t')
        self.config.set_authentication_policy(self.authn_policy)
        self.config.scan("cornice.tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):
        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")

        self.assertIn(b'test({"name": "gawel"})', resp.body, msg=resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users", headers={'Accept': 'text/json'},
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(
            self.patch("/users").json,
            {'test': 'yeah'})

        self.assertEqual(
            self.patch("/users/1").json,
            {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        # service must exist
        self.assert_(route_url('collection_user_service'))

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    def test_acl_support_unauthenticated_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_authenticated_allowed_thing_get(self):
        with mock.patch.object(self.authn_policy, 'unauthenticated_userid',
                               return_value='alice'):
            result = self.app.get('/thing', status=HTTPOk.code)
            self.assertEqual("yay", result.json)

    if validationapp.COLANDER:
        def test_schema_on_resource(self):
            User.schema = CorniceSchema.from_colander(
                validationapp.FooBarSchema)
            result = self.patch("/users/1", status=400).json
            self.assertEquals(
                [(e['name'], e['description']) for e in result['errors']], [
                    ('foo', 'foo is missing'),
                    ('bar', 'bar is missing'),
                    ('yeah', 'yeah is missing'),
                ])
Example #6
0
class TestResource(TestCase):

    def setUp(self):
        from pyramid.renderers import JSONP

        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.authz_policy = ACLAuthorizationPolicy()
        self.config.set_authorization_policy(self.authz_policy)

        self.authn_policy = AuthTktAuthenticationPolicy('$3kr1t')
        self.config.set_authentication_policy(self.authn_policy)
        self.config.scan("tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):
        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")

        self.assertIn(b'test({"name": "gawel"})', resp.body, msg=resp.body)

    @mock.patch('cornice.resource.Service')
    def test_without_collection_path_has_one_service(self, mocked_service):
        @resource(path='/nocollection/{id}', name='nocollection')
        class NoCollection(object):
            def __init__(self, request, context=None):
                pass
        self.assertEqual(mocked_service.call_count, 1)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users", headers={'Accept': 'text/json'},
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(
            self.patch("/users").json,
            {'test': 'yeah'})

        self.assertEqual(
            self.patch("/users/1").json,
            {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        # service must exist
        self.assert_(route_url('collection_user_service'))

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    @mock.patch('cornice.resource.Service')
    def test_collection_acl_can_be_different(self, mocked_service):
        @resource(collection_path='/list', path='/list/{id}', name='list',
                  collection_acl=mock.sentinel.collection_acl,
                  acl=mock.sentinel.acl)
        class List(object):
            pass
        acls_args = [kw['acl'] for _, kw in mocked_service.call_args_list]
        self.assertIn(mock.sentinel.acl, acls_args)
        self.assertIn(mock.sentinel.collection_acl, acls_args)

    def test_acl_support_unauthenticated_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_authenticated_allowed_thing_get(self):
        with mock.patch.object(self.authn_policy, 'unauthenticated_userid',
                               return_value='alice'):
            result = self.app.get('/thing', status=HTTPOk.code)
            self.assertEqual("yay", result.json)
Example #7
0
class BaseWebTest(TestCase):
    def setUp(self):
        self.root = mkdtemp(prefix='assnet_test_root')
        Storage.create(self.root)
        server = Server(self.root)
        self.app = TestApp(server)

    def tearDown(self):
        if self.root:
            shutil.rmtree(self.root)

    def test_listAndDownload(self):
        res = self.app.get("/")
        assert "<title>Index of /</title>" in res.body

        with open(os.path.join(self.root, "penguins_are_cute"), 'w') as f:
            f.write("HELLO")

        res = self.app.get("/")
        assert "penguins_are_cute" in res.body

        res = self.app.get("/penguins_are_cute")
        assert "HELLO" == res.body

    def test_pathNormalization(self):
        os.mkdir(os.path.join(self.root, "penguins"))
        with open(os.path.join(self.root, "penguins", "gentoo"), 'w') as f:
            f.write("The best penguin.")

        # trailing slash for directories
        res = self.app.get("/penguins/", status=200)

        res = self.app.get("/penguins", status=302)
        assert res.location == "http://localhost/penguins/"
        res.follow(status=200)

        res = self.app.get("/penguins?view=list", status=302)
        assert res.location == "http://localhost/penguins/?view=list"
        res.follow(status=200)

        # no trailing slash for files
        res = self.app.get("/penguins/gentoo", status=200)

        res = self.app.get("/penguins/gentoo/", status=302)
        assert res.location == "http://localhost/penguins/gentoo"
        res.follow(status=200)

        res = self.app.get("/penguins/gentoo/?view=raw", status=302)
        assert res.location == "http://localhost/penguins/gentoo?view=raw"
        res.follow(status=200)

        # limit cases
        res = self.app.get("/", status=200)

        res = self.app.get("//", status=302)
        assert res.location == "http://localhost/"
        res.follow(status=200)

        # it fails without the http://localhost
        res = self.app.get("http://localhost///", status=302)
        assert res.location == "http://localhost/"
        res.follow(status=200)

        res = self.app.get("http://localhost////", status=302)
        assert res.location == "http://localhost/"
        res.follow(status=200)

        # more sanitization
        res = self.app.get("/penguins///", status=302)
        assert res.location == "http://localhost/penguins/"
        res.follow(status=200)
        res = self.app.get("/penguins/..//..", status=302)
        assert res.location == "http://localhost/"
        res.follow(status=200)
        res = self.app.get("/../", status=302)
        assert res.location == "http://localhost/"
        res.follow(status=200)
        res = self.app.get(r"/penguins\..\penguins/..", status=302)
        assert res.location == "http://localhost/"
        res.follow(status=200)
        res = self.app.get(r"/penguins\\\gentoo\\", status=302)
        assert res.location == "http://localhost/penguins/gentoo"
        res.follow(status=200)

    def test_notFound(self):
        self.app.get("/penguins/", status=404)
        self.app.get("/penguins", status=404)

    def test_listWithParent(self):
        os.mkdir(os.path.join(self.root, "penguins"))
        res = self.app.get("/", status=200)
        assert "Parent directory" not in res.body
        res = self.app.get("/penguins/", status=200)
        assert "Parent directory" in res.body
        res = res.click("Parent directory")
        assert "<title>Index of /</title>" in res.body

    def test_actionsInRoot(self):
        os.mkdir(os.path.join(self.root, 'penguins'))
        with open(os.path.join(self.root, 'penguins', 'gentoo'), 'w') as f:
            f.write('HELLO')
        res = self.app.get('/?action=login', status=200)
        assert 'penguins' not in res.body
        res = self.app.get('/?foo=bar&action=login', status=200)
        assert 'penguins' not in res.body
        self.app.get('/doesnotexist?action=login', status=404)
        self.app.get('/doesnotexist/?action=login', status=404)
        res = self.app.get('/penguins/?action=login', status=200)
        assert 'gentoo' in res.body
        res = self.app.get('/penguins/gentoo?action=login', status=200)
        assert 'HELLO' == res.body

    def test_methods(self):
        self.app._gen_request('HEAD', '/?view=text_list', status=200)
        self.app.get('/?view=text_list', status=200)
        self.app.post('/?view=text_list', status=405)
        self.app.put('/?view=text_list', status=405)
        self.app.delete('/?view=text_list', status=405)

        self.app.get('/?action=logout', status=302)
        self.app.post('/?action=logout', status=405)

        self.app.get('/?action=login', status=200)
        self.app.post('/?action=login', status=200)
        self.app.post('/?action=login', {'_method': 'DELETE'}, status=405)

        self.app.post('/?_method=GET', status=405)
        self.app.post('/?action=login', {'_method': 'HEAD'}, status=405)

    def test_initConfig(self):
        os.mkdir(os.path.join(self.root, "penguins"))
        self.app.get('http://assnet.test/penguins/', status=200)

        storage = Storage.lookup(self.root)
        assert storage.get_config().data['web']['root_url'] == 'http://assnet.test/'
        assert storage.get_config().data['web']['cookie_secret']
Example #8
0
class TestResource(TestCase):
    def setUp(self):
        from pyramid.renderers import JSONP
        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):
        from pkg_resources import parse_version, get_distribution
        current_version = parse_version(get_distribution('pyramid').version)

        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")

        if current_version < parse_version('1.5a4'):
            self.assertEqual(resp.body, b'test({"name": "gawel"})', resp.body)
        else:
            self.assertEqual(resp.body, b'test({"name": "gawel"});', resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users",
                          headers={
                              'Accept': 'text/json'
                          },
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(self.patch("/users").json, {'test': 'yeah'})

        self.assertEqual(self.patch("/users/1").json, {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        # service must exist
        self.assert_(route_url('collection_user_service'))

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    if validationapp.COLANDER:

        def test_schema_on_resource(self):
            User.schema = CorniceSchema.from_colander(
                validationapp.FooBarSchema)
            result = self.patch("/users/1", status=400).json
            self.assertEquals([(e['name'], e['description'])
                               for e in result['errors']], [
                                   ('foo', 'foo is missing'),
                                   ('bar', 'bar is missing'),
                                   ('yeah', 'yeah is missing'),
                               ])
Example #9
0
class TestResource(TestCase):
    def setUp(self):
        from pyramid.renderers import JSONP

        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.authz_policy = ACLAuthorizationPolicy()
        self.config.set_authorization_policy(self.authz_policy)

        self.authn_policy = AuthTktAuthenticationPolicy('$3kr1t')
        self.config.set_authentication_policy(self.authn_policy)

        add_view(ThingImp.collection_get, permission='read')
        thing_resource = add_resource(ThingImp,
                                      collection_path='/thing',
                                      path='/thing/{id}',
                                      name='thing_service',
                                      collection_acl=my_collection_acl)

        add_view(UserImp.get, renderer='json')
        add_view(UserImp.get, renderer='jsonp')
        add_view(UserImp.collection_post, renderer='json', accept='text/json')
        user_resource = add_resource(UserImp,
                                     collection_path='/users',
                                     path='/users/{id}',
                                     name='user_service',
                                     factory=dummy_factory)

        self.config.add_cornice_resource(thing_resource)
        self.config.add_cornice_resource(user_resource)
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):
        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")

        self.assertIn(b'test({"name": "gawel"})', resp.body, msg=resp.body)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users",
                          headers={
                              'Accept': 'text/json'
                          },
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(self.patch("/users").json, {'test': 'yeah'})

        self.assertEqual(self.patch("/users/1").json, {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        # service must exist
        self.assert_(route_url('collection_user_service'))

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    def test_acl_support_unauthenticated_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_authenticated_allowed_thing_get(self):
        with mock.patch.object(self.authn_policy,
                               'unauthenticated_userid',
                               return_value='alice'):
            result = self.app.get('/thing', status=HTTPOk.code)
            self.assertEqual("yay", result.json)
Example #10
0
class TestResource(TestCase):
    def setUp(self):
        from pyramid.renderers import JSONP

        self.config = testing.setUp()
        self.config.add_renderer('jsonp', JSONP(param_name='callback'))
        self.config.include("cornice")
        self.authz_policy = ACLAuthorizationPolicy()
        self.config.set_authorization_policy(self.authz_policy)

        self.authn_policy = AuthTktAuthenticationPolicy('$3kr1t')
        self.config.set_authentication_policy(self.authn_policy)
        self.config.scan("tests.test_resource")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_basic_resource(self):
        self.assertEqual(self.app.get("/users").json, {'users': [1, 2]})

        self.assertEqual(self.app.get("/users/1").json, {'name': 'gawel'})

        resp = self.app.get("/users/1?callback=test")

        self.assertIn(b'test({"name": "gawel"})', resp.body, msg=resp.body)

    @mock.patch('cornice.resource.Service')
    def test_without_collection_path_has_one_service(self, mocked_service):
        @resource(path='/nocollection/{id}', name='nocollection')
        class NoCollection(object):
            def __init__(self, request, context=None):
                pass

        self.assertEqual(mocked_service.call_count, 1)

    def test_accept_headers(self):
        # the accept headers should work even in case they're specified in a
        # resource method
        self.assertEqual(
            self.app.post("/users",
                          headers={
                              'Accept': 'text/json'
                          },
                          params=json.dumps({'test': 'yeah'})).json,
            {'test': 'yeah'})

    def patch(self, *args, **kwargs):
        return self.app._gen_request('PATCH', *args, **kwargs)

    def test_head_and_patch(self):
        self.app.head("/users")
        self.app.head("/users/1")

        self.assertEqual(self.patch("/users").json, {'test': 'yeah'})

        self.assertEqual(self.patch("/users/1").json, {'test': 'yeah'})

    def test_context_factory(self):
        self.assertEqual(self.app.put('/users/1').json, {'type': 'context!'})

    def test_explicit_collection_service_name(self):
        route_url = testing.DummyRequest().route_url
        # service must exist
        self.assert_(route_url('collection_user_service'))

    def test_explicit_service_name(self):
        route_url = testing.DummyRequest().route_url
        self.assert_(route_url('user_service', id=42))  # service must exist

    @mock.patch('cornice.resource.Service')
    def test_factory_is_autowired(self, mocked_service):
        @resource(collection_path='/list', path='/list/{id}', name='list')
        class List(object):
            pass

        factory_args = [
            kw.get('factory') for _, kw in mocked_service.call_args_list
        ]
        self.assertEqual([List, List], factory_args)

    def test_acl_is_deprecated(self):
        def custom_acl(request):
            return []

        with self.assertRaises(ConfigurationError):

            @resource(collection_path='/list',
                      path='/list/{id}',
                      name='list',
                      collection_acl=custom_acl,
                      acl=custom_acl)
            class List(object):
                pass

    def test_acl_support_unauthenticated_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_unauthenticated_forbidden_thing_get(self):
        # calling a view with permissions without an auth'd user => 403
        with mock.patch.object(self.authn_policy,
                               'authenticated_userid',
                               return_value=None):
            result = self.app.get('/thing', status=HTTPForbidden.code)

    def test_acl_support_authenticated_allowed_thing_get(self):
        with mock.patch.object(self.authn_policy,
                               'unauthenticated_userid',
                               return_value='alice'):
            with mock.patch.object(self.authn_policy,
                                   'authenticated_userid',
                                   return_value='alice'):
                result = self.app.get('/thing', status=HTTPOk.code)
                self.assertEqual("yay", result.json)