def test_shared_data_middleware(tmpdir): def null_application(environ, start_response): start_response("404 NOT FOUND", [("Content-Type", "text/plain")]) yield b"NOT FOUND" test_dir = str(tmpdir) with open(path.join(test_dir, to_native(u"äöü", "utf-8")), "w") as test_file: test_file.write(u"FOUND") app = wsgi.SharedDataMiddleware( null_application, { "/": path.join(path.dirname(__file__), "res"), "/sources": path.join(path.dirname(__file__), "res"), "/pkg": ("werkzeug.debug", "shared"), "/foo": test_dir, }, ) for p in "/test.txt", "/sources/test.txt", "/foo/äöü": app_iter, status, headers = run_wsgi_app(app, create_environ(p)) assert status == "200 OK" with closing(app_iter) as app_iter: data = b"".join(app_iter).strip() assert data == b"FOUND" app_iter, status, headers = run_wsgi_app(app, create_environ("/pkg/debugger.js")) with closing(app_iter) as app_iter: contents = b"".join(app_iter) assert b"$(function() {" in contents app_iter, status, headers = run_wsgi_app(app, create_environ("/missing")) assert status == "404 NOT FOUND" assert b"".join(app_iter).strip() == b"NOT FOUND"
def test_dispatchermiddleware(): def null_application(environ, start_response): start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) yield b'NOT FOUND' def dummy_application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) yield to_bytes(environ['SCRIPT_NAME']) app = wsgi.DispatcherMiddleware(null_application, { '/test1': dummy_application, '/test2/very': dummy_application, }) tests = { '/test1': ('/test1', '/test1/asfd', '/test1/very'), '/test2/very': ('/test2/very', '/test2/very/long/path/after/script/name') } for name, urls in tests.items(): for p in urls: environ = create_environ(p) app_iter, status, headers = run_wsgi_app(app, environ) assert status == '200 OK' assert b''.join(app_iter).strip() == to_bytes(name) app_iter, status, headers = run_wsgi_app( app, create_environ('/missing')) assert status == '404 NOT FOUND' assert b''.join(app_iter).strip() == b'NOT FOUND'
def test_shared_data_middleware(tmpdir): def null_application(environ, start_response): start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) yield b'NOT FOUND' test_dir = str(tmpdir) with open(path.join(test_dir, to_native(u'äöü', 'utf-8')), 'w') as test_file: test_file.write(u'FOUND') app = wsgi.SharedDataMiddleware(null_application, { '/': path.join(path.dirname(__file__), 'res'), '/sources': path.join(path.dirname(__file__), 'res'), '/pkg': ('werkzeug.debug', 'shared'), '/foo': test_dir }) for p in '/test.txt', '/sources/test.txt', '/foo/äöü': app_iter, status, headers = run_wsgi_app(app, create_environ(p)) assert status == '200 OK' with closing(app_iter) as app_iter: data = b''.join(app_iter).strip() assert data == b'FOUND' app_iter, status, headers = run_wsgi_app( app, create_environ('/pkg/debugger.js')) with closing(app_iter) as app_iter: contents = b''.join(app_iter) assert b'$(function() {' in contents app_iter, status, headers = run_wsgi_app( app, create_environ('/missing')) assert status == '404 NOT FOUND' assert b''.join(app_iter).strip() == b'NOT FOUND'
def test_create_environ(self): env = create_environ('/foo?bar=baz', 'http://example.org/') expected = { 'wsgi.multiprocess': False, 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.errors': sys.stderr, 'wsgi.multithread': False, 'wsgi.url_scheme': 'http', 'SCRIPT_NAME': '', 'CONTENT_TYPE': '', 'CONTENT_LENGTH': '0', 'SERVER_NAME': 'example.org', 'REQUEST_METHOD': 'GET', 'HTTP_HOST': 'example.org', 'PATH_INFO': '/foo', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', 'QUERY_STRING': 'bar=baz' } for key, value in expected.iteritems(): assert env[key] == value assert env['wsgi.input'].read(0) == '' assert create_environ('/foo', 'http://example.com/')['SCRIPT_NAME'] == ''
def test_shared_data_middleware(self): def null_application(environ, start_response): start_response('404 NOT FOUND', [('Content-Type', 'text/plain')]) yield b'NOT FOUND' app = wsgi.SharedDataMiddleware(null_application, { '/': path.join(path.dirname(__file__), 'res'), '/sources': path.join(path.dirname(__file__), 'res'), '/pkg': ('werkzeug.debug', 'shared') }) for p in '/test.txt', '/sources/test.txt': app_iter, status, headers = run_wsgi_app(app, create_environ(p)) self.assert_equal(status, '200 OK') with closing(app_iter) as app_iter: data = b''.join(app_iter).strip() self.assert_equal(data, b'FOUND') app_iter, status, headers = run_wsgi_app( app, create_environ('/pkg/debugger.js')) with closing(app_iter) as app_iter: contents = b''.join(app_iter) self.assert_in(b'$(function() {', contents) app_iter, status, headers = run_wsgi_app( app, create_environ('/missing')) self.assert_equal(status, '404 NOT FOUND') self.assert_equal(b''.join(app_iter).strip(), b'NOT FOUND')
def test_shared_data_middleware(self): def null_application(environ, start_response): start_response("404 NOT FOUND", [("Content-Type", "text/plain")]) yield b"NOT FOUND" app = wsgi.SharedDataMiddleware( null_application, { "/": path.join(path.dirname(__file__), "res"), "/sources": path.join(path.dirname(__file__), "res"), "/pkg": ("werkzeug.debug", "shared"), }, ) for p in "/test.txt", "/sources/test.txt": app_iter, status, headers = run_wsgi_app(app, create_environ(p)) self.assert_equal(status, "200 OK") with closing(app_iter) as app_iter: data = b"".join(app_iter).strip() self.assert_equal(data, b"FOUND") app_iter, status, headers = run_wsgi_app(app, create_environ("/pkg/debugger.js")) with closing(app_iter) as app_iter: contents = b"".join(app_iter) self.assert_in(b"$(function() {", contents) app_iter, status, headers = run_wsgi_app(app, create_environ("/missing")) self.assert_equal(status, "404 NOT FOUND") self.assert_equal(b"".join(app_iter).strip(), b"NOT FOUND")
def test_204_and_1XX_response_has_no_content_length(): response = wrappers.Response(status=204) assert response.content_length is None headers = response.get_wsgi_headers(create_environ()) assert 'Content-Length' not in headers response = wrappers.Response(status=100) assert response.content_length is None headers = response.get_wsgi_headers(create_environ()) assert 'Content-Length' not in headers
def test_follow_external_redirect_on_same_subdomain(): env = create_environ('/', base_url='http://example.com') c = Client(external_subdomain_redirect_demo_app, allow_subdomain_redirects=True) c.get(environ_overrides=env, follow_redirects=True) # check that this does not work for real external domains env = create_environ('/', base_url='http://localhost') assert_raises(RuntimeError, lambda: c.get(environ_overrides=env, follow_redirects=True)) # check that subdomain redirects fail if no `allow_subdomain_redirects` is applied c = Client(external_subdomain_redirect_demo_app) assert_raises(RuntimeError, lambda: c.get(environ_overrides=env, follow_redirects=True))
def test_server_name_interpolation(self): server_name = "example.invalid" map = r.Map([r.Rule("/", endpoint="index"), r.Rule("/", endpoint="alt", subdomain="alt")]) env = create_environ("/", "http://%s/" % server_name) adapter = map.bind_to_environ(env, server_name=server_name) assert adapter.match() == ("index", {}) env = create_environ("/", "http://alt.%s/" % server_name) adapter = map.bind_to_environ(env, server_name=server_name) assert adapter.match() == ("alt", {}) env = create_environ("/", "http://%s/" % server_name) adapter = map.bind_to_environ(env, server_name="foo") assert adapter.subdomain == "<invalid>"
def test_server_name_casing(): m = r.Map([r.Rule("/", endpoint="index", subdomain="foo")]) env = create_environ() env["SERVER_NAME"] = env["HTTP_HOST"] = "FOO.EXAMPLE.COM" a = m.bind_to_environ(env, server_name="example.com") assert a.match("/") == ("index", {}) env = create_environ() env["SERVER_NAME"] = "127.0.0.1" env["SERVER_PORT"] = "5000" del env["HTTP_HOST"] a = m.bind_to_environ(env, server_name="example.com") with pytest.raises(r.NotFound): a.match()
def test_closing_iterator(): class Namespace(object): got_close = False got_additional = False class Response(object): def __init__(self, environ, start_response): self.start = start_response # Return a generator instead of making the object its own # iterator. This ensures that ClosingIterator calls close on # the iterable (the object), not the iterator. def __iter__(self): self.start('200 OK', [('Content-Type', 'text/plain')]) yield 'some content' def close(self): Namespace.got_close = True def additional(): Namespace.got_additional = True def app(environ, start_response): return ClosingIterator(Response(environ, start_response), additional) app_iter, status, headers = run_wsgi_app( app, create_environ(), buffered=True) assert ''.join(app_iter) == 'some content' assert Namespace.got_close assert Namespace.got_additional
def test_is_resource_modified_for_range_requests(self): env = create_environ() env["HTTP_IF_MODIFIED_SINCE"] = http.http_date(datetime(2008, 1, 1, 12, 30)) env["HTTP_IF_RANGE"] = http.generate_etag(b"awesome_if_range") # Range header not present, so If-Range should be ignored assert not http.is_resource_modified( env, data=b"not_the_same", ignore_if_range=False, last_modified=datetime(2008, 1, 1, 12, 30), ) env["HTTP_RANGE"] = "" assert not http.is_resource_modified( env, data=b"awesome_if_range", ignore_if_range=False ) assert http.is_resource_modified( env, data=b"not_the_same", ignore_if_range=False ) env["HTTP_IF_RANGE"] = http.http_date(datetime(2008, 1, 1, 13, 30)) assert http.is_resource_modified( env, last_modified=datetime(2008, 1, 1, 14, 00), ignore_if_range=False ) assert not http.is_resource_modified( env, last_modified=datetime(2008, 1, 1, 13, 30), ignore_if_range=False ) assert http.is_resource_modified( env, last_modified=datetime(2008, 1, 1, 13, 30), ignore_if_range=True )
def test_environ_nonascii_pathinfo(self): environ = create_environ("/лошадь") m = r.Map([r.Rule("/", endpoint="index"), r.Rule(u"/лошадь", endpoint="horse")]) a = m.bind_to_environ(environ) self.assert_strict_equal(a.match("/"), ("index", {})) self.assert_strict_equal(a.match("/лошадь"), ("horse", {})) self.assert_raises(r.NotFound, a.match, "/барсук")
def test_package(serial, md5_hash, monkeypatch): safe_join = pretend.call_recorder( lambda *a, **k: "/tmp/packages/any/t/test-1.0.tar.gz" ) _fp = pretend.stub(__enter__=lambda: None, __exit__=lambda *a: None) _open = pretend.call_recorder(lambda *a, **k: _fp) wrap_file = lambda *a, **k: None mtime = pretend.call_recorder(lambda f: 123457) getsize = pretend.call_recorder(lambda f: 54321) monkeypatch.setattr(simple, "safe_join", safe_join) monkeypatch.setattr(simple, "open", _open, raising=False) monkeypatch.setattr(simple, "wrap_file", wrap_file) monkeypatch.setattr(os.path, "getmtime", mtime) monkeypatch.setattr(os.path, "getsize", getsize) gpff = pretend.call_recorder(lambda p: "test") get_md5 = pretend.call_recorder( lambda p: md5_hash ) get_last_serial = pretend.call_recorder(lambda p: serial) app = pretend.stub( config=pretend.stub( cache=pretend.stub(browser=False, varnish=False), paths=pretend.stub(packages="/tmp"), ), models=pretend.stub( packaging=pretend.stub( get_project_for_filename=gpff, get_filename_md5=get_md5, get_last_serial=get_last_serial, ), ), ) request = pretend.stub(environ=create_environ()) resp = simple.package(app, request, path="packages/any/t/test-1.0.tar.gz") if serial: assert resp.headers["X-PyPI-Last-Serial"] == str(serial) else: assert "X-PyPI-Last-Serial" not in resp.headers assert resp.headers["Surrogate-Key"] == "package package~test" assert resp.headers["Content-Length"] == "54321" assert safe_join.calls == [ pretend.call("/tmp", "packages/any/t/test-1.0.tar.gz"), ] assert _open.calls == [ pretend.call("/tmp/packages/any/t/test-1.0.tar.gz", "rb"), ] assert mtime.calls == [pretend.call("/tmp/packages/any/t/test-1.0.tar.gz")] assert getsize.calls == [ pretend.call("/tmp/packages/any/t/test-1.0.tar.gz"), ] assert gpff.calls == [pretend.call("test-1.0.tar.gz")] assert get_md5.calls == [pretend.call("test-1.0.tar.gz")] assert get_last_serial.calls == [pretend.call("test")]
def test_urlfication(): resp = wrappers.Response() resp.headers["Location"] = u"http://üser:pässword@☃.net/påth" resp.headers["Content-Location"] = u"http://☃.net/" headers = resp.get_wsgi_headers(create_environ()) assert headers["location"] == "http://%C3%BCser:p%C3%[email protected]/p%C3%A5th" assert headers["content-location"] == "http://xn--n3h.net/"
def test_server_name_interpolation(self): server_name = 'example.invalid' map = r.Map([r.Rule('/', endpoint='index'), r.Rule('/', endpoint='alt', subdomain='alt')]) env = create_environ('/', 'http://%s/' % server_name) adapter = map.bind_to_environ(env, server_name=server_name) assert adapter.match() == ('index', {}) env = create_environ('/', 'http://alt.%s/' % server_name) adapter = map.bind_to_environ(env, server_name=server_name) assert adapter.match() == ('alt', {}) env = create_environ('/', 'http://%s/' % server_name) adapter = map.bind_to_environ(env, server_name='foo') assert adapter.subdomain == '<invalid>'
def test_path_info_extraction(self): x = wsgi.extract_path_info('http://example.com/app', '/app/hello') self.assert_equal(x, u'/hello') x = wsgi.extract_path_info('http://example.com/app', 'https://example.com/app/hello') self.assert_equal(x, u'/hello') x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app/hello') self.assert_equal(x, u'/hello') x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app') self.assert_equal(x, u'/') x = wsgi.extract_path_info(u'http://☃.net/', u'/fööbär') self.assert_equal(x, u'/fööbär') x = wsgi.extract_path_info(u'http://☃.net/x', u'http://☃.net/x/fööbär') self.assert_equal(x, u'/fööbär') env = create_environ(u'/fööbär', u'http://☃.net/x/') x = wsgi.extract_path_info(env, u'http://☃.net/x/fööbär') self.assert_equal(x, u'/fööbär') x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/a/hello') self.assert_is_none(x) x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app/hello', collapse_http_schemes=False) self.assert_is_none(x)
def test_external_building_with_port_bind_to_environ_wrong_servername(self): map = r.Map([ r.Rule('/', endpoint='index'), ]) environ = create_environ('/', 'http://example.org:5000/') adapter = map.bind_to_environ(environ, server_name="example.org") assert adapter.subdomain == '<invalid>'
def test_range_request_without_complete_length(): env = create_environ() response = wrappers.Response('Hello World') env['HTTP_RANGE'] = 'bytes=-' response.make_conditional(env, accept_ranges=True, complete_length=None) assert response.status_code == 200 assert response.data == b'Hello World'
def test_path_info_extraction(self): x = wsgi.extract_path_info('http://example.com/app', '/app/hello') assert x == u'/hello' x = wsgi.extract_path_info('http://example.com/app', 'https://example.com/app/hello') assert x == u'/hello' x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app/hello') assert x == u'/hello' x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app') assert x == u'/' x = wsgi.extract_path_info(u'http://☃.net/', u'/fööbär') assert x == u'/fööbär' x = wsgi.extract_path_info(u'http://☃.net/x', u'http://☃.net/x/fööbär') assert x == u'/fööbär' env = create_environ(u'/fööbär', u'http://☃.net/x/') x = wsgi.extract_path_info(env, u'http://☃.net/x/fööbär') assert x == u'/fööbär' x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/a/hello') assert x is None x = wsgi.extract_path_info('http://example.com/app/', 'https://example.com/app/hello', collapse_http_schemes=False) assert x is None
def test_wsgi_app_exception(app, monkeypatch): match = pretend.stub(match=pretend.call_recorder(lambda: ("warehouse.fake.view", {}))) urls = pretend.stub(bind_to_environ=pretend.call_recorder(lambda e: match)) response = pretend.call_recorder(lambda e, s: None) class FakeException(HTTPException): # @pretend.call_recorder def __call__(self, *args, **kwargs): return response @pretend.call_recorder def fake_view(*args, **kwargs): raise FakeException("An error has occurred") fake_module = pretend.stub(view=fake_view) import_module = pretend.call_recorder(lambda mod: fake_module) monkeypatch.setattr(importlib, "import_module", import_module) environ = create_environ() start_response = pretend.stub() app.urls = urls app.wsgi_app(environ, start_response) assert match.match.calls == [pretend.call()] assert urls.bind_to_environ.calls == [pretend.call(environ)] assert import_module.calls == [pretend.call("warehouse.fake")] assert fake_view.calls == [pretend.call(app, mock.ANY)]
def test_external_building_with_port_bind_to_environ_wrong_servername(): """Test external URL building with port number (map.bind_to_environ) with wrong server name raises ValueError""" map = Map([ Rule('/', endpoint='index'), ]) environ = create_environ('/', 'http://example.org:5000/') assert_raises(ValueError, lambda: map.bind_to_environ(environ, server_name="example.org"))
def test_generate_response_with_only_accept_header(self): env = create_environ(headers={'Accept': 'application/json'}) req = Request(env) resp = utils.generate_response(request=req) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.status, '200 OK') self.assertEqual(resp.content_type, 'application/json')
def test_generate_response_with_valid_header_and_invalid_extension(self): env = create_environ(headers={'Accept': 'application/json'}) req = Request(env) resp = utils.generate_response(request=req, data=None, \ format='foo') self.assertEqual(resp.status_code, 406) self.assertEqual(resp.status, '406 NOT ACCEPTABLE')
def test_etag_response_mixin(): """ETag response-wrapper mixin""" response = Response('Hello World') assert response.get_etag() == (None, None) response.add_etag() assert response.get_etag() == ('b10a8db164e0754105b7a99be72e3fe5', False) assert not response.cache_control response.cache_control.must_revalidate = True response.cache_control.max_age = 60 response.headers['Content-Length'] = len(response.data) assert response.headers['Cache-Control'] == 'must-revalidate, max-age=60' assert 'date' not in response.headers env = create_environ() env.update({ 'REQUEST_METHOD': 'GET', 'HTTP_IF_NONE_MATCH': response.get_etag()[0] }) response.make_conditional(env) assert 'date' in response.headers # after the thing is invoked by the server as wsgi application # (we're emulating this here), there must not be any entity # headers left and the status code would have to be 304 resp = Response.from_app(response, env) assert resp.status_code == 304 assert not 'content-length' in resp.headers # make sure date is not overriden response = Response('Hello World') response.date = 1337 d = response.date response.make_conditional(env) assert response.date == d
def failed_transaction(): class Env(TransactionMixin, BaseEnvironment): transaction_manager = Fake("TransactionManager").remember_order().expects("begin").expects("abort") with raises(RuntimeError): with Env(BaseApplication(), create_environ()): raise RuntimeError
def test_path_info_from_request_uri_fix(self): app = fixers.PathInfoFromRequestUriFix(path_check_app) for key in 'REQUEST_URI', 'REQUEST_URL', 'UNENCODED_URL': env = dict(create_environ(), SCRIPT_NAME='/test', PATH_INFO='/?????') env[key] = '/test/foo%25bar?drop=this' response = Response.from_app(app, env) assert response.get_data() == b'PATH_INFO: /foo%bar\nSCRIPT_NAME: /test'
def test_proxy_fix(self): @Request.application def app(request): return Response('%s|%s' % ( request.remote_addr, # do not use request.host as this fixes too :) request.environ['HTTP_HOST'] )) app = fixers.ProxyFix(app, num_proxies=2) environ = dict( create_environ(), HTTP_X_FORWARDED_PROTO="https", HTTP_X_FORWARDED_HOST='example.com', HTTP_X_FORWARDED_FOR='1.2.3.4, 5.6.7.8', REMOTE_ADDR='127.0.0.1', HTTP_HOST='fake' ) response = Response.from_app(app, environ) assert response.get_data() == b'1.2.3.4|example.com' # And we must check that if it is a redirection it is # correctly done: redirect_app = redirect('/foo/bar.hml') response = Response.from_app(redirect_app, environ) wsgi_headers = response.get_wsgi_headers(environ) assert wsgi_headers['Location'] == 'https://example.com/foo/bar.hml'
def test_get_host_multiple_forwarded(self): env = {'HTTP_X_FORWARDED_HOST': 'example.com, example.org', 'SERVER_NAME': 'bullshit', 'HOST_NAME': 'ignore me dammit'} self.assert_equal(wsgi.get_host(env), 'example.com') self.assert_equal( wsgi.get_host(create_environ('/', 'http://example.com')), 'example.com')
def test_render_response(): template = pretend.stub(render=pretend.call_recorder(lambda **k: "test")) app = pretend.stub( config=pretend.stub(), templates=pretend.stub( get_template=pretend.call_recorder(lambda t: template), ), ) request = pretend.stub() resp = render_response(app, request, "template.html", foo="bar") assert resp.get_wsgi_headers(create_environ())["Content-Length"] == "4" assert resp.data == b"test" assert app.templates.get_template.calls == [pretend.call("template.html")] assert template.render.calls == [ pretend.call( foo="bar", config=app.config, csrf_token=mock.ANY, gravatar_url=mock.ANY, url_for=mock.ANY, static_url=mock.ANY, ), ]
def test_basic_routing(): map = r.Map([ r.Rule("/", endpoint="index"), r.Rule("/foo", endpoint="foo"), r.Rule("/bar/", endpoint="bar"), r.Rule("/ws", endpoint="ws", websocket=True), r.Rule("/", endpoint="indexws", websocket=True), ]) adapter = map.bind("example.org", "/") assert adapter.match("/") == ("index", {}) assert adapter.match("/foo") == ("foo", {}) assert adapter.match("/bar/") == ("bar", {}) pytest.raises(r.RequestRedirect, lambda: adapter.match("/bar")) pytest.raises(r.NotFound, lambda: adapter.match("/blub")) adapter = map.bind("example.org", "/", url_scheme="ws") assert adapter.match("/") == ("indexws", {}) adapter = map.bind("example.org", "/test") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar") assert excinfo.value.new_url == "http://example.org/test/bar/" adapter = map.bind("example.org", "/") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar") assert excinfo.value.new_url == "http://example.org/bar/" adapter = map.bind("example.org", "/") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar", query_args={"aha": "muhaha"}) assert excinfo.value.new_url == "http://example.org/bar/?aha=muhaha" adapter = map.bind("example.org", "/") with pytest.raises(r.RequestRedirect) as excinfo: adapter.match("/bar", query_args="aha=muhaha") assert excinfo.value.new_url == "http://example.org/bar/?aha=muhaha" adapter = map.bind_to_environ( create_environ("/bar?foo=bar", "http://example.org/")) with pytest.raises(r.RequestRedirect) as excinfo: adapter.match() assert excinfo.value.new_url == "http://example.org/bar/?foo=bar" adapter = map.bind("example.org", "/ws", url_scheme="wss") assert adapter.match("/ws", websocket=True) == ("ws", {}) with pytest.raises(r.WebsocketMismatch): adapter.match("/ws", websocket=False) with pytest.raises(r.WebsocketMismatch): adapter.match("/foo", websocket=True) adapter = map.bind_to_environ( create_environ( "/ws?foo=bar", "http://example.org/", headers=[("Connection", "Upgrade"), ("upgrade", "WebSocket")], )) assert adapter.match("/ws") == ("ws", {}) with pytest.raises(r.WebsocketMismatch): adapter.match("/ws", websocket=False) adapter = map.bind_to_environ( create_environ( "/ws?foo=bar", "http://example.org/", headers=[("Connection", "keep-alive, Upgrade"), ("upgrade", "websocket")], )) assert adapter.match("/ws") == ("ws", {}) with pytest.raises(r.WebsocketMismatch): adapter.match("/ws", websocket=False)
def test_response_304_no_content_length(self): resp = wrappers.Response('Test', status=304) env = create_environ() assert 'content-length' not in resp.get_wsgi_headers(env)
def test_path_info_and_script_name_fetching(): env = create_environ(u'/\N{SNOWMAN}', u'http://example.com/\N{COMET}/') assert wsgi.get_path_info(env) == u'/\N{SNOWMAN}' assert wsgi.get_path_info(env, charset=None) == u'/\N{SNOWMAN}'.encode('utf-8') assert wsgi.get_script_name(env) == u'/\N{COMET}' assert wsgi.get_script_name(env, charset=None) == u'/\N{COMET}'.encode('utf-8')
def test_B_get(self): environ_2 = create_environ("/lang") result = run_wsgi_app(flask_jenkins_app, environ_2, True) self.assertEqual(result[0], [ b'{"languages":[{"name":"python"},{"name":"java"},{"name":"javascript"}]}\n' ])
def test_get_current_url_unicode(): env = create_environ() env['QUERY_STRING'] = 'foo=bar&baz=blah&meh=\xcf' rv = wsgi.get_current_url(env) strict_eq(rv, u'http://localhost/?foo=bar&baz=blah&meh=\ufffd')
adapter.match('/bar', query_args={'aha': 'muhaha'}) except r.RequestRedirect, e: assert e.new_url == 'http://example.org/bar/?aha=muhaha' else: self.fail('Expected request redirect') adapter = map.bind('example.org', '/') try: adapter.match('/bar', query_args='aha=muhaha') except r.RequestRedirect, e: assert e.new_url == 'http://example.org/bar/?aha=muhaha' else: self.fail('Expected request redirect') adapter = map.bind_to_environ( create_environ('/bar?foo=bar', 'http://example.org/')) try: adapter.match() except r.RequestRedirect, e: assert e.new_url == 'http://example.org/bar/?foo=bar' else: self.fail('Expected request redirect') def test_environ_defaults(self): environ = create_environ("/foo") self.assert_equal(environ["PATH_INFO"], '/foo') m = r.Map( [r.Rule("/foo", endpoint="foo"), r.Rule("/bar", endpoint="bar")]) a = m.bind_to_environ(environ) self.assert_equal(a.match("/foo"), ('foo', {}))
# basic models from basedir import _basedir import os import sys import pkg_resources from threading import local # werkzeug from werkzeug.wrappers import Request, Response from werkzeug.routing import Map, Rule from werkzeug import LocalStack, LocalProxy from werkzeug.exceptions import HTTPException from werkzeug.contrib.securecookie import SecureCookie from werkzeug.test import create_environ from werkzeug.test import create_environ environ = create_environ() # jinja from jinja2 import Environment, PackageLoader # try to import the json helpers # simplejson is more efficient than json, so # we first want import simplejson, if it meet ImportError # than import json try: from simplejson import loads as load_json, dumps as dump_json except ImportError: try: from json import loads as load_json, dumps as dump_json except ImportError: pass
def test_wsgi(self): os.environ['RELEASEDATE_CONFIG'] = os.path.join( os.path.dirname(__file__), 'releasedate.cfg') from releasedate.wsgi import application app_iter, status, header = run_wsgi_app(application, create_environ()) assert status == '409 CONFLICT'
def test_redirect_request_exception_code(self): exc = r.RequestRedirect('http://www.google.com/') exc.code = 307 env = create_environ() self.assert_strict_equal(exc.get_response(env).status_code, exc.code)
def test_server_name_match_default_port(base, name): environ = create_environ("/foo", base_url=base) map = r.Map([r.Rule("/foo", endpoint="foo")]) adapter = map.bind_to_environ(environ, server_name=name) assert adapter.match() == ("foo", {})
def test_redirect_request_exception_code(): exc = r.RequestRedirect("http://www.google.com/") exc.code = 307 env = create_environ() strict_eq(exc.get_response(env).status_code, exc.code)
def test_A_health_check(self): environ_1 = create_environ('/health-check') result = run_wsgi_app(flask_jenkins_app, environ_1, True) self.assertEqual(result[0], [b'{"Message":"Server is alive"}\n'])
def test_request_context(self, *args, **kwargs): return self.request_context(create_environ(*args, **kwargs))
def test_get_host(): env = {'HTTP_X_FORWARDED_HOST': 'example.org', 'SERVER_NAME': 'bullshit', 'HOST_NAME': 'ignore me dammit'} assert wsgi.get_host(env) == 'example.org' assert wsgi.get_host(create_environ('/', 'http://example.org')) == \ 'example.org'
def test_query_string_fetching(): env = create_environ(u'/?\N{SNOWMAN}=\N{COMET}') qs = wsgi.get_query_string(env) strict_eq(qs, '%E2%98%83=%E2%98%84')
def test_path_info_and_script_name_fetching(self): env = create_environ(u'/\N{SNOWMAN}', u'http://example.com/\N{COMET}/') self.assert_equal(wsgi.get_path_info(env), u'/\N{SNOWMAN}') self.assert_equal(wsgi.get_path_info(env, charset=None), u'/\N{SNOWMAN}'.encode('utf-8')) self.assert_equal(wsgi.get_script_name(env), u'/\N{COMET}') self.assert_equal(wsgi.get_script_name(env, charset=None), u'/\N{COMET}'.encode('utf-8'))
def create_request(*args, **kwargs): """Creates a test request object""" env = create_environ(*args, **kwargs) return Request(env)
def test_create_environ_query_string_error(): with pytest.raises(ValueError): create_environ("/foo?bar=baz", query_string={"a": "b"})
def application_and_request_context( environ: Optional[Mapping[str, Any]] = None) -> Iterator[None]: if environ is None: environ = dict(create_environ(), REQUEST_URI="") with application_context(environ), request_context(environ): yield
def test_follow_external_redirect(): env = create_environ("/", base_url="http://localhost") c = Client(external_redirect_demo_app) pytest.raises( RuntimeError, lambda: c.get(environ_overrides=env, follow_redirects=True) )
def test_init_makes_form_a_dict_with_decoded_and_deserialized_form_data( self): request = Request(create_environ(data={'a': '{"a":2}', 'b': '"3"'})) self.assertEqual(request.form, {'a': {'a': 2}, 'b': '3'})
def test_create_environ_query_string_error(): with pytest.raises(ValueError): create_environ('/foo?bar=baz', query_string={'a': 'b'})
def test_not_valid_url_raises_404(path): env = create_environ(method="GET", path=path) (app_iter, status, headers) = run_wsgi_app(server.app, env) status = int(status[:3]) assert status == 404
def test_init_makes_json_a_dict_with_decoded_and_deserialized_data(self): request = Request(create_environ(data='{"a":1,"b":2}')) self.assertEqual(request.json, {'a': 1, 'b': 2})
def test_get_current_url_unicode(self): env = create_environ() env['QUERY_STRING'] = 'foo=bar&baz=blah&meh=\xcf' rv = wsgi.get_current_url(env) self.assertEqual(rv, 'http://localhost/?foo=bar&baz=blah&meh=%CF')
def test_valid_url_without_token(path): env = create_environ(method="GET", path=path) (app_iter, status, headers) = run_wsgi_app(server.app, env) status = int(status[:3]) assert status == 403 assert "X-Accel-Redirect" not in headers
def make_req_headers(**kwargs): environ = create_environ('/collections/obs/items', 'http://localhost:5000/') environ.update(kwargs) request = Request(environ) return request.headers
def test_checkmk_app_enables_timeout_handling(): assert signal.alarm(0) == 0 CheckmkTestApp()(create_environ(), make_start_response()) assert signal.alarm(0) == 0
def test_cgi_root_fix_custom_app_root(self): app = fixers.CGIRootFix(path_check_app, app_root='/baz/poop/') response = Response.from_app( app, dict(create_environ(), SCRIPT_NAME='/foo', PATH_INFO='/bar')) assert response.data == 'PATH_INFO: /foo/bar\nSCRIPT_NAME: baz/poop'
def register_builtin_html(): """This fixture registers a global htmllib.html() instance just like the regular GUI""" environ = create_environ() with AppContext(DummyApplication(environ, None)), \ RequestContext(htmllib.html(Request(environ))): yield