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


Python TestApp.post方法代码示例

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


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

示例1: test_validation

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
    def test_validation(self):
        app = TestApp(main({}))
        app.get('/service', status=400)

        res = app.post('/service', params='buh', status=400)
        self.assertTrue('Not a json body' in res.body)

        res = app.post('/service', params=json.dumps('buh'))

        self.assertEqual(res.body, json.dumps({'body': '"buh"'}))

        app.get('/service?paid=yup')

        # valid = foo is one
        res = app.get('/service?foo=1&paid=yup')
        self.assertEqual(res.json['foo'], 1)

        # invalid value for foo
        res = app.get('/service?foo=buh&paid=yup', status=400)

        # check that json is returned
        errors = Errors.from_json(res.body)
        self.assertEqual(len(errors), 1)

        # let's see the docstring !
        apidocs = app.app.registry.settings['apidocs']
        post_doc = apidocs[('/service', 'POST')]['docstring']
        self.assertEqual(post_doc, 'The request body should be a JSON object.')
开发者ID:almet,项目名称:cornice,代码行数:30,代码来源:test_validation.py

示例2: test_register_and_verify_user

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
def test_register_and_verify_user():
    config.activate_profile()
    _clear_db()
    s, user_manager = _get_user_manager()
    app = controllers.make_app()
    app = TestApp(app)
    resp = app.post('/register/new/BillBixby', dict(email="[email protected]",
                                                    password="notangry"))
    assert resp.content_type == "application/json"
    data = simplejson.loads(resp.body)
    assert data == {}
    assert resp.cookies_set['auth_tkt']
    assert app.cookies
    billbixby = user_manager.get_user("BillBixby")
    sample_project = model.get_project(billbixby, billbixby, "SampleProject")
    files = [file.name for file in sample_project.list_files()]
    assert "readme.txt" in files
    
    # should be able to run again without an exception appearing
    resp = app.post('/register/new/BillBixby', dict(email="[email protected]",
                                                    password="notangry"),
                    status=409)
    
    # with the cookie set, we should be able to retrieve the 
    # logged in name
    resp = app.get('/register/userinfo/')
    assert resp.content_type == 'application/json'
    data = simplejson.loads(resp.body)
    assert data['username'] == 'BillBixby'
    assert 'quota' in data
    assert data['quota'] == 15728640
    assert 'amountUsed' in data
    
    resp = app.get("/file/at/BespinSettings/config.js")
    app.post("/file/close/BespinSettings/config.js")
开发者ID:spot,项目名称:bespin,代码行数:37,代码来源:test_users.py

示例3: injectionattack

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
def injectionattack():
    app = TestApp(test.app)
    app.post('/login', {'username':'user','password':'pass'})
    assert app.get('/admin').status == '200 OK'
    app.get('/logout')
    app.reset()
    assert app.get('/admin').status == '401 Unauthorized'
开发者ID:AshleyRegan,项目名称:CSC485,代码行数:9,代码来源:attack.py

示例4: test_previous_next

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
def test_previous_next():
    c = Client(App())

    c.post('/documents/add_submit', {'title': 'Two', 'content': 'Secundus'})

    response = c.get('/documents/?limit=1&offset=0')
    expected_documents = [{
        "id": 1,
        "title": "My Title",
        "content": "My Content",
        "link": "http://localhost/documents/1"
    }]

    assert response.json["documents"] == expected_documents
    assert "http://localhost/documents/add" in response.json["add"]
    assert response.json["previous"] is None
    assert "http://localhost/documents" in response.json["next"]
    assert "limit=1" in response.json["next"]
    assert "offset=1" in response.json["next"]

    response = c.get('/documents/?limit=1&offset=1')
    expected_documents = [{
        "id": 2,
        "title": "Two",
        "content": "Secundus",
        "link": "http://localhost/documents/2"
    }]

    assert response.json["documents"] == expected_documents
    assert "http://localhost/documents/add" in response.json["add"]
    assert "http://localhost/documents" in response.json["previous"]
    assert "limit=1" in response.json["previous"]
    assert "offset=0" in response.json["previous"]
    assert response.json["next"] is None
开发者ID:morepath,项目名称:morepath_sqlalchemy,代码行数:36,代码来源:test_sqlalchemy.py

示例5: TestApplication

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
class TestApplication(unittest.TestCase):
    def setUp(self):
        logging.basicConfig(level=logging.INFO)
        self.redis = mock.Mock()

        app.db_client = self.redis
        self.test_app = TestApp(app)

    def test_health_check(self):
        resp = self.test_app.get("/health_check")
        self.assertEqual(200, resp.status_int)

    def test_add_vote(self):
        self.test_app.get("/vote/test_key")

        self.redis.incrVote.assert_called_with(u"test_key")
        self.redis.getVote.assert_called_with(u"test_key")

    def test_get_vote(self):
        self.test_app.post("/clear", {"key":"test_key"})
        self.redis.clearVote.assert_called_with("test_key")

    @mock.patch('requests.get')
    def test_proxy_hulu(self, mock_requests):
        response = mock.Mock()
        response.status_code = 200
        mock_requests.return_value = response

        resp = self.test_app.get("/proxy_hulu")
        self.assertEqual(200, resp.status_int)
        mock_requests.assert_called_with("http://www.hulu.com")
开发者ID:ycui1984,项目名称:hackathonJan2016,代码行数:33,代码来源:test_app.py

示例6: TestViewBase

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
class TestViewBase(unittest.TestCase):
    """In setup, bootstrap the app and make sure we clean up after ourselves

    """
    def setUp(self):
        """Setup Tests"""
        from pyramid.paster import get_app
        from bookie.tests import BOOKIE_TEST_INI
        app = get_app(BOOKIE_TEST_INI, 'bookie')
        from webtest import TestApp
        self.app = TestApp(app)
        testing.setUp()
        res = DBSession.execute(
            "SELECT api_key FROM users WHERE username = 'admin'").\
            fetchone()
        self.api_key = res['api_key']

    def tearDown(self):
        """Tear down each test"""
        testing.tearDown()
        empty_db()

    def _login_admin(self):
        """Make the login call to the app"""
        self.app.post(
            '/login',
            params={
                "login": u"admin",
                "password": u"admin",
                "form.submitted": u"Log In",
            },
            status=302)
开发者ID:BraindeadCrew,项目名称:Bookie,代码行数:34,代码来源:__init__.py

示例7: test_simple_validation

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
    def test_simple_validation(self):
        class RegistrationSchema(Schema):
            first_name         = validators.String(not_empty=True)
            last_name          = validators.String(not_empty=True)
            email              = validators.Email()
            username           = validators.PlainText()
            password           = validators.String()
            password_confirm   = validators.String()
            age                = validators.Int()
            chained_validators = [
                validators.FieldsMatch('password', 'password_confirm')
            ]
        

        class RootController(object):
            @expose(schema=RegistrationSchema())
            def index(self, first_name, 
                            last_name, 
                            email, 
                            username, 
                            password,
                            password_confirm,
                            age):
                assert age == 31
                assert isinstance(age, int)
                return 'Success!'
            
            @expose(json_schema=RegistrationSchema())
            def json(self, data):
                assert data['age'] == 31
                assert isinstance(data['age'], int)
                return 'Success!'


        # test form submissions
        app = TestApp(make_app(RootController()))
        r = app.post('/', dict(
            first_name='Jonathan',
            last_name='LaCour',
            email='[email protected]',
            username='jlacour',
            password='123456',
            password_confirm='123456',
            age='31'
        ))
        assert r.status_int == 200
        assert r.body == 'Success!'
        
        # test JSON submissions
        r = app.post('/json', dumps(dict(
            first_name='Jonathan',
            last_name='LaCour',
            email='[email protected]',
            username='jlacour',
            password='123456',
            password_confirm='123456',
            age='31'
        )), [('content-type', 'application/json')])
        assert r.status_int == 200
        assert r.body == 'Success!'
开发者ID:cajun-code,项目名称:pecan,代码行数:62,代码来源:test_validation.py

示例8: FunctionalTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
class FunctionalTests(unittest.TestCase):
    def setUp(self):
        from app import main
        app = main({})
        from webtest import TestApp
        self.testapp = TestApp(app)

    def test_root(self):
        res = self.testapp.get('/')
        assert res.status_int == 200

    def test_encrypt(self):
        data = {'plainText': 'test', 'key': 'b'}
        resp = self.testapp.post(
            '/encrypt',
            json.dumps(data),
            content_type='application/json; utf-8',
            xhr=True
        )
        assert resp.json['data']['originalText'] == 'test'
        assert resp.json['data']['encryptedText'] == 'uftu'

    def test_decrypt(self):
        data = {'cipherText': 'uftu', 'key': 'b'}
        resp = self.testapp.post(
            '/decrypt',
            json.dumps(data),
            content_type='application/json; utf-8',
            xhr=True
        )
        assert resp.json['data']['originalText'] == 'uftu'
        assert resp.json['data']['decryptedText'] == 'test'
开发者ID:Bedrock02,项目名称:Vigenere,代码行数:34,代码来源:test_encrypt.py

示例9: test_enforce_https_wrong

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
 def test_enforce_https_wrong(self):
     config = copy.deepcopy(SHARED_DEFAULTS)
     config["enforce_https"] = True
     application = RoutingApplication(config)
     app = TestApp(application, extra_environ={"REMOTE_ADDR": "127.0.0.1"})
     app.get("/", status=406)
     app.post("/connect", status=406)
开发者ID:AppEnlight,项目名称:channelstream,代码行数:9,代码来源:tests_integration.py

示例10: TestService

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
class TestService(TestCase):

    def setUp(self):
        self.config = testing.setUp()
        self.config.include("cornice")
        self.config.scan("cornice.tests.test_service")
        self.config.scan("cornice.tests.test_pyramidhook")
        self.app = TestApp(CatchErrors(self.config.make_wsgi_app()))

    def tearDown(self):
        testing.tearDown()

    def test_404(self):
        # a get on a resource that explicitely return a 404 should return
        # 404
        self.app.get("/service", status=404)

    def test_405(self):
        # calling a unknown verb on an existing resource should return a 405
        self.app.post("/service", status=405)

    def test_acl_support(self):
        self.app.delete('/service')

    def test_class_support(self):
        self.app.get('/fresh-air', status=400)
        resp = self.app.get('/fresh-air', headers={'X-Temperature': '50'})
        self.assertEquals(resp.body, 'fresh air')
开发者ID:CDC,项目名称:cornice,代码行数:30,代码来源:test_pyramidhook.py

示例11: test_perflog_view_dictionary_w_empty_prefix_extra_logging

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
def test_perflog_view_dictionary_w_empty_prefix_extra_logging():
    with mock.patch('notaliens.log.logger') as mock_logger:
        def view_func(request):
            return {
                'status': 0,
                'data': {'output_key': 'output_val'},
            }

        # Create a WSGI app with Pyramid and then wrap it with
        # webtest.TestApp for testing
        config = testing.setUp()
        config.add_route('view', '/view')
        config.add_view(view_func, route_name='view', renderer='json')
        config.include('notaliens.log')
        config.add_logging("", lambda req: {'foo': 'bar'})
        app = config.make_wsgi_app()
        app = TestApp(app)

        def info(log_template, template_params):
            assert 'ms=%(ms)s view=%(view)s foo=%(foo)s' == log_template
            assert template_params['foo'] == 'bar'

        mock_logger.info.side_effect = info

        app.post('/view', status=200)

        assert mock_logger.info.called
开发者ID:dobrite,项目名称:notaliens.com,代码行数:29,代码来源:test_log_tween.py

示例12: test_log_tween_include_with_comma_separator

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
def test_log_tween_include_with_comma_separator():
    # This tests automatic instrumentation of Pyramid views, using the
    # NewEvent subscriber

    with mock.patch('notaliens.log.logger') as mock_logger:
        def view_func(request):
            return {
                'status': 0,
                'data': {
                    'foo': 'bar',
                },
            }

        # Create a WSGI app with Pyramid and then wrap it with
        # webtest.TestApp for testing
        config = testing.setUp()
        config.add_route('view', '/view')
        config.add_view(view_func, route_name='view', renderer='json')
        config.include('notaliens.log')
        config.logging_separator(', ')
        app = config.make_wsgi_app()
        app = TestApp(app)

        def info(log_template, template_params):
            assert log_template == 'ms=%(ms)s, view=%(view)s'

        mock_logger.info.side_effect = info
        app.post('/view', params="", status=200)
        assert mock_logger.info.called
开发者ID:dobrite,项目名称:notaliens.com,代码行数:31,代码来源:test_log_tween.py

示例13: ViewTests

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
class ViewTests(unittest.TestCase):
    def setUp(self):
        import os
        import pkg_resources
        from pyramid.paster import bootstrap
        pkgroot = pkg_resources.get_distribution('quizr').location
        testing_ini = os.path.join(pkgroot, 'testing.ini')
        env = bootstrap(testing_ini)
        self.closer = env['closer']
        from webtest import TestApp
        self.testapp = TestApp(env['app'])

    def tearDown(self):
        import transaction
        transaction.abort()
        self.closer()

    def login(self):
        self.testapp.post(
            '/register',
            {
                'form.submitted': u'Register',
                'username': u'username',
                'password': u'secret',
                'confirm_password': u'secret',
                'email': u'[email protected]',
                'name': u'John Doe',
            },
            status=302,
        )
        self.testapp.post(
            '/login',
            {'login': 'username', 'password': 'secret'},
            status=302,
        )
开发者ID:KatyDi,项目名称:quizr-pyramid,代码行数:37,代码来源:test_functional.py

示例14: test_inject_request_id

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
def test_inject_request_id():
    with mock.patch('notaliens.log.logger') as mock_logger:
        def view_func(request):
            return {
                'status': 0,
                'data': {
                    'foo': 'bar',
                },
            }

        # Create a WSGI app with Pyramid and then wrap it with
        # webtest.TestApp for testing
        config = testing.setUp()
        config.add_route('view', '/view')
        config.add_view(view_func, route_name='view', renderer='json')
        config.include('notaliens.log')
        app = config.make_wsgi_app()
        app = TestApp(app)

        def info(log_template, template_params):
            import threading
            import re
            thread_name = threading.current_thread().name

            assert thread_name.startswith('MainThread][request=')
            assert re.search(
                r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",  # nopep8
                thread_name
            )

        mock_logger.info.side_effect = info
        app.post('/view', params="", status=200)
        assert mock_logger.info.called
开发者ID:dobrite,项目名称:notaliens.com,代码行数:35,代码来源:test_log_tween.py

示例15: test_callable_error_handler

# 需要导入模块: from webtest import TestApp [as 别名]
# 或者: from webtest.TestApp import post [as 别名]
 def test_callable_error_handler(self):
     
     class ColorSchema(Schema):
         colors = ForEach(validators.String(not_empty=True))
     
     class RootController(object):
         
         @expose()
         def errors(self, *args, **kwargs):
             return 'There was an error!'
         
         @expose(schema=ColorSchema(), 
                 error_handler=lambda: '/errors',
                 variable_decode=True)
         def index(self, **kwargs):
             return 'Success!'
     
     # test with error handler
     app = TestApp(make_app(RootController()))
     r = app.post('/', {
         'colors-0' : 'blue',
         'colors-1' : 'red'
     })
     assert r.status_int == 200
     assert r.body == 'Success!'
     
     # test with error handler
     r = app.post('/', {
         'colors-0' : 'blue',
         'colors-1' : ''
     })
     assert r.status_int == 200
     assert r.body == 'There was an error!'
开发者ID:johnmontero,项目名称:pecan,代码行数:35,代码来源:test_validation.py


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