• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python test.Client类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中werkzeug.test.Client的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: test_smart_static_css

def test_smart_static_css():
    """
    Contents of CSS files served by SmartStatic should have url(), @import and
    other internal links updated to include hashes.
    """
    routes = (
        ('/<path:filepath>', 'test', SmartStatic(directory=static_folder)),
    )

    css_path = os.path.join(static_folder, 'css', 'test.css')
    with open(css_path, 'rb') as f:
        css_hash = get_hash(f)

    app = spa.App(routes)
    c = Client(app, spa.Response)
    resp = c.get('/css/test.%s.css' % css_hash)
    assert resp.status_code == 200

    # css-relative url
    assert b'url("blah.c9a8f43433e4.css")' in resp.data

    # absolute path url
    assert b'url("/css/blah2.54197c389773.css")' in resp.data

    # url with IE compatibility hack
    assert b'url("/font/lato-regular-webfont.97add36de4b3.eot?#iefix")' in resp.data

    # url with fragment but no query string
    assert b'url("/font/lato-regular-webfont.01ee9ec2a839.svg#svgFontName")' in resp.data

    # css-relative url with query string
    assert b'url("../img/background.fb32250cea28.png?foo=bar")' in resp.data
开发者ID:btubbs,项目名称:spa,代码行数:32,代码来源:test_static.py


示例2: test_append_slash_redirect

def test_append_slash_redirect():
    def app(env, sr):
        return utils.append_slash_redirect(env)(env, sr)
    client = Client(app, BaseResponse)
    response = client.get('foo', base_url='http://example.org/app')
    assert response.status_code == 301
    assert response.headers['Location'] == 'http://example.org/app/foo/'
开发者ID:nzavagli,项目名称:UnrealPy,代码行数:7,代码来源:test_utils.py


示例3: test_responder

 def test_responder(self):
     def foo(environ, start_response):
         return BaseResponse('Test')
     client = Client(wsgi.responder(foo), BaseResponse)
     response = client.get('/')
     assert response.status_code == 200
     assert response.data == 'Test'
开发者ID:y2bishop2y,项目名称:microengine,代码行数:7,代码来源:wsgi.py


示例4: test_simple

    def test_simple(self):

        app = CORSMiddleware(hello_world,
                             origin=origin([
                                 "https://example.tld/",
                                 "http://example.tld/",
                             ]),
                             allowed=("Foo", "Bar"), exposed=("Spam", ))

        client = Client(app, Response)

        rv = client.get("/", headers={"Origin": "https://example.tld"})

        self.assertEqual(
            rv.headers["Access-Control-Allow-Origin"], "https://example.tld")
        self.assertEqual(
            rv.headers["Access-Control-Allow-Credentials"], "true")
        self.assertEqual(
            rv.headers["Access-Control-Allow-Methods"], "HEAD, GET, POST, PUT, DELETE")
        self.assertEqual(
            rv.headers["Access-Control-Allow-Headers"], "Foo, Bar")
        self.assertEqual(rv.headers["Access-Control-Expose-Headers"], "Spam")

        a = client.get("/", headers={"Origin": "http://example.tld"})
        self.assertEqual(
            a.headers["Access-Control-Allow-Origin"], "http://example.tld")

        b = client.get("/", headers={"Origin": "http://example.tld"})
        self.assertEqual(
            b.headers["Access-Control-Allow-Origin"], "http://example.tld")

        c = client.get("/", headers={"Origin": "http://foo.other"})
        self.assertEqual(
            c.headers["Access-Control-Allow-Origin"], "https://example.tld")
开发者ID:panta82,项目名称:isso,代码行数:34,代码来源:test_cors.py


示例5: test_json_render

def test_json_render(render_json=None):
    if render_json is None:
        render_json = JSONRender(dev_mode=True)
    app = Application([('/', hello_world_ctx, render_json),
                       ('/<name>/', hello_world_ctx, render_json),
                       ('/beta/<name>/', complex_context, render_json)])

    yield ok_, callable(app.routes[0]._execute)
    yield ok_, callable(app.routes[0]._render)
    c = Client(app, BaseResponse)

    resp = c.get('/')
    yield eq_, resp.status_code, 200
    resp_data = json.loads(resp.data)
    yield eq_, resp_data['name'], 'world'

    resp = c.get('/Kurt/')
    yield eq_, resp.status_code, 200
    resp_data = json.loads(resp.data)
    yield eq_, resp_data['name'], 'Kurt'

    resp = c.get('/beta/Rajkumar/')
    yield eq_, resp.status_code, 200
    resp_data = json.loads(resp.data)
    yield eq_, resp_data['name'], 'Rajkumar'
    yield ok_, resp_data['date']
    yield ok_, len(resp_data) > 4
开发者ID:Kewpie007,项目名称:clastic,代码行数:27,代码来源:test_render.py


示例6: test_post_auth

    def test_post_auth(self):
        """
        Test a read only api.
        GET should be ok, POST and PUT should not
        """
        from rest_api_framework.pagination import Pagination

        ressources = [{"id": "azerty"}]
        authentication = ApiKeyAuthentication(
            PythonListDataStore(ressources,
                                ApiModel)
            )

        class ApiAppAuth(ApiApp):
            controller = {
                "list_verbs": ["GET"],
                "unique_verbs": ["GET"],
                "options": {"pagination": Pagination(20),
                            "authentication": authentication,
                            "authorization": ApiKeyAuthorization
                            }
                }
        client = Client(
            WSGIDispatcher([ApiAppAuth]),
            response_wrapper=BaseResponse)

        resp = client.get("/address/1/?apikey=azerty")
        self.assertEqual(resp.status_code, 200)
        resp = client.post("/address/?apikey=azerty",
                           data=json.dumps({'name': 'bob', 'age': 34}))
        self.assertEqual(resp.status_code, 405)
开发者ID:peopledoc,项目名称:python-rest-api-framework,代码行数:31,代码来源:test_authentication.py


示例7: test_responder

 def test_responder(self):
     def foo(environ, start_response):
         return BaseResponse(b'Test')
     client = Client(wsgi.responder(foo), BaseResponse)
     response = client.get('/')
     self.assert_equal(response.status_code, 200)
     self.assert_equal(response.data, b'Test')
开发者ID:TheWaWaR,项目名称:werkzeug,代码行数:7,代码来源:wsgi.py


示例8: test_resent_cookie

def test_resent_cookie():
    """Test that the client resends cookies on subsequent requests
    """
    c = Client(cookie_app)
    c.open()
    appiter, code, headers = c.open()
    assert ''.join(appiter) == 'test=test'
开发者ID:AndryulE,项目名称:kitsune,代码行数:7,代码来源:test_test.py


示例9: test_base_pagination_offset

 def test_base_pagination_offset(self):
     client = Client(WSGIDispatcher([ApiApp]),
                     response_wrapper=BaseResponse)
     resp = client.get("/address/?offset=2")
     self.assertEqual(
         json.loads(resp.data)["object_list"][0]['ressource_uri'],
         "/address/2/")
开发者ID:peopledoc,项目名称:python-rest-api-framework,代码行数:7,代码来源:test_pagination.py


示例10: test_get_list

    def test_get_list(self):
        client = Client(WSGIDispatcher([ApiApp]),
                        response_wrapper=BaseResponse)
        resp = client.get("/address/")

        self.assertEqual(resp.status_code, 200)
        self.assertIsInstance(json.loads(resp.data)["object_list"], list)
开发者ID:bdh1011,项目名称:python-rest-api-framework,代码行数:7,代码来源:test_views.py


示例11: runtest

    def runtest(self):
        fs = self._prepareMockFs()

        url = self.spec.get('url')
        if url is None:
            raise Exception("Missing URL in test spec.")

        expected_status = self.spec.get('status', 200)
        expected_headers = self.spec.get('headers')
        expected_output = self.spec.get('out')
        expected_contains = self.spec.get('out_contains')

        from werkzeug.test import Client
        from werkzeug.wrappers import BaseResponse
        from piecrust.serving.server import Server
        with mock_fs_scope(fs):
            server = Server(fs.path('/kitchen'))
            test_app = self._TestApp(server)
            client = Client(test_app, BaseResponse)
            resp = client.get(url)
            assert expected_status == resp.status_code

            if expected_headers:
                for k, v in expected_headers.items():
                    assert v == resp.headers.get(k)

            actual = resp.data.decode('utf8').rstrip()
            if expected_output:
                assert expected_output.rstrip() == actual

            if expected_contains:
                assert expected_contains.rstrip() in actual
开发者ID:sinistersnare,项目名称:PieCrust2,代码行数:32,代码来源:conftest.py


示例12: test_check_login

def test_check_login():
    from glashammer.bundles.auth import setup_auth, login
    from glashammer.bundles.sessions import get_session

    called = []

    def check(u, p):
        called.append((u, p))
        return u == p

    def view(req):
        login('a')
        return Response()

    def setup_app(app):
        app.add_setup(setup_auth)
        app.connect_event('password-check', check)
        app.add_url('/', 'a/b', view=view)

    app = make_app(setup_app, 'test_output')
    c = Client(app)
    c.open()

    session = get_session()
    token_key = get_app().conf['auth/token_key']
    assert token_key in session
    assert session[token_key] == 'a'
开发者ID:passy,项目名称:glashammer-rdrei,代码行数:27,代码来源:test_all.py


示例13: TestJsonRestService

class TestJsonRestService(object):

    def setup(self):
        def _setup_json(app):
            app.add_url('/', '', view=_Service())

        app = make_app(_setup_json, 'test_output')

        self.client = Client(app)

    def test_get(self):
        ai, st, h = self.client.open(method='GET')
        s = list(ai)[0]
        assert 'GET' in s

    def test_post(self):
        ai, st, h = self.client.open(method='POST')
        s = list(ai)[0]
        assert 'POST' in s

    def test_put(self):
        ai, st, h = self.client.open(method='PUT')
        s = list(ai)[0]
        assert 'PUT' in s

    def test_delete(self):
        ai, st, h = self.client.open(method='DELETE')
        s = list(ai)[0]
        assert 'DELETE' in s
开发者ID:passy,项目名称:glashammer-rdrei,代码行数:29,代码来源:test_all.py


示例14: TestJsonRest

class TestJsonRest(object):

    def setup(self):
        app = load_app_from_path('examples/jsonrest/run.py')
        self.c = Client(app)

    def test_index(self):
        iter, status, headers = self.c.open()
        s = ''.join(iter)
        assert  """
    <a href="#" id="get_link">GET</a>
    <a href="#" id="post_link">POST</a>
    <a href="#" id="put_link">PUT</a>
    <a href="#" id="delete_link">DELETE</a>
""".strip('\n') in s

    def test_get(self):
        iter, status, headers = self.c.open('/svc')
        d = loads(''.join(iter))
        assert d['type'] == 'GET'

    def test_put(self):
        iter, status, headers = self.c.put('/svc')
        d = loads(''.join(iter))
        assert d['type'] == 'PUT'

    def test_delete(self):
        iter, status, headers = self.c.delete('/svc')
        d = loads(''.join(iter))
        assert d['type'] == 'DELETE'

    def test_post(self):
        iter, status, headers = self.c.post('/svc')
        d = loads(''.join(iter))
        assert d['type'] == 'POST'
开发者ID:passy,项目名称:glashammer-rdrei,代码行数:35,代码来源:test_all.py


示例15: test_mount_parent_link

def test_mount_parent_link():
    app = morepath.App('app')
    class Model(object):
        def __init__(self, id):
            self.id = id

    mounted = morepath.App('mounted')

    class MountedRoot(object):
        def __init__(self, mount_id):
            self.mount_id = mount_id

    def root_default(request, model):
        return request.link(Model('one'), mounted=request.mounted().parent())

    def get_context(id):
        return {
            'mount_id': id
            }

    c = setup()
    c.configurable(app)
    c.configurable(mounted)
    c.action(app.model(path='models/{id}',
                       variables=lambda m: {'id': m.id}),
             Model)
    c.action(app.mount(path='{id}', app=mounted), get_context)
    c.action(mounted.root(), MountedRoot)
    c.action(mounted.view(model=MountedRoot), root_default)
    c.commit()

    c = Client(app, Response)

    response = c.get('/foo')
    assert response.data == 'models/one'
开发者ID:webmaven,项目名称:morepath,代码行数:35,代码来源:test_directive.py


示例16: test_base_request

def test_base_request():
    """Base request behavior"""
    client = Client(request_demo_app, RequestTestResponse)

    # get requests
    response = client.get('/?foo=bar&foo=hehe')
    assert response['args'] == MultiDict([('foo', 'bar'), ('foo', 'hehe')])
    assert response['args_as_list'] == [('foo', ['bar', 'hehe'])]
    assert response['form'] == MultiDict()
    assert response['form_as_list'] == []
    assert response['data'] == ''
    assert_environ(response['environ'], 'GET')

    # post requests with form data
    response = client.post('/?blub=blah', data='foo=blub+hehe&blah=42',
                           content_type='application/x-www-form-urlencoded')
    assert response['args'] == MultiDict([('blub', 'blah')])
    assert response['args_as_list'] == [('blub', ['blah'])]
    assert response['form'] == MultiDict([('foo', 'blub hehe'), ('blah', '42')])
    assert response['data'] == ''
    # currently we do not guarantee that the values are ordered correctly
    # for post data.
    ## assert response['form_as_list'] == [('foo', ['blub hehe']), ('blah', ['42'])]
    assert_environ(response['environ'], 'POST')

    # post requests with json data
    json = '{"foo": "bar", "blub": "blah"}'
    response = client.post('/?a=b', data=json, content_type='application/json')
    assert response['data'] == json
    assert response['args'] == MultiDict([('a', 'b')])
    assert response['form'] == MultiDict()
开发者ID:MostAwesomeDude,项目名称:werkzeug,代码行数:31,代码来源:test_wrappers.py


示例17: test_broken_error_render

def test_broken_error_render():
    rt = Route('/<number:int>', odd_endpoint, render_basic)
    app = Application([rt], render_error=render_error_broken)
    cl = Client(app, BaseResponse)
    err_resp = cl.get('/2')
    yield eq_, err_resp.status_code, 500
    yield ok_, 'not in my house' in err_resp.data
开发者ID:canassa,项目名称:clastic,代码行数:7,代码来源:test_render_error.py


示例18: WebsiteTest

class WebsiteTest(TestCase):
    SQLALCHEMY_DATABASE_URI = 'sqlite://'
    TESTING = True

    def create_app(self):
        return application

    def setUp(self):
        db.create_all()

        self.client = Client(application, BaseResponse)

    def tearDown(self):
        db.session.remove()
        db.drop_all()

    def test_home_page_status_code(self):
        response = self.client.get('/')

        self.assertEqual(response.status_code, 200)

    def test_manage_page_status_code(self):
        response = self.client.get('/manage')

        self.assertEqual(response.status_code, 200)
开发者ID:jan-rudolf,项目名称:pywps,代码行数:25,代码来源:test_website.py


示例19: test_auth_unique_uri

    def test_auth_unique_uri(self):
        from rest_api_framework.pagination import Pagination

        ressources = [{"id": "azerty"}]
        authentication = ApiKeyAuthentication(
            PythonListDataStore(ressources,
                                ApiModel)
            )

        class ApiAppAuth(ApiApp):
            controller = {
                "list_verbs": ["GET", "POST"],
                "unique_verbs": ["GET", "PUT", "DElETE"],
                "options": {"pagination": Pagination(20),
                            "authentication": authentication,
                            "authorization": ApiKeyAuthorization
                            }
                }

        client = Client(
            WSGIDispatcher([ApiAppAuth]),
            response_wrapper=BaseResponse)

        resp = client.get("/address/1/?apikey=azerty")
        self.assertEqual(resp.status_code, 200)
        resp = client.get("/address/1/?apikey=querty")
        self.assertEqual(resp.status_code, 401)
开发者ID:peopledoc,项目名称:python-rest-api-framework,代码行数:27,代码来源:test_authentication.py


示例20: test_link_to_unknown_model

def test_link_to_unknown_model():
    app = morepath.App()

    class Root(object):
        def __init__(self):
            self.value = 'ROOT'

    class Model(object):
        def __init__(self, id):
            self.id = id

    def root_link(request, model):
        try:
            return request.link(Model('foo'))
        except LinkError:
            return "Link error"

    c = setup()
    c.configurable(app)
    c.action(app.root(), Root)
    c.action(app.view(model=Root), root_link)
    c.commit()

    c = Client(app, Response)

    response = c.get('/')
    assert response.data == 'Link error'
开发者ID:webmaven,项目名称:morepath,代码行数:27,代码来源:test_directive.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python test.EnvironBuilder类代码示例发布时间:2022-05-26
下一篇:
Python test.run_wsgi_app函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap