Example #1
0
    def test_singular_resource(self, *a):
        View = get_test_view_class()
        config = _create_config()
        root = config.get_root_resource()
        root.add('thing', view=View)
        grandpa = root.add('grandpa', 'grandpas', view=View)
        wife = grandpa.add('wife', view=View, renderer='string')
        wife.add('child', 'children', view=View)

        config.begin()
        app = TestApp(config.make_wsgi_app())

        self.assertEqual(
            '/grandpas/1/wife',
            route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1)
        )

        self.assertEqual(
            '/grandpas/1',
            route_path('grandpa', testing.DummyRequest(), id=1)
        )

        self.assertEqual(
            '/grandpas/1/wife/children/2',
            route_path('grandpa_wife:child', testing.DummyRequest(),
                       grandpa_id=1, id=2)
        )

        self.assertEqual(app.put('/grandpas').body, six.b('update_many'))
        self.assertEqual(app.head('/grandpas').body, six.b(''))
        self.assertEqual(app.options('/grandpas').body, six.b(''))

        self.assertEqual(app.delete('/grandpas/1').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1').body, six.b(''))

        self.assertEqual(app.put('/thing').body, six.b('replace'))
        self.assertEqual(app.patch('/thing').body, six.b('update'))
        self.assertEqual(app.delete('/thing').body, six.b('delete'))
        self.assertEqual(app.head('/thing').body, six.b(''))
        self.assertEqual(app.options('/thing').body, six.b(''))

        self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace'))
        self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update'))
        self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1/wife').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1/wife').body, six.b(''))

        self.assertEqual(six.b('show'), app.get('/grandpas/1').body)
        self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body)
        self.assertEqual(
            six.b('show'), app.get('/grandpas/1/wife/children/1').body)
Example #2
0
    def test_singular_resource(self, *a):
        View = get_test_view_class()
        config = _create_config()
        root = config.get_root_resource()
        root.add('thing', view=View)
        grandpa = root.add('grandpa', 'grandpas', view=View)
        wife = grandpa.add('wife', view=View, renderer='string')
        wife.add('child', 'children', view=View)

        config.begin()
        app = TestApp(config.make_wsgi_app())

        self.assertEqual(
            '/grandpas/1/wife',
            route_path('grandpa:wife', testing.DummyRequest(), grandpa_id=1)
        )

        self.assertEqual(
            '/grandpas/1',
            route_path('grandpa', testing.DummyRequest(), id=1)
        )

        self.assertEqual(
            '/grandpas/1/wife/children/2',
            route_path('grandpa_wife:child', testing.DummyRequest(),
                       grandpa_id=1, id=2)
        )

        self.assertEqual(app.put('/grandpas').body, six.b('update_many'))
        self.assertEqual(app.head('/grandpas').body, six.b(''))
        self.assertEqual(app.options('/grandpas').body, six.b(''))

        self.assertEqual(app.delete('/grandpas/1').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1').body, six.b(''))

        self.assertEqual(app.put('/thing').body, six.b('replace'))
        self.assertEqual(app.patch('/thing').body, six.b('update'))
        self.assertEqual(app.delete('/thing').body, six.b('delete'))
        self.assertEqual(app.head('/thing').body, six.b(''))
        self.assertEqual(app.options('/thing').body, six.b(''))

        self.assertEqual(app.put('/grandpas/1/wife').body, six.b('replace'))
        self.assertEqual(app.patch('/grandpas/1/wife').body, six.b('update'))
        self.assertEqual(app.delete('/grandpas/1/wife').body, six.b('delete'))
        self.assertEqual(app.head('/grandpas/1/wife').body, six.b(''))
        self.assertEqual(app.options('/grandpas/1/wife').body, six.b(''))

        self.assertEqual(six.b('show'), app.get('/grandpas/1').body)
        self.assertEqual(six.b('show'), app.get('/grandpas/1/wife').body)
        self.assertEqual(
            six.b('show'), app.get('/grandpas/1/wife/children/1').body)
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.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 #4
0
class Detalle(TestCase):
    """
    NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase 
    """

    @classmethod
    def setUpClass(self):

        # Cargamos los datos
        entidad = cargar_datos('usuario')[1]
        self.uid = entidad['uid']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)

        res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token)

    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)

    def test_detalle_usuario(self):
        res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token) 
        respuesta = res.json_body['mensaje'][0]['givenName']
        datos = self.datos['corpus']['givenName']
        
        self.assertEqual(respuesta, datos)

    def test_detalle_claves(self):
        claves = ['dn', 'givenName', 'cn']

        res = self.testapp.get('/usuarios/' + self.uid, params={'claves': ','.join(claves)}, headers=self.token)
        respuesta = res.json_body['mensaje'][0].keys()
        self.assertListEqual(respuesta, claves)

    def test_detalle_claves_noexistentes(self):
        claves = ['dn', 'givenName', 'cn', 'noexistente']

        res = self.testapp.get('/usuarios/' + self.uid, params={'claves': ','.join(claves)}, headers=self.token)
        respuesta = res.json_body['mensaje'][0].keys()
        del claves[claves.index('noexistente')]
        
        self.assertListEqual(respuesta, claves)
    
    def test_detalle_noexistente(self):
        uid = 'fitzcarraldo'
        self.testapp.get('/usuarios/' + uid, status=404, headers=self.token)
        
    def test_detalle_unauth(self):
        self.testapp.post_json('/usuarios' + self.uid, status=404)
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.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 #6
0
def test_web_basic():
    """The web basic test
    """
    class TestService(Service):
        """The test service
        """
        @get('/test/get')
        @post('/test/post')
        @put('/test/put')
        @delete('/test/delete')
        @head('/test/head')
        @patch('/test/patch')
        @options('/test/options')
        @endpoint()
        def test(self):
            """Test
            """
            return 'OK'

        @get('/test2')
        @endpoint()
        def test2(self, param):
            """Test 2
            """
            return 'OK'

    adapter = WebAdapter()
    server = Server([ TestService() ], [ adapter ])
    server.start()
    # Test
    app = TestApp(adapter)
    rsp = app.get('/test', expect_errors = True)
    assert rsp.status_int == 404
    rsp = app.get('/test/get')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.post('/test/post')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.put('/test/put')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.delete('/test/delete')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.head('/test/head')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain'
    rsp = app.patch('/test/patch')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    rsp = app.options('/test/options')
    assert rsp.status_int == 200 and rsp.content_type == 'text/plain' and rsp.text == 'OK'
    # Too many parameters
    rsp = app.get('/test/get?a=1', expect_errors = True)
    assert rsp.status_int == 400
    # Lack of parameters
    rsp = app.get('/test2', expect_errors = True)
    assert rsp.status_int == 400
    rsp = app.get('/test2?param=1')
    assert rsp.status_int == 200 and rsp.text == 'OK'
Example #7
0
class Creacion(TestCase):
    """
    NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase 
    """

    @classmethod
    def setUp(self):

        # Cargamos los datos
        entidad = cargar_datos('usuario')[0]
        self.uid = entidad['uid']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)

    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)

    def test_creacion(self):
        res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token)
        respuesta = res.location
        self.assertEqual(respuesta, 'http://localhost/usuarios/%s' % self.uid)

    def test_creacion_no_json(self):
        datos = "Mínimo esfuerzo para máximo daño"
        self.testapp.post_json('/usuarios', status=400, params=datos, headers=self.token)

    def test_creacion_corpus_faltante(self):
        datos = {'cuerpo': self.datos['corpus'].copy()}
        
        self.testapp.post_json('/usuarios', status=400, params=datos, headers=self.token)

    def test_creacion_usuario_existente(self):
        self.testapp.post_json('/usuarios', status=409, params=self.datos, headers=self.token)
   
    def test_creacion_usuario_datos_inconsistente(self):
        datos = self.datos.copy()
        datos['corpus']['grupo'] = "0"
        datos['corpus']['uid'] = "nuevoUsuario"
        
        self.testapp.post_json('/usuarios', status=400, params=datos, headers=self.token)

    def test_usuarios_creacion_unauth(self):
        self.testapp.post_json('/usuarios', status=403, params=self.datos)
Example #8
0
def test_file_note_header(app):
    ensure_correct_depot(app)

    transaction.begin()
    files = FileCollection(app.session())
    fid = files.add('avatar.png', create_image(1024, 1024), note='Avatar').id
    transaction.commit()

    client = Client(app)

    response = client.get('/storage/{}'.format(fid))
    assert response.headers['X-File-Note'] == '{"note":"Avatar"}'

    response = client.get('/storage/{}/thumbnail'.format(fid))
    assert response.headers['X-File-Note'] == '{"note":"Avatar"}'

    response = client.head('/storage/{}'.format(fid))
    assert response.headers['X-File-Note'] == '{"note":"Avatar"}'

    response = client.head('/storage/{}/thumbnail'.format(fid))
    assert response.headers['X-File-Note'] == '{"note":"Avatar"}'
Example #9
0
class Borrado(TestCase):

    @classmethod
    def setUpClass(self):

        # Cargamos los datos
        entidad = cargar_datos('usuario')[0]
        self.uid = entidad['uid']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)
    
        self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token)
    
    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)
    
    def test_borrado(self):
        self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)
    
    def test_borrado_noexistente(self):
        uid = "fitzcarraldo"
        res = self.testapp.delete('/usuarios/' + uid, status=404, headers=self.token)
    
    def test_borrado_noauth(self):
        self.testapp.delete('/usuarios/' + self.uid, status=403)
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("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'),
                ])
def test():
    app = TestApp(drop_server.app)
    app.get('/illegal',
            status=400)
    app.get('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
            status=204)
    app.head('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
             status=204)

    # missing body
    app.post('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
             headers={'Content-Type': 'application/octet-stream'},
             status=400)

    # excessive body
    app.post('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
             params=2574 * 'x',
             headers={'Content-Type': 'application/octet-stream'},
             status=413)

    timestamp = time()
    app.post('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
             params='a message',
             headers={'Content-Type': 'application/octet-stream'},
             status=200)
    app.head('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
             status=200)

    r = app.get('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
                status=200)
    eq_(r.content_type, 'multipart/mixed')
    assert r.content_length > 0
    r.mustcontain('a message',
                  'Content-Type: application/octet-stream\r\n',
                  'Date: ')

    # space the messages at least one second
    sleep(1)
    app.post('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
             params='second message',
             headers={'Content-Type': 'application/octet-stream'},
             status=200)

    r = app.head('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
                 headers={'If-Modified-Since':
                          formatdate(time() + 1, False, True)},
                 status=304)

    r = app.get('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
                headers={'If-Modified-Since':
                         formatdate(time() + 1, False, True)},
                status=304)

    r = app.head('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
                 headers={'If-Modified-Since':
                          formatdate(timestamp, False, True)},
                 status=200)

    r = app.get('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
                headers={'If-Modified-Since':
                         formatdate(timestamp - 1, False, True)},
                status=200)
    r.mustcontain('a message',
                  'second message')

    r = app.get('/abcdefghijklmnopqrstuvwxyzabcdefghijklmnopo',
                headers={'If-Modified-Since':
                         formatdate(timestamp, False, True)},
                status=200)
    r.mustcontain('second message')
    assert not 'a message' in r
Example #12
0
class BasicUserTest(unittest.TestCase):
	def setUp(self):
		app = get_app('development.ini')
		self.engine = create_engine('sqlite://')

		db = scoped_session(sessionmaker())
		db.configure(bind=self.engine)
		Base.metadata.bind = self.engine
		Base.metadata.create_all(self.engine)

		from webtest import TestApp
		self.testapp = TestApp(app)

	def tearDown(self):
		del self.testapp
		Base.metadata.drop_all(self.engine)

	def test_urls(self):
		self.testapp.get('/')
		self.testapp.get('/api/xmlrpc')

	def test_google_up(self):
		res = self.testapp.get('/')
		res.form['url'] = 'http://google.com'
		nres = res.form.submit()
		# log.debug(nres.text)
		soup = BeautifulSoup(nres.text)
		url = soup.find('h1', id='up')
		log.debug(url)
		assert url
		r = db.query(HTTPUrl).filter(HTTPUrl.host_url == 'http://google.com').one()
		c = db.query(Checked).filter(Checked.http_url_id == r.id).one()
		assert c


	@unittest.skip("not finished")
	def test_head(self):
		res = self.testapp.get('/')
		res.form['url'] = 'http://google.com'
		nres = res.form.submit()
		nres = nres.follow()
		# log.debug(nres.text)
		soup = BeautifulSoup(nres.text)
		url = soup.find('h1', id='url')
		assert url.text
		#test HEAD request
		res = self.testapp.head(url.text)
		assert res.status_int == 200

	@unittest.skip("not finished")
	def test_duplicate(self):
		res = self.testapp.get('/')
		res.form['url'] = 'http://google.co.uk'
		nres = res.form.submit()
		nres = nres.follow()
		# log.debug(nres.text)
		soup = BeautifulSoup(nres.text)
		url = soup.find('h1', id='url')
		res = self.testapp.get('/')
		res.form['url'] = 'http://google.co.uk'
		nres = res.form.submit()
		nres = nres.follow()
		# log.debug(nres.text)
		soup = BeautifulSoup(nres.text)
		url2 = soup.find('h1', id='url')
		log.info(url.text)
		assert url2.text == url.text
Example #13
0
class AppUser:
    """:class:`webtest.TestApp` wrapper for backend functional testing."""

    def __init__(self,
                 app_router: Router,
                 base_path: str='/',
                 header: dict=None,
                 user_path: str='',
                 user_login: str='',
                 user_password: str='',
                 ):
        """Initialize self."""
        self.app_router = app_router
        """The adhocracy wsgi application"""
        self.app = TestApp(app_router)
        """:class:`webtest.TestApp`to send requests to the backend server."""
        self.rest_url = rest_url()
        """backend server url to generate request urls."""
        self.base_path = base_path
        """path prefix to generate request urls."""
        self.header = header or {}
        """default header for requests, mostly for authentication.
           If not set, `user_login` and `user_password` is used to login,
           the new authentication header is stored in `header`.
        """
        if user_password and user_login and not header:
            token, user_path = self._get_token_and_user_path(user_login,
                                                             user_password)
            self.header = {UserTokenHeader: token}
        self.user_password = user_password
        """password for authenticated user."""
        self.user_login = user_login
        """login name for authenticated user."""
        self.user_path = user_path
        """path for authenticated user."""
        self._resolver = DottedNameResolver()

    def _get_token_and_user_path(self, login: str, password: str) -> tuple:
        login_page = self.rest_url + '/login_username'
        data = {'name': login,
                'password': password}
        resp = self.app.post_json(login_page, data).json
        return resp['user_token'], resp['user_path']

    def post_resource(self, path: str,
                      iresource: IInterface,
                      cstruct: dict) -> TestResponse:
        """Build and post request to create a new resource."""
        url = self._build_url(path)
        props = self._build_post_body(iresource, cstruct)
        resp = self.app.post_json(url, props, headers=self.header,
                                  expect_errors=True)
        return resp

    def put(self,
            path: str,
            cstruct: dict={},
            upload_files: [(str, str, bytes)]=None,
            extra_headers: dict={},
            ) -> TestResponse:
        """Put request to modify a resource."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        kwargs = {'headers': headers,
                  'expect_errors': True,
                  }
        if upload_files:
            kwargs['upload_files'] = upload_files
            resp = self.app.put(url, cstruct, **kwargs)
        else:
            resp = self.app.put_json(url, cstruct, **kwargs)
        return resp

    def post(self,
             path: str,
             cstruct: dict={},
             upload_files: [(str, str, bytes)]=None,
             extra_headers: dict={},
             ) -> TestResponse:
        """Post request to create a new resource."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        kwargs = {'headers': headers,
                  'expect_errors': True,
                  }
        if upload_files:
            kwargs['upload_files'] = upload_files
            resp = self.app.post(url, cstruct, **kwargs)
        else:
            resp = self.app.post_json(url, cstruct, **kwargs)
        return resp

    def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict:
        return {'content_type': iresource.__identifier__,
                'data': cstruct}

    def _build_url(self, path: str) -> str:
        if path.startswith('http'):
            return path
        elif path.startswith('/') and (self.base_path == '\\'):
            return self.rest_url + path
        else:
            return self.rest_url + self.base_path + path

    def batch(self, subrequests: list):
        """Build and post batch request to the backend rest server."""
        resp = self.app.post_json(batch_url, subrequests, headers=self.header,
                                  expect_errors=True)
        return resp

    def head(self, path: str, extra_headers={}) -> TestResponse:
        """Send head request to the backend rest server."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        resp = self.app.head(url,
                             headers=headers,
                             expect_errors=True)
        return resp

    def get(self, path: str, params={}, extra_headers={}) -> TestResponse:
        """Send get request to the backend rest server."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        resp = self.app.get(url,
                            headers=headers,
                            params=params,
                            expect_errors=True)
        return resp

    def delete(self, path: str) -> TestResponse:
        """Send delete request to the backend rest server."""
        url = self._build_url(path)
        resp = self.app.delete(url,
                               headers=self.header,
                               expect_errors=True)
        return resp

    def options(self, path: str) -> TestResponse:
        """Send options request to the backend rest server."""
        url = self._build_url(path)
        resp = self.app.options(url, headers=self.header, expect_errors=True)
        return resp

    def get_postable_types(self, path: str) -> []:
        """Send options request and return the postable content types."""
        resp = self.options(path)
        if 'POST' not in resp.json:
            return []
        post_request_body = resp.json['POST']['request_body']
        type_names = sorted([r['content_type'] for r in post_request_body])
        iresources = [self._resolver.resolve(t) for t in type_names]
        return iresources
Example #14
0
class TestResourceRecognition(Test):
    def setUp(self):
        from nefertari.resource import add_resource_routes
        self.config = _create_config()
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='string'
        )
        self.config.begin()
        self.app = TestApp(self.config.make_wsgi_app())
        self.collection_path = '/messages'
        self.collection_name = 'messages'
        self.member_path = '/messages/{id}'
        self.member_name = 'message'

    def test_get_collection(self):
        self.assertEqual(self.app.get('/messages').body, six.b('index'))

    @mock.patch('nefertari.renderers.JsonRendererFactory._trigger_events')
    def test_get_collection_json(self, mock_trigger):
        from nefertari.resource import add_resource_routes
        mock_trigger.side_effect = lambda x, y: x
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='json'
        )
        self.assertEqual(self.app.get('/messages').body, six.b('"index"'))

    @mock.patch('nefertari.renderers.JsonRendererFactory._trigger_events')
    def test_get_collection_nefertari_json(self, mock_trigger):
        from nefertari.resource import add_resource_routes
        mock_trigger.side_effect = lambda x, y: x
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='nefertari_json'
        )
        self.assertEqual(self.app.get('/messages').body, six.b('"index"'))

    def test_get_collection_no_renderer(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config, DummyCrudRenderedView, 'message', 'messages')
        self.assertRaises(ValueError, self.app.get, '/messages')

    def test_post_collection(self):
        result = self.app.post('/messages').body
        self.assertEqual(result, six.b('create'))

    def test_head_collection(self):
        response = self.app.head('/messages')
        self.assertEqual(response.body, six.b(''))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.headers)

    def test_get_member(self):
        result = self.app.get('/messages/1').body
        self.assertEqual(result, six.b('show'))

    def test_head_member(self):
        response = self.app.head('/messages/1')
        self.assertEqual(response.body, six.b(''))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.headers)

    def test_put_member(self):
        result = self.app.put('/messages/1').body
        self.assertEqual(result, six.b('replace'))

    def test_patch_member(self):
        result = self.app.patch('/messages/1').body
        self.assertEqual(result, six.b('update'))

    def test_delete_member(self):
        result = self.app.delete('/messages/1').body
        self.assertEqual(result, six.b('delete'))
Example #15
0
class Modificacion(TestCase):
    """
    NOTA: Sobre la validación de datos, testar directamente nuestra pequeña clase 
    TODO: Validar cambio de grupo principal
    TODO: Validar cambio de estado de la cuenta
    TODO: Validar cambios de grupos
    TODO: Validar cambio de contraseña
    TODO: Validar que tan pocas claves podemos cambiar
    """

    @classmethod
    def setUpClass(self):

        # Cargamos los datos
        entidad = cargar_datos('usuario')[2]
        self.uid = entidad['uid']
        self.datos = {'corpus': entidad}

        # Trabajamos en obtener un token
        self.token = cargar_credenciales()
        
        # Creamos nuestro objeto para pruebas
        from justine import main
        from webtest import TestApp

        app = main({})
        self.testapp = TestApp(app)

        res = self.testapp.post_json('/usuarios', status=201, params=self.datos, headers=self.token)

    @classmethod
    def tearDownClass(self):
        res = self.testapp.head('/usuarios/' + self.uid, status="*", headers=self.token)
        if res.status_int == 200:
            self.testapp.delete('/usuarios/' + self.uid, status=200, headers=self.token)

    def test_actualizacion(self):
        self.datos['corpus']['title'] = "Titulador"
        
        self.testapp.patch_json('/usuarios/' + self.uid, status=200, params=self.datos, headers=self.token)
        
        res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token)
        respuesta = res.json_body['mensaje'][0]['title']
        datos = self.datos['corpus']['title']
        
        self.assertEqual(respuesta, datos)

    def test_actualizacion_displayName(self):
        sn = "Sotomayor"
        givenName = self.datos['corpus']['givenName']
        displayName = givenName + " " + sn 
        
        self.datos['corpus']['sn'] = sn
        self.testapp.patch_json('/usuarios/' + self.uid, status=200, params=self.datos, headers=self.token)
        
        res = self.testapp.get('/usuarios/' + self.uid, status=200, headers=self.token)
        respuesta = res.json_body['mensaje'][0]['displayName']
        
        self.assertEqual(respuesta, displayName)

    def test_corpus_faltante(self):
        datos = {'cuerpo': self.datos['corpus'].copy()}
        
        self.testapp.patch_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token)
    
    def test_json_malformateado(self):
        datos = "Mínimo esfuerzo para máximo daño"
        self.testapp.patch_json('/usuarios/' + self.uid, status=400, params=datos, headers=self.token)
    
    def test_noexistente(self):
        uid = 'fitzcarraldo'
        datos = {'corpus': self.datos['corpus'].copy()}
        datos['corpus']['uid'] = uid
        
        self.testapp.patch_json('/usuarios/' + uid, status=404, params=datos, headers=self.token)

    def test_claves_incompletas(self):
        cuerpo = self.datos['corpus'].copy()
        del cuerpo['sn']
        del cuerpo['givenName']
        datos = {'corpus': cuerpo}
        
        self.testapp.patch_json('/usuarios/' + self.uid, status=200, params=datos, headers=self.token)

    def test_actualizacion_noauth(self):
        self.testapp.patch_json('/usuarios/' + self.uid, status=403, params=self.datos)
Example #16
0
class TestResourceRecognition(Test):
    def setUp(self):
        from nefertari.resource import add_resource_routes
        self.config = _create_config()
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='string'
        )
        self.config.begin()
        self.app = TestApp(self.config.make_wsgi_app())
        self.collection_path = '/messages'
        self.collection_name = 'messages'
        self.member_path = '/messages/{id}'
        self.member_name = 'message'

    def test_get_collection(self):
        self.assertEqual(self.app.get('/messages').body, six.b('index'))

    def test_get_collection_json(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='json'
        )
        self.assertEqual(self.app.get('/messages').body, six.b('"index"'))

    def test_get_collection_nefertari_json(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config,
            DummyCrudRenderedView,
            'message',
            'messages',
            renderer='nefertari_json'
        )
        self.assertEqual(self.app.get('/messages').body, six.b('"index"'))

    def test_get_collection_no_renderer(self):
        from nefertari.resource import add_resource_routes
        add_resource_routes(
            self.config, DummyCrudRenderedView, 'message', 'messages')
        self.assertRaises(ValueError, self.app.get, '/messages')

    def test_post_collection(self):
        result = self.app.post('/messages').body
        self.assertEqual(result, six.b('create'))

    def test_head_collection(self):
        response = self.app.head('/messages')
        self.assertEqual(response.body, six.b(''))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.headers)

    def test_get_member(self):
        result = self.app.get('/messages/1').body
        self.assertEqual(result, six.b('show'))

    def test_head_member(self):
        response = self.app.head('/messages/1')
        self.assertEqual(response.body, six.b(''))
        self.assertEqual(response.status_code, 200)
        self.assertTrue(response.headers)

    def test_put_member(self):
        result = self.app.put('/messages/1').body
        self.assertEqual(result, six.b('replace'))

    def test_patch_member(self):
        result = self.app.patch('/messages/1').body
        self.assertEqual(result, six.b('update'))

    def test_delete_member(self):
        result = self.app.delete('/messages/1').body
        self.assertEqual(result, six.b('delete'))
Example #17
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 #18
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 #19
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)
Example #20
0
class ApiTestCase(utils.TestCase):

    def setUp(self):
        super(ApiTestCase, self).setUp()

        # Mock methods
        db._now = MagicMock(return_value=NOW)   # pylint: disable=W0212
        uuid.uuid4 = MagicMock(return_value=UUID)

        self.db = utils.db_init()
        self.server = api.ImageApiServer()
        self.app = TestApp(self.server.app)

    def tearDown(self):
        super(ApiTestCase, self).tearDown()

    def test_http_error(self):
        self.app.get('/no-such-url', status=404)
        self.app.get('/v1/images/no-such-id', status=400)

    def test_image_create(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        resp = self.app.post('/v1/images', IMAGE_DATA, headers, status=200)

        self.assertEqual(json.loads(resp.body), IMAGE_CREATE_RESP)
        with open('/tmp/dwarf/images/%s' % UUID, 'r') as fh:
            self.assertEqual(fh.read(), IMAGE_DATA)
        # TBD: check the content of the database

    def test_image_create_chunked(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        headers.append(('Transfer-Encoding', 'chunked'))
        resp = self.app.post('/v1/images', IMAGE_DATA_CHUNKED, headers,
                             status=200)

        self.assertEqual(json.loads(resp.body), IMAGE_CREATE_RESP)
        with open('/tmp/dwarf/images/%s' % UUID, 'r') as fh:
            self.assertEqual(fh.read(), IMAGE_DATA)

    def test_image_create_chunked_malformed(self):
        self.app.post('/v1/images', '1', [('Transfer-Encoding', 'chunked')],
                      status=500)

    def test_image_create_chunked_cc(self):
        self.app.post('/v1/images', '\r', [('Transfer-Encoding', 'chunked')],
                      status=500)
        self.app.post('/v1/images', '\r1', [('Transfer-Encoding', 'chunked')],
                      status=500)

    def test_image_list(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        self.app.post('/v1/images', IMAGE_DATA, headers, status=200)
        resp = self.app.get('/v1/images/detail', status=200)

        self.assertEqual(json.loads(resp.body), IMAGE_LIST_RESP)

    def test_image_show(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        self.app.post('/v1/images', IMAGE_DATA, headers, status=200)
        resp = self.app.head('/v1/images/%s' % UUID, status=200)

        self.assertEqual(resp.body, '')
        self.assertEqual(sorted(resp.headers.items()), sorted(IMAGE_SHOW_RESP))

    def test_image_delete(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        self.app.post('/v1/images', IMAGE_DATA, headers, status=200)
        resp = self.app.delete('/v1/images/%s' % UUID, status=200)

        self.assertEqual(resp.body, '')
        self.assertEqual(sorted(resp.headers.items()),
                         sorted(IMAGE_DELETE_RESP))

        self.assertEqual(os.path.exists('/tmp/dwarf/images/%s' % UUID), False)
        resp = self.app.get('/v1/images/detail', status=200)
        self.assertEqual(json.loads(resp.body), {'images': []})
        # TBD: check the content of the database

    def test_image_update(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        self.app.post('/v1/images', IMAGE_DATA, headers, status=200)

        resp = self.app.put('/v1/images/%s' % UUID, status=200)
        self.assertEqual(json.loads(resp.body), IMAGE_CREATE_RESP)

    # -------------------------------------------------------------------------
    # Additional tests for code coverage

    def test_image_delete_cc(self):
        headers = utils.to_headers(IMAGE_CREATE_REQ)
        self.app.post('/v1/images', IMAGE_DATA, headers, status=200)
        os.unlink('/tmp/dwarf/images/%s' % UUID)
        resp = self.app.delete('/v1/images/%s' % UUID, status=200)

        self.assertEqual(resp.body, '')
        self.assertEqual(sorted(resp.headers.items()),
                         sorted(IMAGE_DELETE_RESP))
Example #21
0
class TestHttplib(unittest.TestCase):

    client = 'httplib'
    client_options = {}

    def setUp(self):
        self.server = StopableWSGIServer.create(debug_app)
        self.application_url = self.server.application_url.rstrip('/')
        self.proxy = proxies.HostProxy(self.application_url,
                                       client=self.client,
                                       **self.client_options)
        self.app = TestApp(self.proxy)

    def test_form(self):
        resp = self.app.get('/form.html')
        resp.mustcontain('</form>')
        form = resp.form
        form['name'] = 'gawel'
        resp = form.submit()
        resp.mustcontain('name=gawel')

    def test_head(self):
        resp = self.app.head('/form.html')
        self.assertEqual(resp.status_int, 200)
        self.assertEqual(len(resp.body), 0)

    def test_webob_error(self):
        req = Request.blank('/')
        req.content_length = '-1'
        resp = req.get_response(self.proxy)
        self.assertEqual(resp.status_int, 500, resp)

    def test_status(self):
        resp = self.app.get('/?status=404', status='*')
        self.assertEqual(resp.status_int, 404)

    def test_redirect(self):
        location = self.application_url + '/form.html'
        resp = self.app.get(
            '/?status=301%20Redirect&header-location=' + location,
            status='*')
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

        location = 'http://foo.com'
        resp = self.app.get(
            '/?status=301%20Redirect&header-location=' + location,
            status='*')
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

        location = '/foo'
        resp = self.app.get(
            '/?status=301%20Redirect&header-location=' + location,
            status='*')
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, self.application_url + location)

        location = self.application_url + '/script_name/form.html'
        self.proxy.strip_script_name = False
        resp = self.app.get(
            '/?status=301%20Redirect&header-Location=' + location,
            status='*', extra_environ={'SCRIPT_NAME': '/script_name'})
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

    def test_chunked(self):
        resp = self.app.get('/',
                            headers=[('Transfer-Encoding', 'chunked')])
        resp.mustcontain(no='chunked')

    def test_quoted_utf8_url(self):
        path = '/targets/NR2F1%C3%82-human/'
        resp = self.app.get(path)
        resp.mustcontain(b'PATH_INFO: /targets/NR2F1\xc3\x82-human/')

    def tearDown(self):
        self.server.shutdown()
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 #23
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 #24
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'),
                ])
Example #25
0
class TestHttplib(unittest.TestCase):

    client = 'httplib'
    client_options = {}

    def setUp(self):
        self.server = StopableWSGIServer.create(debug_app)
        self.application_url = self.server.application_url.rstrip('/')
        self.proxy = proxies.HostProxy(self.application_url,
                                       client=self.client,
                                       **self.client_options)
        self.app = TestApp(self.proxy)

    def test_form(self):
        resp = self.app.get('/form.html')
        resp.mustcontain('</form>')
        form = resp.form
        form['name'] = 'gawel'
        resp = form.submit()
        resp.mustcontain('name=gawel')

    def test_head(self):
        resp = self.app.head('/form.html')
        self.assertEqual(resp.status_int, 200)
        self.assertEqual(len(resp.body), 0)

    def test_webob_error(self):
        req = Request.blank('/')
        req.content_length = '-1'
        resp = req.get_response(self.proxy)
        self.assertEqual(resp.status_int, 500, resp)

    def test_not_allowed_method(self):
        resp = self.app.options('/', status='*')
        self.assertEqual(resp.status_int, 405)

    def test_status(self):
        resp = self.app.get('/?status=404', status='*')
        self.assertEqual(resp.status_int, 404)

    def test_redirect(self):
        location = self.application_url + '/form.html'
        resp = self.app.get('/?status=301%20Redirect&header-location=' +
                            location,
                            status='*')
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

        location = 'http://foo.com'
        resp = self.app.get('/?status=301%20Redirect&header-location=' +
                            location,
                            status='*')
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

        location = '/foo'
        resp = self.app.get('/?status=301%20Redirect&header-location=' +
                            location,
                            status='*')
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, self.application_url + location)

        location = self.application_url + '/script_name/form.html'
        self.proxy.strip_script_name = False
        resp = self.app.get('/?status=301%20Redirect&header-Location=' +
                            location,
                            status='*',
                            extra_environ={'SCRIPT_NAME': '/script_name'})
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

    def test_chunked(self):
        resp = self.app.get('/', headers=[('Transfer-Encoding', 'chunked')])
        resp.mustcontain(no='chunked')

    def tearDown(self):
        self.server.shutdown()
Example #26
0
class TestHttplib(unittest.TestCase):

    client = "httplib"
    client_options = {}

    def setUp(self):
        self.server = StopableWSGIServer.create(debug_app)
        self.application_url = self.server.application_url.rstrip("/")
        self.proxy = proxies.HostProxy(self.application_url, client=self.client, **self.client_options)
        self.app = TestApp(self.proxy)

    def test_form(self):
        resp = self.app.get("/form.html")
        resp.mustcontain("</form>")
        form = resp.form
        form["name"] = "gawel"
        resp = form.submit()
        resp.mustcontain("name=gawel")

    def test_head(self):
        resp = self.app.head("/form.html")
        self.assertEqual(resp.status_int, 200)
        self.assertEqual(len(resp.body), 0)

    def test_webob_error(self):
        req = Request.blank("/")
        req.content_length = "-1"
        resp = req.get_response(self.proxy)
        self.assertEqual(resp.status_int, 500, resp)

    def test_not_allowed_method(self):
        resp = self.app.options("/", status="*")
        self.assertEqual(resp.status_int, 405)

    def test_status(self):
        resp = self.app.get("/?status=404", status="*")
        self.assertEqual(resp.status_int, 404)

    def test_redirect(self):
        location = self.application_url + "/form.html"
        resp = self.app.get("/?status=301%20Redirect&header-location=" + location, status="*")
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

        location = "http://foo.com"
        resp = self.app.get("/?status=301%20Redirect&header-location=" + location, status="*")
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

        location = "/foo"
        resp = self.app.get("/?status=301%20Redirect&header-location=" + location, status="*")
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, self.application_url + location)

        location = self.application_url + "/script_name/form.html"
        self.proxy.strip_script_name = False
        resp = self.app.get(
            "/?status=301%20Redirect&header-Location=" + location,
            status="*",
            extra_environ={"SCRIPT_NAME": "/script_name"},
        )
        self.assertEqual(resp.status_int, 301, resp)
        self.assertEqual(resp.location, location)

    def test_chunked(self):
        resp = self.app.get("/", headers=[("Transfer-Encoding", "chunked")])
        resp.mustcontain(no="chunked")

    def test_quoted_utf8_url(self):
        path = "/targets/NR2F1%C3%82-human/"
        resp = self.app.get(path)
        resp.mustcontain(b"PATH_INFO: /targets/NR2F1\xc3\x82-human/")

    def tearDown(self):
        self.server.shutdown()
Example #27
0
class AppUser:
    """:class:`webtest.TestApp` wrapper for backend functional testing."""
    def __init__(
        self,
        app_router: Router,
        base_path: str = '/',
        header: dict = None,
        user_path: str = '',
        user_login: str = '',
        user_password: str = '',
    ):
        """Initialize self."""
        self.app_router = app_router
        """The adhocracy wsgi application"""
        self.app = TestApp(app_router)
        """:class:`webtest.TestApp`to send requests to the backend server."""
        self.rest_url = rest_url()
        """backend server url to generate request urls."""
        self.base_path = base_path
        """path prefix to generate request urls."""
        self.header = header or {}
        """default header for requests, mostly for authentication.
           If not set, `user_login` and `user_password` is used to login,
           the new authentication header is stored in `header`.
        """
        if user_password and user_login and not header:
            token, user_path = self._get_token_and_user_path(
                user_login, user_password)
            self.header = {UserTokenHeader: token}
        self.user_password = user_password
        """password for authenticated user."""
        self.user_login = user_login
        """login name for authenticated user."""
        self.user_path = user_path
        """path for authenticated user."""
        self._resolver = DottedNameResolver()

    def _get_token_and_user_path(self, login: str, password: str) -> tuple:
        login_page = self.rest_url + '/login_username'
        data = {'name': login, 'password': password}
        resp = self.app.post_json(login_page, data).json
        return resp['user_token'], resp['user_path']

    def post_resource(self, path: str, iresource: IInterface,
                      cstruct: dict) -> TestResponse:
        """Build and post request to create a new resource."""
        url = self._build_url(path)
        props = self._build_post_body(iresource, cstruct)
        resp = self.app.post_json(url,
                                  props,
                                  headers=self.header,
                                  expect_errors=True)
        return resp

    def put(
        self,
        path: str,
        cstruct: dict = {},
        upload_files: [(str, str, bytes)] = None,
        extra_headers: dict = {},
    ) -> TestResponse:
        """Put request to modify a resource."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        kwargs = {
            'headers': headers,
            'expect_errors': True,
        }
        if upload_files:
            kwargs['upload_files'] = upload_files
            resp = self.app.put(url, cstruct, **kwargs)
        else:
            resp = self.app.put_json(url, cstruct, **kwargs)
        return resp

    def post(
        self,
        path: str,
        cstruct: dict = {},
        upload_files: [(str, str, bytes)] = None,
        extra_headers: dict = {},
    ) -> TestResponse:
        """Post request to create a new resource."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        kwargs = {
            'headers': headers,
            'expect_errors': True,
        }
        if upload_files:
            kwargs['upload_files'] = upload_files
            resp = self.app.post(url, cstruct, **kwargs)
        else:
            resp = self.app.post_json(url, cstruct, **kwargs)
        return resp

    def _build_post_body(self, iresource: IInterface, cstruct: dict) -> dict:
        return {'content_type': iresource.__identifier__, 'data': cstruct}

    def _build_url(self, path: str) -> str:
        if path.startswith('http'):
            return path
        elif path.startswith('/') and (self.base_path == '\\'):
            return self.rest_url + path
        else:
            return self.rest_url + self.base_path + path

    def batch(self, subrequests: list):
        """Build and post batch request to the backend rest server."""
        resp = self.app.post_json(batch_url,
                                  subrequests,
                                  headers=self.header,
                                  expect_errors=True)
        return resp

    def head(self, path: str, extra_headers={}) -> TestResponse:
        """Send head request to the backend rest server."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        resp = self.app.head(url, headers=headers, expect_errors=True)
        return resp

    def get(self, path: str, params={}, extra_headers={}) -> TestResponse:
        """Send get request to the backend rest server."""
        url = self._build_url(path)
        headers = copy(self.header)
        headers.update(extra_headers)
        resp = self.app.get(url,
                            headers=headers,
                            params=params,
                            expect_errors=True)
        return resp

    def delete(self, path: str) -> TestResponse:
        """Send delete request to the backend rest server."""
        url = self._build_url(path)
        resp = self.app.delete(url, headers=self.header, expect_errors=True)
        return resp

    def options(self, path: str) -> TestResponse:
        """Send options request to the backend rest server."""
        url = self._build_url(path)
        resp = self.app.options(url, headers=self.header, expect_errors=True)
        return resp

    def get_postable_types(self, path: str) -> []:
        """Send options request and return the postable content types."""
        resp = self.options(path)
        if 'POST' not in resp.json:
            return []
        post_request_body = resp.json['POST']['request_body']
        type_names = sorted([r['content_type'] for r in post_request_body])
        iresources = [self._resolver.resolve(t) for t in type_names]
        return iresources