当前位置: 首页>>代码示例>>Python>>正文


Python TestApp.head方法代码示例

本文整理汇总了Python中webtest.TestApp.head方法的典型用法代码示例。如果您正苦于以下问题:Python TestApp.head方法的具体用法?Python TestApp.head怎么用?Python TestApp.head使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在webtest.TestApp的用法示例。


在下文中一共展示了TestApp.head方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_singular_resource

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
    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)
开发者ID:mbijon,项目名称:nefertari,代码行数:54,代码来源:test_resource.py

示例2: TestResource

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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'})
开发者ID:CDC,项目名称:cornice,代码行数:50,代码来源:test_resource.py

示例3: Detalle

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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)
开发者ID:VTacius,项目名称:justine,代码行数:62,代码来源:testDetalle.py

示例4: Creacion

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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)
开发者ID:VTacius,项目名称:justine,代码行数:57,代码来源:testCreacion.py

示例5: test_web_basic

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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'
开发者ID:penfree,项目名称:pyunified-rpc,代码行数:57,代码来源:test_web.py

示例6: test_file_note_header

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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"}'
开发者ID:OneGov,项目名称:onegov.file,代码行数:23,代码来源:test_integration.py

示例7: Borrado

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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)
开发者ID:VTacius,项目名称:justine,代码行数:39,代码来源:testBorrado.py

示例8: TestResource

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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'),
                ])
开发者ID:EastridgeLabs,项目名称:cornice,代码行数:69,代码来源:test_resource.py

示例9: TestResource

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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)
开发者ID:joesteeve,项目名称:cornice,代码行数:93,代码来源:test_imperative_resource.py

示例10: Modificacion

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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)
开发者ID:VTacius,项目名称:justine,代码行数:88,代码来源:testModificacion.py

示例11: TestResource

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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'),
                ])
开发者ID:codersmill,项目名称:cornice,代码行数:86,代码来源:test_resource.py

示例12: TestHttplib

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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()
开发者ID:gawel,项目名称:WSGIProxy2,代码行数:80,代码来源:test_wsgiproxy.py

示例13: BasicUserTest

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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
开发者ID:digitalprime,项目名称:hostdown,代码行数:69,代码来源:tests.py

示例14: test

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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
开发者ID:NanNor,项目名称:qabel-drop,代码行数:73,代码来源:func_test_drop_server.py

示例15: TestHttplib

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import head [as 别名]
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()
开发者ID:gawel,项目名称:WSGIProxy2,代码行数:77,代码来源:tests.py


注:本文中的webtest.TestApp.head方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。