def test_delete_requests_with_form(): @Request.application def test_app(request): return Response(request.form.get('x', None)) client = Client(test_app, Response) resp = client.delete('/', data={'x': 42}) strict_eq(resp.data, b'42')
def test_authenticate_mixin(): resp = wrappers.Response() resp.www_authenticate.type = 'basic' resp.www_authenticate.realm = 'Testing' strict_eq(resp.headers['WWW-Authenticate'], u'Basic realm="Testing"') resp.www_authenticate.realm = None resp.www_authenticate.type = None assert 'WWW-Authenticate' not in resp.headers
def test_map_repr(): m = r.Map([ r.Rule(u'/wat', endpoint='enter'), r.Rule(u'/woop', endpoint='foobar') ]) rv = repr(m) strict_eq(rv, "Map([<Rule '/woop' -> foobar>, <Rule '/wat' -> enter>])")
def test_authenticate_mixin(): resp = wrappers.Response() resp.www_authenticate.type = "basic" resp.www_authenticate.realm = "Testing" strict_eq(resp.headers["WWW-Authenticate"], u'Basic realm="Testing"') resp.www_authenticate.realm = None resp.www_authenticate.type = None assert "WWW-Authenticate" not in resp.headers
def test_secure(self): response = wrappers.BaseResponse() response.set_cookie('foo', value='bar', max_age=60, expires=0, path='/blub', domain='example.org', secure=True) strict_eq(response.headers.to_wsgi_list(), [ ('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'foo=bar; Domain=example.org; Expires=Thu, ' '01-Jan-1970 00:00:00 GMT; Max-Age=60; Secure; Path=/blub') ])
def test_multi_value_submit(): c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = {"field": ["val1", "val2"]} resp = c.post("/", data=data) strict_eq(resp.status_code, 200) c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = MultiDict({"field": ["val1", "val2"]}) resp = c.post("/", data=data) strict_eq(resp.status_code, 200)
def test_stream_only_mixing(): request = wrappers.PlainRequest.from_values( data=b'foo=blub+hehe', content_type='application/x-www-form-urlencoded' ) assert list(request.files.items()) == [] assert list(request.form.items()) == [] pytest.raises(AttributeError, lambda: request.data) strict_eq(request.stream.read(), b'foo=blub+hehe')
def test_access_route(): req = wrappers.Request.from_values(headers={"X-Forwarded-For": "192.168.1.2, 192.168.1.1"}) req.environ["REMOTE_ADDR"] = "192.168.1.3" assert req.access_route == ["192.168.1.2", "192.168.1.1"] strict_eq(req.remote_addr, "192.168.1.3") req = wrappers.Request.from_values() req.environ["REMOTE_ADDR"] = "192.168.1.3" strict_eq(list(req.access_route), ["192.168.1.3"])
def test_ie7_unc_path(self): client = Client(form_data_consumer, Response) data_file = join(dirname(__file__), 'multipart', 'ie7_full_path_request.txt') data = get_contents(data_file) boundary = '---------------------------7da36d1b4a0164' response = client.post('/?object=cb_file_upload_multiple', data=data, content_type= 'multipart/form-data; boundary="%s"' % boundary, content_length=len(data)) lines = response.get_data().split(b'\n', 3) strict_eq(lines[0], repr(u'Sellersburg Town Council Meeting 02-22-2010doc.doc').encode('ascii'))
def test_url_joining(): strict_eq(urls.url_join('/foo', '/bar'), '/bar') strict_eq(urls.url_join('http://example.com/foo', '/bar'), 'http://example.com/bar') strict_eq(urls.url_join('file:///tmp/', 'test.html'), 'file:///tmp/test.html') strict_eq(urls.url_join('file:///tmp/x', 'test.html'), 'file:///tmp/test.html') strict_eq(urls.url_join('file:///tmp/x', '../../../x.html'), 'file:///x.html')
def test_post_with_file_descriptor(tmpdir): c = Client(Response(), response_wrapper=Response) f = tmpdir.join('some-file.txt') f.write('foo') with open(f.strpath, mode='rt') as data: resp = c.post('/', data=data) strict_eq(resp.status_code, 200) with open(f.strpath, mode='rb') as data: resp = c.post('/', data=data) strict_eq(resp.status_code, 200)
def test_environ_nonascii_pathinfo(): environ = create_environ(u'/лошадь') m = r.Map([ r.Rule(u'/', endpoint='index'), r.Rule(u'/лошадь', endpoint='horse') ]) a = m.bind_to_environ(environ) strict_eq(a.match(u'/'), ('index', {})) strict_eq(a.match(u'/лошадь'), ('horse', {})) pytest.raises(r.NotFound, a.match, u'/барсук')
def test_path_info_script_name_unquoting(): def test_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return [environ['PATH_INFO'] + '\n' + environ['SCRIPT_NAME']] c = Client(test_app, response_wrapper=BaseResponse) resp = c.get('/foo%40bar') strict_eq(resp.data, b'/foo@bar\n') c = Client(test_app, response_wrapper=BaseResponse) resp = c.get('/foo%40bar', 'http://localhost/bar%40baz') strict_eq(resp.data, b'/foo@bar\n/bar@baz')
def test_access_route(): req = wrappers.Request.from_values(headers={ 'X-Forwarded-For': '192.168.1.2, 192.168.1.1' }) req.environ['REMOTE_ADDR'] = '192.168.1.3' assert req.access_route == ['192.168.1.2', '192.168.1.1'] strict_eq(req.remote_addr, '192.168.1.3') req = wrappers.Request.from_values() req.environ['REMOTE_ADDR'] = '192.168.1.3' strict_eq(list(req.access_route), ['192.168.1.3'])
def test_empty_keys_are_ignored(self): strict_eq( dict(http.parse_cookie( 'first=IamTheFirst ; a=1; a=2 ;second=andMeTwo; ; ' )), { 'first': u'IamTheFirst', 'a': u'2', 'second': u'andMeTwo' } )
def test_path_info_script_name_unquoting(): def test_app(environ, start_response): start_response("200 OK", [("Content-Type", "text/plain")]) return [environ["PATH_INFO"] + "\n" + environ["SCRIPT_NAME"]] c = Client(test_app, response_wrapper=BaseResponse) resp = c.get("/foo%40bar") strict_eq(resp.data, b"/foo@bar\n") c = Client(test_app, response_wrapper=BaseResponse) resp = c.get("/foo%40bar", "http://localhost/bar%40baz") strict_eq(resp.data, b"/foo@bar\n/bar@baz")
def test_full_url_requests_with_args(): base = 'http://example.com/' @Request.application def test_app(request): return Response(request.args['x']) client = Client(test_app, Response) resp = client.get('/?x=42', base) strict_eq(resp.data, b'42') resp = client.get('http://www.example.com/?x=23', base) strict_eq(resp.data, b'23')
def test_content_type(): @Request.application def test_app(request): return Response(request.content_type) client = Client(test_app, Response) resp = client.get('/', data=b'testing', mimetype='text/css') strict_eq(resp.data, b'text/css; charset=utf-8') resp = client.get('/', data=b'testing', mimetype='application/octet-stream') strict_eq(resp.data, b'application/octet-stream')
def test_environ_builder_content_type(): builder = EnvironBuilder() assert builder.content_type is None builder.method = "POST" assert builder.content_type == "application/x-www-form-urlencoded" builder.form["foo"] = "bar" assert builder.content_type == "application/x-www-form-urlencoded" builder.files.add_file("blafasel", BytesIO(b"foo"), "test.txt") assert builder.content_type == "multipart/form-data" req = builder.get_request() strict_eq(req.form["foo"], u"bar") strict_eq(req.files["blafasel"].read(), b"foo")
def test_redirect_path_quoting(): url_map = r.Map([ r.Rule('/<category>', defaults={'page': 1}, endpoint='category'), r.Rule('/<category>/page/<int:page>', endpoint='category') ]) adapter = url_map.bind('example.com') with pytest.raises(r.RequestRedirect) as excinfo: adapter.match('/foo bar/page/1') response = excinfo.value.get_response({}) strict_eq(response.headers['location'], u'http://example.com/foo%20bar')
def test_bad_cookies(self): strict_eq( dict(http.parse_cookie( 'first=IamTheFirst ; a=1; oops ; a=2 ;second = andMeTwo;' )), { 'first': u'IamTheFirst', 'a': u'2', 'oops': u'', 'second': u'andMeTwo', } )
def test_environ_builder_stream_switch(): d = MultiDict(dict(foo=u'bar', blub=u'blah', hu=u'hum')) for use_tempfile in False, True: stream, length, boundary = stream_encode_multipart( d, use_tempfile, threshold=150) assert isinstance(stream, BytesIO) != use_tempfile form = parse_form_data({'wsgi.input': stream, 'CONTENT_LENGTH': str(length), 'CONTENT_TYPE': 'multipart/form-data; boundary="%s"' % boundary})[1] strict_eq(form, d) stream.close()
def test_full_url_requests_with_args(): base = "http://example.com/" @Request.application def test_app(request): return Response(request.args["x"]) client = Client(test_app, Response) resp = client.get("/?x=42", base) strict_eq(resp.data, b"42") resp = client.get("http://www.example.com/?x=23", base) strict_eq(resp.data, b"23")
def test_bad_newline_bad_newline_assumption(self): class ISORequest(Request): charset = 'latin1' contents = b'U2vlbmUgbORu' data = b'--foo\r\nContent-Disposition: form-data; name="test"\r\n' \ b'Content-Transfer-Encoding: base64\r\n\r\n' + \ contents + b'\r\n--foo--' req = ISORequest.from_values(input_stream=BytesIO(data), content_length=len(data), content_type='multipart/form-data; boundary=foo', method='POST') strict_eq(req.form['test'], u'Sk\xe5ne l\xe4n')
def test_proxy_fix_weird_enum(self): @fixers.ProxyFix @Request.application def app(request): return Response(request.remote_addr) environ = dict(create_environ(), HTTP_X_FORWARDED_FOR=',', REMOTE_ADDR='127.0.0.1', ) response = Response.from_app(app, environ) strict_eq(response.get_data(), b'127.0.0.1')
def test_file_no_content_type(self): data = ( b'--foo\r\n' b'Content-Disposition: form-data; name="test"; filename="test.txt"\r\n\r\n' b'file contents\r\n--foo--' ) data = Request.from_values(input_stream=BytesIO(data), content_length=len(data), content_type='multipart/form-data; boundary=foo', method='POST') assert data.files['test'].filename == 'test.txt' strict_eq(data.files['test'].read(), b'file contents')
def test_multiple_cookies(): @Request.application def test_app(request): response = Response(repr(sorted(request.cookies.items()))) response.set_cookie(u"test1", b"foo") response.set_cookie(u"test2", b"bar") return response client = Client(test_app, Response) resp = client.get("/") strict_eq(resp.data, b"[]") resp = client.get("/") strict_eq(resp.data, to_bytes(repr([("test1", u"foo"), ("test2", u"bar")]), "ascii"))
def test_multiple_cookies(): @Request.application def test_app(request): response = Response(repr(sorted(request.cookies.items()))) response.set_cookie(u'test1', b'foo') response.set_cookie(u'test2', b'bar') return response client = Client(test_app, Response) resp = client.get('/') strict_eq(resp.data, b'[]') resp = client.get('/') strict_eq(resp.data, to_bytes(repr([('test1', u'foo'), ('test2', u'bar')]), 'ascii'))
def test_multi_value_submit(): c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = { 'field': ['val1','val2'] } resp = c.post('/', data=data) strict_eq(resp.status_code, 200) c = Client(multi_value_post_app, response_wrapper=BaseResponse) data = MultiDict({ 'field': ['val1', 'val2'] }) resp = c.post('/', data=data) strict_eq(resp.status_code, 200)
def test_accept_mixin(): request = wrappers.Request( { "HTTP_ACCEPT": "text/xml,application/xml,application/xhtml+xml," "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5", "HTTP_ACCEPT_CHARSET": "ISO-8859-1,utf-8;q=0.7,*;q=0.7", "HTTP_ACCEPT_ENCODING": "gzip,deflate", "HTTP_ACCEPT_LANGUAGE": "en-us,en;q=0.5", } ) assert request.accept_mimetypes == MIMEAccept( [ ("text/xml", 1), ("image/png", 1), ("application/xml", 1), ("application/xhtml+xml", 1), ("text/html", 0.9), ("text/plain", 0.8), ("*/*", 0.5), ] ) strict_eq(request.accept_charsets, CharsetAccept([("ISO-8859-1", 1), ("utf-8", 0.7), ("*", 0.7)])) strict_eq(request.accept_encodings, Accept([("gzip", 1), ("deflate", 1)])) strict_eq(request.accept_languages, LanguageAccept([("en-us", 1), ("en", 0.5)])) request = wrappers.Request({"HTTP_ACCEPT": ""}) strict_eq(request.accept_mimetypes, MIMEAccept())
def test_streaming_parse(self): data = b'x' * (1024 * 600) class StreamMPP(formparser.MultiPartParser): def parse(self, file, boundary, content_length): i = iter( self.parse_lines(file, boundary, content_length, cap_at_buffer=False)) one = next(i) two = next(i) return self.cls(()), {'one': one, 'two': two} class StreamFDP(formparser.FormDataParser): def _sf_parse_multipart(self, stream, mimetype, content_length, options): form, files = StreamMPP( self.stream_factory, self.charset, self.errors, max_form_memory_size=self.max_form_memory_size, cls=self.cls).parse( stream, options.get('boundary').encode('ascii'), content_length) return stream, form, files parse_functions = {} parse_functions.update(formparser.FormDataParser.parse_functions) parse_functions['multipart/form-data'] = _sf_parse_multipart class StreamReq(Request): form_data_parser_class = StreamFDP req = StreamReq.from_values(data={'foo': (BytesIO(data), 'test.txt')}, method='POST') strict_eq('begin_file', req.files['one'][0]) strict_eq(('foo', 'test.txt'), req.files['one'][1][1:]) strict_eq('cont', req.files['two'][0]) strict_eq(data, req.files['two'][1])
def test_environ_builder_unicode_file_mix(): for use_tempfile in False, True: f = FileStorage(BytesIO(u'\N{SNOWMAN}'.encode('utf-8')), 'snowman.txt') d = MultiDict(dict(f=f, s=u'\N{SNOWMAN}')) stream, length, boundary = stream_encode_multipart( d, use_tempfile, threshold=150) assert isinstance(stream, BytesIO) != use_tempfile _, form, files = parse_form_data({ 'wsgi.input': stream, 'CONTENT_LENGTH': str(length), 'CONTENT_TYPE': 'multipart/form-data; boundary="%s"' % boundary }) strict_eq(form['s'], u'\N{SNOWMAN}') strict_eq(files['f'].name, 'f') strict_eq(files['f'].filename, u'snowman.txt') strict_eq(files['f'].read(), u'\N{SNOWMAN}'.encode('utf-8')) stream.close()
def test_parse_form_data_put_without_content(self): # A PUT without a Content-Type header returns empty data # Both rfc1945 and rfc2616 (1.0 and 1.1) say "Any HTTP/[1.0/1.1] message # containing an entity-body SHOULD include a Content-Type header field # defining the media type of that body." In the case where either # headers are omitted, parse_form_data should still work. env = create_environ('/foo', 'http://example.org/', method='PUT') del env['CONTENT_TYPE'] del env['CONTENT_LENGTH'] stream, form, files = formparser.parse_form_data(env) strict_eq(stream.read(), b'') strict_eq(len(form), 0) strict_eq(len(files), 0)
def test_cookies(self): strict_eq( dict(http.parse_cookie('dismiss-top=6; CP=null*; PHPSESSID=0a539d42abc001cd' 'c762809248d4beed; a=42; b="\\\";"')), { 'CP': u'null*', 'PHPSESSID': u'0a539d42abc001cdc762809248d4beed', 'a': u'42', 'dismiss-top': u'6', 'b': u'\";' } ) rv = http.dump_cookie('foo', 'bar baz blub', 360, httponly=True, sync_expires=False) assert type(rv) is str assert set(rv.split('; ')) == set(['HttpOnly', 'Max-Age=360', 'Path=/', 'foo="bar baz blub"']) strict_eq(dict(http.parse_cookie('fo234{=bar; blub=Blah')), {'fo234{': u'bar', 'blub': u'Blah'}) strict_eq(http.dump_cookie('key', 'xxx/'), 'key=xxx/; Path=/') strict_eq(http.dump_cookie('key', 'xxx='), 'key=xxx=; Path=/')
def test_accept_mixin(): request = wrappers.Request({ 'HTTP_ACCEPT': 'text/xml,application/xml,application/xhtml+xml,' 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'HTTP_ACCEPT_CHARSET': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7', 'HTTP_ACCEPT_ENCODING': 'gzip,deflate', 'HTTP_ACCEPT_LANGUAGE': 'en-us,en;q=0.5' }) assert request.accept_mimetypes == MIMEAccept([ ('text/xml', 1), ('image/png', 1), ('application/xml', 1), ('application/xhtml+xml', 1), ('text/html', 0.9), ('text/plain', 0.8), ('*/*', 0.5) ]) strict_eq(request.accept_charsets, CharsetAccept([ ('ISO-8859-1', 1), ('utf-8', 0.7), ('*', 0.7) ])) strict_eq(request.accept_encodings, Accept([ ('gzip', 1), ('deflate', 1)])) strict_eq(request.accept_languages, LanguageAccept([ ('en-us', 1), ('en', 0.5)])) request = wrappers.Request({'HTTP_ACCEPT': ''}) strict_eq(request.accept_mimetypes, MIMEAccept())
def test_run_wsgi_apps(buffered, iterable): leaked_data = [] def simple_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return ['Hello World!'] def yielding_app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) yield 'Hello ' yield 'World!' def late_start_response(environ, start_response): yield 'Hello ' yield 'World' start_response('200 OK', [('Content-Type', 'text/html')]) yield '!' def depends_on_close(environ, start_response): leaked_data.append('harhar') start_response('200 OK', [('Content-Type', 'text/html')]) class Rv(object): def __iter__(self): yield 'Hello ' yield 'World' yield '!' def close(self): assert leaked_data.pop() == 'harhar' return Rv() for app in (simple_app, yielding_app, late_start_response, depends_on_close): if iterable: app = iterable_middleware(app) app_iter, status, headers = run_wsgi_app(app, {}, buffered=buffered) strict_eq(status, '200 OK') strict_eq(list(headers), [('Content-Type', 'text/html')]) strict_eq(''.join(app_iter), 'Hello World!') if hasattr(app_iter, 'close'): app_iter.close() assert not leaked_data
def test_correct_open_invocation_on_redirect(): class MyClient(Client): counter = 0 def open(self, *args, **kwargs): self.counter += 1 env = kwargs.setdefault('environ_overrides', {}) env['werkzeug._foo'] = self.counter return Client.open(self, *args, **kwargs) @Request.application def test_app(request): return Response(str(request.environ['werkzeug._foo'])) c = MyClient(test_app, response_wrapper=Response) strict_eq(c.get('/').data, b'1') strict_eq(c.get('/').data, b'2') strict_eq(c.get('/').data, b'3')
def test_sentinel_cases(self): def producer_dummy_flush(out): out.flush() iterable = IterIO(producer_dummy_flush) strict_eq(next(iterable), '') def producer_empty(out): pass iterable = IterIO(producer_empty) pytest.raises(StopIteration, next, iterable) iterable = IterIO(producer_dummy_flush, b'') strict_eq(next(iterable), b'') iterable = IterIO(producer_dummy_flush, u'') strict_eq(next(iterable), u'')
def test_lazy_start_response_empty_response_app(buffered, iterable): @implements_iterator class app: def __init__(self, environ, start_response): self.start_response = start_response def __iter__(self): return self def __next__(self): self.start_response('200 OK', [('Content-Type', 'text/html')]) raise StopIteration if iterable: app = iterable_middleware(app) app_iter, status, headers = run_wsgi_app(app, {}, buffered=buffered) strict_eq(status, '200 OK') strict_eq(list(headers), [('Content-Type', 'text/html')]) strict_eq(''.join(app_iter), '')
def test_modified_url_encoding(): class ModifiedRequest(wrappers.Request): url_charset = 'euc-kr' req = ModifiedRequest.from_values(u'/?foo=정상처리'.encode('euc-kr')) strict_eq(req.args['foo'], u'정상처리')
def test_base_request(): client = Client(request_demo_app, RequestTestResponse) # get requests response = client.get('/?foo=bar&foo=hehe') strict_eq(response['args'], MultiDict([('foo', u'bar'), ('foo', u'hehe')])) strict_eq(response['args_as_list'], [('foo', [u'bar', u'hehe'])]) strict_eq(response['form'], MultiDict()) strict_eq(response['form_as_list'], []) strict_eq(response['data'], b'') 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') strict_eq(response['args'], MultiDict([('blub', u'blah')])) strict_eq(response['args_as_list'], [('blub', [u'blah'])]) strict_eq(response['form'], MultiDict([('foo', u'blub hehe'), ('blah', u'42')])) strict_eq(response['data'], b'') # currently we do not guarantee that the values are ordered correctly # for post data. # strict_eq(response['form_as_list'], [('foo', ['blub hehe']), ('blah', ['42'])]) assert_environ(response['environ'], 'POST') # patch requests with form data response = client.patch('/?blub=blah', data='foo=blub+hehe&blah=42', content_type='application/x-www-form-urlencoded') strict_eq(response['args'], MultiDict([('blub', u'blah')])) strict_eq(response['args_as_list'], [('blub', [u'blah'])]) strict_eq(response['form'], MultiDict([('foo', u'blub hehe'), ('blah', u'42')])) strict_eq(response['data'], b'') assert_environ(response['environ'], 'PATCH') # post requests with json data json = b'{"foo": "bar", "blub": "blah"}' response = client.post('/?a=b', data=json, content_type='application/json') strict_eq(response['data'], json) strict_eq(response['args'], MultiDict([('a', u'b')])) strict_eq(response['form'], MultiDict())
def assert_environ(environ, method): strict_eq(environ['REQUEST_METHOD'], method) strict_eq(environ['PATH_INFO'], '/') strict_eq(environ['SCRIPT_NAME'], '') strict_eq(environ['SERVER_NAME'], 'localhost') strict_eq(environ['wsgi.version'], (1, 0)) strict_eq(environ['wsgi.url_scheme'], 'http')
def test_user_agent_mixin(): user_agents = [ ('Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.11) ' 'Gecko/20071127 Firefox/2.0.0.11', 'firefox', 'macos', '2.0.0.11', 'en-US'), ('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; de-DE) Opera 8.54', 'opera', 'windows', '8.54', 'de-DE'), ('Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420 ' '(KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3', 'safari', 'iphone', '3.0', 'en'), ('Bot Googlebot/2.1 ( http://www.googlebot.com/bot.html)', 'google', None, '2.1', None), ('Mozilla/5.0 (X11; CrOS armv7l 3701.81.0) AppleWebKit/537.31 ' '(KHTML, like Gecko) Chrome/26.0.1410.57 Safari/537.31', 'chrome', 'chromeos', '26.0.1410.57', None), ('Mozilla/5.0 (Windows NT 6.3; Trident/7.0; .NET4.0E; rv:11.0) like Gecko', 'msie', 'windows', '11.0', None), ('Mozilla/5.0 (SymbianOS/9.3; Series60/3.2 NokiaE5-00/101.003; ' 'Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/533.4 (KHTML, like Gecko) ' 'NokiaBrowser/7.3.1.35 Mobile Safari/533.4 3gpp-gba', 'safari', 'symbian', '533.4', None) ] for ua, browser, platform, version, lang in user_agents: request = wrappers.Request({'HTTP_USER_AGENT': ua}) strict_eq(request.user_agent.browser, browser) strict_eq(request.user_agent.platform, platform) strict_eq(request.user_agent.version, version) strict_eq(request.user_agent.language, lang) assert bool(request.user_agent) strict_eq(request.user_agent.to_header(), ua) strict_eq(str(request.user_agent), ua) request = wrappers.Request({'HTTP_USER_AGENT': 'foo'}) assert not request.user_agent
def test_response_status_codes(): response = wrappers.BaseResponse() response.status_code = 404 strict_eq(response.status, '404 NOT FOUND') response.status = '200 OK' strict_eq(response.status_code, 200) response.status = '999 WTF' strict_eq(response.status_code, 999) response.status_code = 588 strict_eq(response.status_code, 588) strict_eq(response.status, '588 UNKNOWN') response.status = 'wtf' strict_eq(response.status_code, 0) strict_eq(response.status, '0 wtf')
def test_bytes_unquoting(): strict_eq( urls.url_unquote(urls.url_quote(u'#%="\xf6', charset='latin1'), charset=None), b'#%="\xf6')
def test_url_attributes_bytes(): rv = urls.url_parse(b'http://foo%3a:bar%3a@[::1]:80/123?x=y#frag') strict_eq(rv.scheme, b'http') strict_eq(rv.auth, b'foo%3a:bar%3a') strict_eq(rv.username, u'foo:') strict_eq(rv.password, u'bar:') strict_eq(rv.raw_username, b'foo%3a') strict_eq(rv.raw_password, b'bar%3a') strict_eq(rv.host, b'::1') assert rv.port == 80 strict_eq(rv.path, b'/123') strict_eq(rv.query, b'x=y') strict_eq(rv.fragment, b'frag')
def test_partial_unencoded_decode(): ref = u'foo=정상처리'.encode('euc-kr') x = urls.url_decode(ref, charset='euc-kr') strict_eq(x['foo'], u'정상처리')
def test_limiting(self): data = b'foo=Hello+World&bar=baz' req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='application/x-www-form-urlencoded', method='POST') req.max_content_length = 400 strict_eq(req.form['foo'], u'Hello World') req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='application/x-www-form-urlencoded', method='POST') req.max_form_memory_size = 7 pytest.raises(RequestEntityTooLarge, lambda: req.form['foo']) req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='application/x-www-form-urlencoded', method='POST') req.max_form_memory_size = 400 strict_eq(req.form['foo'], u'Hello World') data = (b'--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\n' b'Hello World\r\n' b'--foo\r\nContent-Disposition: form-field; name=bar\r\n\r\n' b'bar=baz\r\n--foo--') req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='multipart/form-data; boundary=foo', method='POST') req.max_content_length = 4 pytest.raises(RequestEntityTooLarge, lambda: req.form['foo']) req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='multipart/form-data; boundary=foo', method='POST') req.max_content_length = 400 strict_eq(req.form['foo'], u'Hello World') req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='multipart/form-data; boundary=foo', method='POST') req.max_form_memory_size = 7 pytest.raises(RequestEntityTooLarge, lambda: req.form['foo']) req = Request.from_values( input_stream=BytesIO(data), content_length=len(data), content_type='multipart/form-data; boundary=foo', method='POST') req.max_form_memory_size = 400 strict_eq(req.form['foo'], u'Hello World')
def test_replace(): url = urls.url_parse('http://de.wikipedia.org/wiki/Troll') strict_eq(url.replace(query='foo=bar'), urls.url_parse('http://de.wikipedia.org/wiki/Troll?foo=bar')) strict_eq(url.replace(scheme='https'), urls.url_parse('https://de.wikipedia.org/wiki/Troll'))
def test_href_past_root(): base_href = urls.Href('http://www.blagga.com/1/2/3') strict_eq(base_href('../foo'), 'http://www.blagga.com/1/2/foo') strict_eq(base_href('../../foo'), 'http://www.blagga.com/1/foo') strict_eq(base_href('../../../foo'), 'http://www.blagga.com/foo') strict_eq(base_href('../../../../foo'), 'http://www.blagga.com/foo') strict_eq(base_href('../../../../../foo'), 'http://www.blagga.com/foo') strict_eq(base_href('../../../../../../foo'), 'http://www.blagga.com/foo')
def test_url_decoding(): x = urls.url_decode(b'foo=42&bar=23&uni=H%C3%A4nsel') strict_eq(x['foo'], u'42') strict_eq(x['bar'], u'23') strict_eq(x['uni'], u'Hänsel') x = urls.url_decode(b'foo=42;bar=23;uni=H%C3%A4nsel', separator=b';') strict_eq(x['foo'], u'42') strict_eq(x['bar'], u'23') strict_eq(x['uni'], u'Hänsel') x = urls.url_decode(b'%C3%9Ch=H%C3%A4nsel', decode_keys=True) strict_eq(x[u'Üh'], u'Hänsel')
def test_cookie_domain_resolving(self): val = http.dump_cookie('foo', 'bar', domain=u'\N{SNOWMAN}.com') strict_eq(val, 'foo=bar; Domain=xn--n3h.com; Path=/')
def test_url_attributes(): rv = urls.url_parse('http://foo%3a:bar%3a@[::1]:80/123?x=y#frag') strict_eq(rv.scheme, 'http') strict_eq(rv.auth, 'foo%3a:bar%3a') strict_eq(rv.username, u'foo:') strict_eq(rv.password, u'bar:') strict_eq(rv.raw_username, 'foo%3a') strict_eq(rv.raw_password, 'bar%3a') strict_eq(rv.host, '::1') assert rv.port == 80 strict_eq(rv.path, '/123') strict_eq(rv.query, 'x=y') strict_eq(rv.fragment, 'frag') rv = urls.url_parse(u'http://\N{SNOWMAN}.com/') strict_eq(rv.host, u'\N{SNOWMAN}.com') strict_eq(rv.ascii_host, 'xn--n3h.com')
def test_base_response(): # unicode response = wrappers.BaseResponse(u'öäü') strict_eq(response.get_data(), u'öäü'.encode('utf-8')) # writing response = wrappers.Response('foo') response.stream.write('bar') strict_eq(response.get_data(), b'foobar') # set cookie response = wrappers.BaseResponse() response.set_cookie('foo', 'bar', 60, 0, '/blub', 'example.org') strict_eq(response.headers.to_wsgi_list(), [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'foo=bar; Domain=example.org; Expires=Thu, ' '01-Jan-1970 00:00:00 GMT; Max-Age=60; Path=/blub')]) # delete cookie response = wrappers.BaseResponse() response.delete_cookie('foo') strict_eq( response.headers.to_wsgi_list(), [('Content-Type', 'text/plain; charset=utf-8'), ('Set-Cookie', 'foo=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/')]) # close call forwarding closed = [] @implements_iterator class Iterable(object): def __next__(self): raise StopIteration() def __iter__(self): return self def close(self): closed.append(True) response = wrappers.BaseResponse(Iterable()) response.call_on_close(lambda: closed.append(True)) app_iter, status, headers = run_wsgi_app(response, create_environ(), buffered=True) strict_eq(status, '200 OK') strict_eq(''.join(app_iter), '') strict_eq(len(closed), 2) # with statement del closed[:] response = wrappers.BaseResponse(Iterable()) with response: pass assert len(closed) == 1
def test_query_string_is_bytes(): req = wrappers.Request.from_values(u'/?foo=%2f') strict_eq(req.query_string, b'foo=%2f')
def test_quoting(): strict_eq(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC') strict_eq(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6') strict_eq(urls.url_quote_plus('foo bar'), 'foo+bar') strict_eq(urls.url_unquote_plus('foo+bar'), u'foo bar') strict_eq(urls.url_quote_plus('foo+bar'), 'foo%2Bbar') strict_eq(urls.url_unquote_plus('foo%2Bbar'), u'foo+bar') strict_eq(urls.url_encode({b'a': None, b'b': b'foo bar'}), 'b=foo+bar') strict_eq(urls.url_encode({u'a': None, u'b': u'foo bar'}), 'b=foo+bar') strict_eq( urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'), 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)') strict_eq(urls.url_quote_plus(42), '42') strict_eq(urls.url_quote(b'\xff'), '%FF')
def test_url_request_descriptors(): req = wrappers.Request.from_values('/bar?foo=baz', 'http://example.com/test') strict_eq(req.path, u'/bar') strict_eq(req.full_path, u'/bar?foo=baz') strict_eq(req.script_root, u'/test') strict_eq(req.url, u'http://example.com/test/bar?foo=baz') strict_eq(req.base_url, u'http://example.com/test/bar') strict_eq(req.url_root, u'http://example.com/test/') strict_eq(req.host_url, u'http://example.com/') strict_eq(req.host, 'example.com') strict_eq(req.scheme, 'http') req = wrappers.Request.from_values('/bar?foo=baz', 'https://example.com/test') strict_eq(req.scheme, 'https')
def test_url_request_descriptors_hosts(): req = wrappers.Request.from_values('/bar?foo=baz', 'http://example.com/test') req.trusted_hosts = ['example.com'] strict_eq(req.path, u'/bar') strict_eq(req.full_path, u'/bar?foo=baz') strict_eq(req.script_root, u'/test') strict_eq(req.url, u'http://example.com/test/bar?foo=baz') strict_eq(req.base_url, u'http://example.com/test/bar') strict_eq(req.url_root, u'http://example.com/test/') strict_eq(req.host_url, u'http://example.com/') strict_eq(req.host, 'example.com') strict_eq(req.scheme, 'http') req = wrappers.Request.from_values('/bar?foo=baz', 'https://example.com/test') strict_eq(req.scheme, 'https') req = wrappers.Request.from_values('/bar?foo=baz', 'http://example.com/test') req.trusted_hosts = ['example.org'] pytest.raises(SecurityError, lambda: req.url) pytest.raises(SecurityError, lambda: req.base_url) pytest.raises(SecurityError, lambda: req.url_root) pytest.raises(SecurityError, lambda: req.host_url) pytest.raises(SecurityError, lambda: req.host)
def test_url_unquote_plus_unicode(): # was broken in 0.6 strict_eq(urls.url_unquote_plus(u'\x6d'), u'\x6d') assert type(urls.url_unquote_plus(u'\x6d')) is text_type
def test_quoting_of_local_urls(): rv = urls.iri_to_uri(u'/foo\x8f') strict_eq(rv, '/foo%C2%8F') assert type(rv) is str