Python aiohttp.test_utils.make_mocked_request() Examples

The following are 30 code examples of aiohttp.test_utils.make_mocked_request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module aiohttp.test_utils , or try the search function .
Example #1
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_template_not_found():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    t = "Template 'template' not found"
    assert t == ctx.value.text
    assert t == ctx.value.reason 
Example #2
Source File: test_simple_renderer.py    From aiohttp-mako with Apache License 2.0 6 votes vote down vote up
def test_render_not_initialized():

    async def func(request):
        return aiohttp_mako.render_template('template', request, {})

    app = web.Application()
    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert "Template engine is not initialized, " \
        "call aiohttp_mako.setup(app_key={}) first" \
        "".format(aiohttp_mako.APP_KEY) == ctx.value.text 
Example #3
Source File: test_simple_renderer.py    From aiohttp-mako with Apache License 2.0 6 votes vote down vote up
def test_template_not_mapping():

    @aiohttp_mako.template('tmpl.html')
    async def func(request):
        return 'data'

    app = web.Application()
    lookup = aiohttp_mako.setup(app, input_encoding='utf-8',
                                output_encoding='utf-8',
                                default_filters=['decode.utf8'])

    tplt = "<html><body><h1>${head}</h1>${text}</body></html>"
    lookup.put_string('tmpl.html', tplt)

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert "context should be mapping, not" \
           " <class 'str'>" == ctx.value.text 
Example #4
Source File: test.py    From slim with zlib License 6 votes vote down vote up
def make_mocked_view_instance(app, view_cls, method, url, params=None, post=None, *, headers=None,
                                    content_type='application/json') -> Union[BaseView, AbstractSQLView, PeeweeView]:
    if not headers:
        headers = {}

    if content_type:
        headers['Content-Type'] = content_type

    request = _make_mocked_request(method, url, headers=headers, protocol=mock.Mock(), app=app)
    _polyfill_post(request, post)

    view = view_cls(app, request)
    view._params_cache = params
    view._post_data_cache = post

    await view._prepare()
    return view 
Example #5
Source File: test_dispatcher.py    From aiohttp_apiset with Apache License 2.0 6 votes vote down vote up
def test_content_receiver():
    cr = ContentReceiver()
    l1 = len(cr)
    assert l1
    mime_json = 'application/json'
    assert mime_json in cr
    cr[None] = cr[mime_json]
    assert len(cr) == l1 + 1
    request = make_request('PUT', '/', headers={'Content-Type': mime_json})
    request._read_bytes = json.dumps(2).encode()
    assert 2 == await cr.receive(request)
    del cr[None]

    cr.freeze()
    with pytest.raises(RuntimeError):
        del cr[mime_json]
    with pytest.raises(RuntimeError):
        cr[None] = None

    request = make_request('PUT', '/', headers={'Content-Type': '1'})
    with pytest.raises(TypeError):
        await cr.receive(request)

    assert list(cr) 
Example #6
Source File: test_dispatcher.py    From aiohttp_apiset with Apache License 2.0 6 votes vote down vote up
def test_default_options(test_client):
    headers = {
        hdrs.ACCESS_CONTROL_REQUEST_HEADERS: hdrs.AUTHORIZATION}
    request = make_request('OPTIONS', '/', headers=headers)
    router = TreeUrlDispatcher()
    mi = await router.resolve(request)
    assert isinstance(mi, MatchInfoError)

    app = web.Application(router=router)
    router.set_cors(app)
    router.add_get('/', lambda request: web.Response())
    mi = await router.resolve(request)
    assert not isinstance(mi, MatchInfoError)
    client = await test_client(app)
    response = await client.options('/', headers=headers)
    assert response.status == 200
    h = response.headers
    assert h[hdrs.ACCESS_CONTROL_ALLOW_ORIGIN] == '*'
    assert h[hdrs.ACCESS_CONTROL_ALLOW_METHODS] == 'GET'
    assert h[hdrs.ACCESS_CONTROL_ALLOW_HEADERS] == hdrs.AUTHORIZATION 
Example #7
Source File: test_aiohttp_helpers.py    From aiozipkin with Apache License 2.0 6 votes vote down vote up
def test_middleware_with_not_skip_route(tracer, fake_transport):

    async def handler(request):
        return web.Response(body=b'data')

    app = web.Application()
    skip_route = app.router.add_get('/', handler)
    az.setup(app, tracer)

    match_info = Mock()
    match_info.route = skip_route

    req = make_mocked_request('GET', '/', headers={'token': 'x'}, app=app)
    req._match_info = match_info
    middleware = middleware_maker(skip_routes=[skip_route])
    await middleware(req, handler)

    assert len(fake_transport.records) == 0 
Example #8
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_not_mapping():

    @aiohttp_jinja2.template('tmpl.jinja2')
    async def func(request):
        return 123

    app = web.Application()
    aiohttp_jinja2.setup(app, loader=jinja2.DictLoader(
        {'tmpl.jinja2': 'tmpl'}))

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)
    msg = "context should be mapping, not <class 'int'>"
    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert msg == ctx.value.text 
Example #9
Source File: test_simple_renderer.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def test_render_not_initialized():

    async def func(request):
        return aiohttp_jinja2.render_template('template', request, {})

    app = web.Application()

    app.router.add_route('GET', '/', func)

    req = make_mocked_request('GET', '/', app=app)
    msg = "Template engine is not initialized, " \
          "call aiohttp_jinja2.setup(..., app_key={}" \
          ") first".format(aiohttp_jinja2.APP_KEY)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        await func(req)

    assert msg == ctx.value.text 
Example #10
Source File: test_aiohttp_helpers.py    From aiozipkin with Apache License 2.0 6 votes vote down vote up
def test_middleware_with_invalid_ip(tracer, version, address):
    app = web.Application()
    az.setup(app, tracer)

    # Fake transport
    transp = Mock()
    transp.get_extra_info.return_value = (address, '0')

    async def handler(request):
        return web.Response(body=b'data')

    req = make_mocked_request('GET', '/',
                              headers={'token': 'x'},
                              transport=transp, app=app)

    middleware = middleware_maker()
    with patch('aiozipkin.span.Span.remote_endpoint') as mocked_remote_ep:
        await middleware(req, handler)
        assert mocked_remote_ep.call_count == 0 
Example #11
Source File: test_get_session.py    From aiohttp-session with Apache License 2.0 6 votes vote down vote up
def test_get_new_session():
    req = make_mocked_request('GET', '/')
    session = Session('identity', data=None, new=False)

    class Storage(AbstractStorage):
        async def load_session(self, request):
            pass

        async def save_session(self, request, response, session):
            pass

    req[SESSION_KEY] = session
    req[STORAGE_KEY] = Storage()

    ret = await new_session(req)
    assert ret is not session 
Example #12
Source File: test_aiohttp_helpers.py    From aiozipkin with Apache License 2.0 5 votes vote down vote up
def test_middleware_with_valid_ip(tracer, version,
                                        address_in, address_out):
    if address_out is None:
        address_out = address_in

    app = web.Application()
    az.setup(app, tracer)

    # Fake transport
    transp = Mock()
    transp.get_extra_info.return_value = (address_in, '0')

    async def handler(request):
        return web.Response(body=b'data')

    req = make_mocked_request('GET', '/',
                              headers={'token': 'x'},
                              transport=transp,
                              app=app)

    middleware = middleware_maker()
    with patch('aiozipkin.span.Span.remote_endpoint') as mocked_remote_ep:
        await middleware(req, handler)

        assert mocked_remote_ep.call_count == 1
        args, kwargs = mocked_remote_ep.call_args
        assert kwargs[version] == address_out 
Example #13
Source File: test_aiohttp_helpers.py    From aiozipkin with Apache License 2.0 5 votes vote down vote up
def test_middleware_with_handler_404(tracer):
    app = web.Application()
    az.setup(app, tracer)

    async def handler(request):
        raise HTTPNotFound

    req = make_mocked_request('GET', '/', headers={'token': 'x'}, app=app)

    middleware = middleware_maker()

    with pytest.raises(HTTPException):
        await middleware(req, handler) 
Example #14
Source File: test_simple_renderer.py    From aiohttp-mako with Apache License 2.0 5 votes vote down vote up
def test_template_not_found():

    app = web.Application()
    aiohttp_mako.setup(app, input_encoding='utf-8',
                       output_encoding='utf-8',
                       default_filters=['decode.utf8'])

    req = make_mocked_request('GET', '/', app=app)

    with pytest.raises(web.HTTPInternalServerError) as ctx:
        aiohttp_mako.render_template('template', req, {})

    assert "Template 'template' not found" == ctx.value.text 
Example #15
Source File: test_sqlview.py    From slim with zlib License 5 votes vote down vote up
def test_bind():
    request = make_mocked_request('GET', '/api/test1', headers={}, protocol=mock.Mock(), app=app)
    view = ATestView(app, request)
    assert len(view.model._meta.fields) == len(view.fields)
    assert set(view.model._meta.fields.values()) == set(view.model._meta.fields.values()) 
Example #16
Source File: test_baseview.py    From slim with zlib License 5 votes vote down vote up
def test_get_captcha():
    request = make_mocked_request('GET', '/api/base_test', headers={},
                                  protocol=mock.Mock(), app=app)
    view = ATestView(app, request)
    await view._prepare()
    await view.captcha()
    assert view.ret_val == base64.b64decode(captcha)
    assert view.response.content_type == 'image/png'
    assert view.response.status == 206 
Example #17
Source File: test_view_base_view.py    From slim with zlib License 5 votes vote down vote up
def make_req(method, data=None, raw_data: bytes = None):
    headers = {'Content-Type': 'application/json'}
    request = _make_mocked_request(method, '/x', headers=headers, protocol=mock.Mock(), app=app)
    if raw_data:
        request._read_bytes = raw_data
    else:
        _polyfill_post(request, data)
    return request 
Example #18
Source File: test_secure.py    From aiohttp-remotes with MIT License 5 votes vote down vote up
def test_default_redirect():
    s = Secure()

    async def handler(request):
        pass

    req = make_mocked_request('GET', '/path',
                              headers={'Host': 'example.com'})
    with pytest.raises(web.HTTPPermanentRedirect) as ctx:
        await s.middleware(req, handler)
    assert ctx.value.location == URL('https://example.com/path') 
Example #19
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_allowed_origin_default(self):
        conf = Config()
        # lack of Origin is always allowed
        self.assertTrue(allowed(request('GET', '/'), conf))
        # deny all other Origins
        self.assertFalse(allowed(request('GET', '/', headers={'Origin': 'null'}), conf))
        self.assertFalse(allowed(request('GET', '/', headers={'Origin': 'localhost'}), conf))
        self.assertFalse(allowed(request('GET', '/', headers={'Origin': 'hackers.com'}), conf)) 
Example #20
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_allowed_origin_star(self):
        conf = Config(allowed_origin='*')
        # everything is allowed
        self.assertTrue(allowed(request('GET', '/'), conf))
        self.assertTrue(allowed(request('GET', '/', headers={'Origin': 'null'}), conf))
        self.assertTrue(allowed(request('GET', '/', headers={'Origin': 'localhost'}), conf))
        self.assertTrue(allowed(request('GET', '/', headers={'Origin': 'hackers.com'}), conf)) 
Example #21
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_allowed_origin_specified(self):
        conf = Config(allowed_origin='localhost')
        # no origin and only localhost are allowed
        self.assertTrue(allowed(request('GET', '/'), conf))
        self.assertTrue(allowed(request('GET', '/', headers={'Origin': 'localhost'}), conf))
        self.assertFalse(allowed(request('GET', '/', headers={'Origin': 'null'}), conf))
        self.assertFalse(allowed(request('GET', '/', headers={'Origin': 'hackers.com'}), conf)) 
Example #22
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_ensure_default(self):
        conf = Config()
        ensure(request('GET', '/'), conf)
        with self.assertLogs() as log:
            with self.assertRaises(HTTPForbidden):
                ensure(request('GET', '/', headers={'Origin': 'localhost'}), conf)
            self.assertIn("'localhost' are not allowed", log.output[0]) 
Example #23
Source File: test_allowed_origin.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_ensure_specific(self):
        conf = Config(allowed_origin='localhost')
        ensure(request('GET', '/', headers={'Origin': 'localhost'}), conf)
        with self.assertLogs() as log:
            with self.assertRaises(HTTPForbidden):
                ensure(request('GET', '/', headers={'Origin': 'hackers.com'}), conf)
            self.assertIn("'hackers.com' are not allowed", log.output[0])
            self.assertIn("'allowed_origin' limits requests to: 'localhost'", log.output[0]) 
Example #24
Source File: test_aiohttp_helpers.py    From aiozipkin with Apache License 2.0 5 votes vote down vote up
def test_middleware_with_default_transport(tracer, fake_transport):
    app = web.Application()
    az.setup(app, tracer)

    async def handler(request):
        return web.Response(body=b'data')

    req = make_mocked_request('GET', '/aa', headers={'token': 'x'}, app=app)
    req.match_info.route.resource.canonical = '/{pid}'

    middleware = middleware_maker()
    await middleware(req, handler)
    span = az.request_span(req)
    assert span
    assert len(fake_transport.records) == 1

    rec = fake_transport.records[0]
    assert rec.asdict()['tags'][az.HTTP_ROUTE] == '/{pid}'

    # noop span does not produce records
    headers = {'X-B3-Sampled': '0'}
    req_noop = make_mocked_request('GET', '/', headers=headers, app=app)
    await middleware(req_noop, handler)
    span = az.request_span(req_noop)
    assert span
    assert len(fake_transport.records) == 1 
Example #25
Source File: test_dispatcher.py    From aiohttp_apiset with Apache License 2.0 5 votes vote down vote up
def test_simple(dispatcher: TreeUrlDispatcher, request: web.Request):
    request = make_request('GET', '/api/1/pet/1')
    md = await dispatcher.resolve(request)
    assert md == {'id': '1'}

    request = make_request('GET', '/api/1/pets')
    md = await dispatcher.resolve(request)
    assert not md 
Example #26
Source File: test_get_session.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def test_get_stored_session():
    req = make_mocked_request('GET', '/')
    session = Session('identity', data=None, new=False)
    req[SESSION_KEY] = session

    ret = await get_session(req)
    assert session is ret 
Example #27
Source File: test_get_session.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def test_session_is_not_stored():
    req = make_mocked_request('GET', '/')

    with pytest.raises(RuntimeError):
        await get_session(req) 
Example #28
Source File: test_get_session.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def test_storage_returns_not_session_on_load_session():
    req = make_mocked_request('GET', '/')

    class Storage():
        async def load_session(self, request):
            return None

    req[STORAGE_KEY] = Storage()

    with pytest.raises(RuntimeError):
        await get_session(req) 
Example #29
Source File: test_get_session.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def test_get_new_session_no_storage():
    req = make_mocked_request('GET', '/')
    session = Session('identity', data=None, new=False)
    req[SESSION_KEY] = session

    with pytest.raises(RuntimeError):
        await new_session(req) 
Example #30
Source File: test_response_types.py    From aiohttp-session with Apache License 2.0 5 votes vote down vote up
def test_bad_response_type(aiohttp_client):

    async def bad_response(request):
        return ''

    middleware = session_middleware(SimpleCookieStorage())
    req = make_mocked_request('GET', '/')
    with pytest.raises(RuntimeError):
        await middleware(req, bad_response)