def test_websocket (app): def onopen (was): return 'Welcome' @app.route ("/echo") @app.websocket (skitai.WS_SIMPLE, 60, onopen = onopen) def echo (was, message): was.websocket.send ('1st: ' + message) return "2nd: " + message @app.route ("/echo2") @app.websocket (skitai.WS_SIMPLE | skitai.WS_NQ, 60, onopen = onopen) def echo2 (was, message): was.websocket.send ('1st: ' + message) return "2nd: " + message with app.test_client ("/", confutil.getroot ()) as cli: resp = cli.ws ("/echo", "hello") assert resp.status_code == 403 app.access_control_allow_origin = ["*"] with app.test_client ("/", confutil.getroot ()) as cli: resp = cli.ws ("/echo", "hello") assert resp.status_code == 101 assert resp.content == b'\x81\x07Welcome' resp = cli.ws ("/echo2", "hello") assert resp.status_code == 101 assert resp.content == b'\x81\x07Welcome'
def test_route_empty(app): app._mount_option["point"] = "/beta" @app.route("/") def index2(was, path=None): return "Hello, World" with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/beta") assert resp.status_code == 301 resp = cli.get("/beta/") assert resp.status_code == 200 resp = cli.get("/beta/1") assert resp.status_code == 404 @app.route("") def index(was, path=None): return "Hello, World" with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/beta") assert resp.text == "Hello, World" resp = cli.get("/beta/") assert resp.status_code == 200 resp = cli.get("/beta/1") assert resp.status_code == 404
def test_atila(wasc, app): was = wasc() was.app = app app.skito_jinja() app.set_home(confutil.getroot()) assert app.get_resource() == os.path.join(confutil.getroot(), 'resources') app._mount(confutil) assert confutil in app.reloadables
def test_default_error_handler(app): @app.default_error_handler def default_error_handler(was, error): was.response.update("Content-Type", "application/json; charset: utf8") error["say"] = "hello" return json.dumps(error, ensure_ascii=False, indent=2) @app.route("/f1") def f1(was): def respond(was, rss): raise was.Error("414 Not Found") reqs = [was.get("@pypi/project/rs4/")] return was.futures(reqs).then(respond) @app.route("/f2") def f2(was): raise was.Error("414 Not Found") app.alias("@pypi", skitai.PROTO_HTTPS, "pypi.org") with app.test_client("/", confutil.getroot()) as cli: api = cli.api("/") resp = api.f1.get() assert resp.status_code == 414 assert resp.data["say"] == "hello" resp = api.f2.get() assert resp.status_code == 414 assert resp.data["say"] == "hello" assert resp.get_header( "content-type") == "application/json; charset: utf8"
def test_wsgi_handler(wasc, app, client): @app.route("/") def index(was): return "Hello" @app.route("/json") def json(was): return "Hello" @app.route("/rpc2/add") def add(was, a, b): return a + b # WSGI vh = testutil.install_vhost_handler() testutil.mount("/", (app, confutil.getroot()), skitai.pref()) request = client.get("http://www.skitai.com/") resp = assert_request(vh, request, 200) assert resp.text == "Hello" request = client.get("http://www.skitai.com/", version="2.0") resp = assert_request(vh, request, 200) assert resp.text == "Hello" request = client.get("http://www.skitai.com/a") resp = assert_request(vh, request, 404) request = client.get("http://www.skitai.com/?a=b") resp = assert_request(vh, request, 200) request = client.api().json.post({'a': 1}) resp = assert_request(vh, request, 200) answer = client.rpc("http://www.skitai.com/rpc2/").add(100, 50) resp = assert_request(vh, request, 200) answer = client.jsonrpc("http://www.skitai.com/rpc2/").add(100, 50) resp = assert_request(vh, request, 200) testutil.enable_threads() assert wasc.numthreads == 1 assert wasc.threads request = client.postjson("http://www.skitai.com/json", {'a': 1}) resp = assert_request(vh, request, 200) request = client.postjson("http://www.skitai.com/json", {'a': 1}, version="2.0") resp = assert_request(vh, request, 200) testutil.disable_threads() assert wasc.numthreads == 0 assert wasc.threads is None request = client.postjson("http://www.skitai.com/json", {'a': 1}) resp = assert_request(vh, request, 200) request = client.postjson("http://www.skitai.com/json", {'a': 1}, version="2.0") resp = assert_request(vh, request, 200)
def test_namespaced_mount(app): app.mount("/v1", myapp, ns="v1") app._mount(myapp) with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/v1/apis/owners/1") assert resp.status_code == 200 assert app.urlfor("v1.owners", 2) == "/v1/apis/owners/2"
def test_error_handler(app): @app.default_error_handler def default_error_handler(was, error): return str(error) @app.route("/") def index(was): raise ValueError app.debug = True with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert "ValueError" in resp.text app.debug = False with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert "ValueError" not in resp.text
def test_error_handler_2(app): @app.route("/20") @app.require("GET", ["limit"], ints=['limit']) @app.require("POST", ["id"]) def index20(was, limit=10, **DATA): if was.request.method == "POST": assert DATA['id'] return 'OK' @app.route("/21") @app.require("URL", ["limit"], ints=['limit']) @app.require("POST", ["id"]) def index21(was, limit, **DATA): if was.request.method == "POST": assert DATA['id'] return 'OK' @app.route("/22") @app.require("POST", ["id"]) def index21(was, limit, **DATA): if was.request.method == "POST": assert DATA['id'] return 'OK' with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/20") assert resp.status_code == 400 resp = cli.get("/20?limit=4") assert resp.status_code == 200 resp = cli.post("/20?limit=4", {}) assert resp.status_code == 400 resp = cli.post("/20?limit=4", {'id': 'ttt'}) assert resp.status_code == 200 resp = cli.post("/20", {'id': 'ttt'}) assert resp.status_code == 200 resp = cli.get("/21") assert resp.status_code == 400 resp = cli.get("/21?limit=4") assert resp.status_code == 200 resp = cli.post("/21?limit=4", {}) assert resp.status_code == 400 resp = cli.post("/21", {'id': 'ttt'}) assert resp.status_code == 400 resp = cli.get("/22") assert resp.status_code == 400
def test_https(launch): with launch("./examples/https.py", ssl=True) as engine: for url in ("/", "/documentation", "/documentation2", "/documentation3", "/hello", "/redirect1", "/redirect2"): assert_requests(200, url) assert_post_requests(200, "/post", {"username": "******"}) jpg = open(os.path.join(confutil.getroot(), "statics", "reindeer.jpg"), "rb") assert_post_requests(200, "/upload", {"username": "******"}, files={"file1": jpg})
def test_route_root(app, dbpath): @app.route("/<path:path>") @app.route("/") def index(was, path=None): return "Hello, World" with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.text == "Hello, World" resp = cli.get("/hello") assert resp.text == "Hello, World"
def test_error_handler(app): @app.route("/") @app.parameters_required("URL", ["limit"]) def index(was): return "" @app.route("/2") @app.parameters_required("FORM", ["limit"]) def index2(was): return "" @app.route("/3") @app.parameters_required("JSON", ["limit"]) def index3(was): return "" @app.route("/4") @app.parameters_required("ARGS", ["limit"]) def index4(was): return "" with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.status_code == 400 resp = cli.get("/?limit=4") assert resp.status_code == 200 resp = cli.get("/2?limit=4") assert resp.status_code == 400 resp = cli.post("/2", {"limit": 4}) assert resp.status_code == 200 api = cli.api() resp = api("2").post({"limit": 4}) assert resp.status_code == 400 api = cli.api() resp = api("3").post({"limit": 4}) assert resp.status_code == 200 api = cli.api() resp = api("4").post({"limit": 4}) assert resp.status_code == 200 resp = cli.get("/4?limit=4") assert resp.status_code == 200 resp = cli.post("/4", {"limit": 4}) assert resp.status_code == 200
def test_db3(app, dbpath): @app.route("/") def index(was): with was.sdb("@sqlite") as trx: d = trx.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT', )).fetch() with was.sdb("@sqlite") as trx: d2 = trx.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) return str(d2.fetch()) app.alias("@sqlite", skitai.DB_SQLITE3, dbpath) with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert "RHAT" in resp.text
def test_route_root(app, dbpath): @app.route("/index") @app.require("URL", ints=["t"]) def index(was, t=0): t = int(t) if t == 0: return was.API("200 OK") if t == 1: return was.API("205 No Content") if t == 2: return was.API("201 Created", {"data": 1}) if t == 3: return was.API("201 Created", data=1) if t == 4: return was.API(data=1) if t == 5: return was.API({"data": 1}) if t == 9: return was.API("201 Created", {"data": 1}, data=2) with app.test_client("/", confutil.getroot()) as cli: api = cli.api() resp = api.index.get(t=0) assert resp.status_code == 200 resp = api.index.get(t=1) assert resp.status_code == 205 assert resp.data == {} resp = api.index.get(t=2) assert resp.status_code == 201 assert resp.data == {"data": 1} resp = api.index.get(t=3) assert resp.status_code == 201 assert resp.data == {"data": 1} resp = api.index.get(t=4) assert resp.status_code == 200 assert resp.data == {"data": 1} resp = api.index.get(t=5) assert resp.status_code == 200 assert resp.data == {"data": 1} resp = api.index.get(t=9) assert resp.status_code == 201 assert resp.data == {"data": 2}
def makeset (https = 0, http2 = False): server = (https and "https" or "http") + "://127.0.0.1:30371" jpg = open (os.path.join (confutil.getroot (), "statics", "reindeer.jpg"), "rb") targets = ("/", "/hello", "/redirect1", "/redirect2", "/documentation", "/documentation2") for url in targets: aquests.get (server + url) aquests.get (server +"/members/", auth = ('admin', '1111')) aquests.post (server + "/post", {"username": "******"}) aquests.upload (server +"/upload", {"username": "******", "file1": jpg}) stub = aquests.rpc (server +"/rpc2/") stub.add_number (5, 7) if http2 and GRPC: stub = aquests.grpc (server +"/routeguide.RouteGuide/") point = route_guide_pb2.Point (latitude=409146138, longitude=-746188906) stub.GetFeature (point)
def test_futures(app, dbpath): @app.route("/") def index(was): with was.xmlrpc("@pypi/pypi") as stub: req = stub.package_releases('roundup') assert req.fetch() == ['1.6.1'] with was.asyncon("@sqlite") as db: req = db.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) result = was.Tasks([req])[0] return str(result.fetch()) app.alias("@pypi", skitai.PROTO_HTTPS, "pypi.org") app.alias("@sqlite", skitai.DB_SQLITE3, dbpath) with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert "RHAT" in resp.text
def test_websocket_handler(wasc, app, client): @app.route("/echo") def echo(was, message): if was.wsinit(): return was.wsconfig(skitai.WS_SIMPLE, 60) elif was.wsopened(): return "Welcome Client %s" % was.wsclient() elif was.wshasevent(): # ignore the other events return was.websocket.send("You said," + message) was.websocket.send("acknowledge") @app.route("/chat") def chat(was, message, roomid): if was.wsinit(): return was.wsconfig(skitai.WS_GROUPCHAT, 60) elif was.wsopened(): return "Client %s has entered" % was.wsclient() elif was.wsclosed(): return "Client %s has leaved" % was.wsclient() return "Client %s Said: %s" % (was.wsclient(), message) vh = testutil.install_vhost_handler() root = confutil.getroot() pref = skitai.pref() vh.add_route("default", ("/ws", app, root), pref) app.access_control_allow_origin = ["http://www.skitai.com:80"] # WEBSOCKET testutil.enable_threads() resp = client.ws("http://www.skitai.com/ws/echo", "Hello") assert resp.status_code == 101 resp = client.ws("http://www.skitai.com/ws/chat", "Hello") assert resp.status_code == 500 resp = client.ws("http://www.skitai.com/ws/chat?roomid=1", "Hello") assert resp.status_code == 101 testutil.disable_threads() resp = client.ws("http://www.skitai.com/ws/echo", "Hello") assert resp.status_code == 101 resp = client.ws("http://www.skitai.com/ws/chat?roomid=1", "Hello") assert resp.status_code == 101
def test_app(launch): with launch("./examples/app.py") as engine: assert_request(401, "/members/") assert_request(200, "/members/", auth=HTTPDigestAuth("admin", "1111")) for url in ("/", "/documentation", "/documentation2", "/documentation3", "/hello", "/redirect1", "/redirect2", "/db", "/dbmap", "/dbtx", "/xmlrpc"): assert_request(200, url) assert_request(200, url) assert_post_request(200, "/post", {"username": "******"}) jpg = open(os.path.join(confutil.getroot(), "statics", "reindeer.jpg"), "rb") assert_post_request(200, "/upload", {"username": "******"}, files={"file1": jpg}) with xmlrpc.client.ServerProxy( "http://127.0.0.1:30371/rpc2/") as proxy: assert proxy.add_number(1, 3) == 4
def test_futures (app, dbpath): @app.route ("/") def index (was): return was.File ('level3/test_file.py', 'application/python', 'test.py') @app.route ("/1") def index (was): f = BytesIO () f.write (b'Be cool') return was.File (f, 'application/python', 'test.py') app.alias ("@sqlite", skitai.DB_SQLITE3, dbpath) with app.test_client ("/", confutil.getroot ()) as cli: resp = cli.get ("/") assert resp.status_code == 200 assert resp.headers.get ('content-type') == 'application/python' assert b'application/python' in resp.content resp = cli.get ("/1") print (resp.headers) assert resp.status_code == 200 assert resp.headers.get ('content-type') == 'application/python' assert 'Be cool' in resp.text
def test_error_handler(app): @app.route("/a") @app.require("JSON", ["limit"]) def indexa(was, limit): return was.API() @app.route("/b") @app.require("URL", ["limit"]) def indexb(was, limit): raise was.Error("422 Bad Request") with app.test_client("/", confutil.getroot()) as cli: app.expose_spec = True app.debug = True resp = cli.api().a.post({"limit": 10}) assert resp.status_code == 200 assert "__spec__" in resp.data resp = cli.api().b.get(limit=10) assert resp.status_code == 422 assert "__spec__" in resp.data app.debug = False app.expose_spec = False
def test_futures(app, dbpath): @app.route("/") def index(was): def respond(was, rss): return was.response.API( status_code=[rs.status_code for rs in rss.dispatch()], a=rss.a) reqs = [ was.get("@pypi/project/skitai/"), was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return was.Tasks(reqs, a=100).then(respond) @app.route("/2") def index2(was): def repond(was, rss): return was.response.API( status_code_db=[rs.status_code for rs in rss.dispatch()], b=rss.b, status_code=rss.status_code) def checkdb(was, rss): reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return was.Tasks(reqs, b=rss.a + 100, status_code=[ rs.status_code for rs in rss.dispatch() ]).then(repond) def begin(): reqs = [ was.get("@pypi/project/skitai/"), was.get("@pypi/project/rs4/") ] return was.Tasks(reqs, a=100).then(checkdb) begin() @app.route("/3") def index3(was): def respond(was, rss): datas = str(rss[0].fetch()) + str(rss[1].one()) return datas reqs = [ was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return was.Tasks(reqs).then(respond) @app.route("/4") def index4(was): def respond(was, rss): return str(rss[0].one()) reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('---', )) ] return was.Tasks(reqs).then(respond) @app.route("/4-1") def index4_1(was): def respond(was, rs): return str(rs.fetch()) req = was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('---', )) return req.then(respond) @app.route("/5") def index5(was): reqs = [ was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return str([rs.fetch() for rs in was.Tasks(reqs)]) @app.route("/6") def index6(was): reqs = [ was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return str(was.Tasks(reqs).fetch()) @app.route("/7") def index7(was): reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=? limit 1', ('RHAT', )), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=? limit 1', ('RHAT', )) ] return str(was.Tasks(reqs).one()) @app.route("/8") def index8(was): reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM ghost WHERE symbol=? limit 1', ('RHAT', )), was.backend("@sqlite").execute( 'SELECT * FROM ghost WHERE symbol=? limit 1', ('RHAT', )) ] return str(was.Tasks(reqs).one()) @app.route("/9") def index9(was): reqs = [ was.backend("@sqlite").execute("INSERT INTO ghost (id) values (1)") ] return str(was.Tasks(reqs).wait()) @app.route("/10") def index10(was): reqs = [ was.backend("@sqlite").execute("INSERT INTO ghost (id) values (1)") ] return str(was.Tasks(reqs).commit()) @app.route("/11") def index11(was): reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=? limit 0', ('RHAT', )), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=? limit 1', ('RHAT', )) ] return str(was.Tasks(reqs).one()) @app.route("/12") def index12(was): a = was.Tasks([ was.backend("@sqlite").execute( 'SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT', )) ]) b = was.Tasks([ was.backend("@sqlite").execute( 'SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT', )) ]) a.add(b) return str(a.one()) @app.route("/13") def index13(was): def respond(was, rss): return str(rss.one()) a = was.Tasks([ was.backend("@sqlite").execute( 'SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT', )) ]) b = was.Tasks([ was.backend("@sqlite").execute( 'SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT', )) ]) a.merge(b) return a.then(respond) app.alias("@pypi", skitai.PROTO_HTTPS, "pypi.org") app.alias("@sqlite", skitai.DB_SQLITE3, dbpath) with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.data['status_code'] == [200, 200, 200] assert resp.data['a'] == 100 resp = cli.get("/2") assert resp.data['status_code'] == [200, 200] assert resp.data['status_code_db'] == [200] assert resp.data['b'] == 200 resp = cli.get("/3") assert "hansroh" in resp.text assert "RHAT" in resp.text resp = cli.get("/4") assert resp.status_code == 410 resp = cli.get("/4-1") assert resp.status_code == 200 assert resp.data == '[]' resp = cli.get("/5") assert "hansroh" in resp.text assert "RHAT" in resp.text resp = cli.get("/6") assert "hansroh" in resp.text assert "RHAT" in resp.text resp = cli.get("/7") assert "RHAT" in resp.text resp = cli.get("/8") assert resp.status_code == 502 resp = cli.get("/9") assert resp.status_code == 200 resp = cli.get("/10") assert resp.status_code == 502 resp = cli.get("/11") assert resp.status_code == 410 resp = cli.get("/12") assert resp.data == "[{'symbol': 'RHAT'}, [{'symbol': 'RHAT'}]]" resp = cli.get("/13") assert resp.data == "[{'symbol': 'RHAT'}, {'symbol': 'RHAT'}]"
def test_error_handler(app): @app.permission_check_handler def permission_check_handler(was, perms): if not perms: return if "admin" in perms: raise was.Error("402 Permission Denied") raise was.Error("403 Permission Denied") @app.route("/") @app.permission_required() def index(was): return "" @app.route("/1") @app.permission_required(["staff"]) def index1(was): return "" @app.route("/animals/<int:id>", methods=["GET", "DELETE"]) @app.permission_required(id=["staff"], DELETE=["admin"]) def index2(was, id=None): return "" @app.route("/animals2/<int:id>", methods=["GET", "DELETE", "PATCH"]) @app.permission_required(id=["staff"]) def index3(was, id=None): return "" with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.status_code == 200 resp = cli.get("/1") assert resp.status_code == 403 resp = cli.get("/animals") assert resp.status_code == 200 resp = cli.get("/animals/me") assert resp.status_code == 200 resp = cli.get("/animals/1") assert resp.status_code == 403 resp = cli.delete("/animals/1") assert resp.status_code == 402 resp = cli.get("/animals2/them") assert resp.status_code == 404 resp = cli.get("/animals2/me") assert resp.status_code == 200 resp = cli.get("/animals2/notme") assert resp.status_code == 403 resp = cli.delete("/animals2/notme") assert resp.status_code == 421 resp = cli.patch("/animals2/notme", {}) assert resp.status_code == 421
def test_params(wasc, app, client): def z(was): k = list(was.request.args.keys()) k.sort() return " ".join(k) @app.route("/do", methods=["GET", "POST"]) def index(was): return z(was) @app.route("/do2", methods=["GET", "POST"]) def index2(was, a): return z(was) @app.route("/do3/<u>", methods=["GET", "POST"]) def index3(was, **args): return z(was) @app.route("/do4/<u>", methods=["GET", "POST"]) def index4(was, u, a, b): return z(was) @app.route("/do5/<u>", methods=["GET", "POST"]) def index5(was, u, a): return z(was) @app.route("/do6", methods=["GET", "POST"]) def index6(was, a): return z(was) # WSGI vh = testutil.install_vhost_handler() root = confutil.getroot() pref = skitai.pref() vh.add_route("default", ("/", app, root), pref) request = client.get("http://www.skitai.com/do") resp = assert_request(vh, request, 200) assert resp.text == "" request = client.get("http://www.skitai.com/do6?a=1") resp = assert_request(vh, request, 200) assert resp.text == "a" request = client.post("http://www.skitai.com/do6", {'a': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a" request = client.postjson("http://www.skitai.com/do6", {'a': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a" request = client.get("http://www.skitai.com/do?a=1") resp = assert_request(vh, request, 200) request = client.post("http://www.skitai.com/do", {'a': 1}) resp = assert_request(vh, request, 200) request = client.postjson("http://www.skitai.com/do", {'a': 1}) resp = assert_request(vh, request, 200) #---------------------------------------- request = client.get("http://www.skitai.com/do2") resp = assert_request(vh, request, 400) request = client.get("http://www.skitai.com/do2?a=1") resp = assert_request(vh, request, 200) assert resp.text == "a" request = client.get("http://www.skitai.com/do2?a=1&b=1") resp = assert_request(vh, request, 400) request = client.post("http://www.skitai.com/do2", {'a': 1, 'b': 1}) resp = assert_request(vh, request, 400) request = client.post("http://www.skitai.com/do2?a=1", {'b': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a b" request = client.post("http://www.skitai.com/do2", {'a': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a" #------------------------------------------ request = client.post("http://www.skitai.com/do3/1", {'a': 1}) resp = assert_request(vh, request, 200) request = client.post("http://www.skitai.com/do4/1?a=1", {'b': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a b u" request = client.post("http://www.skitai.com/do4/1?b=1", {'a': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a b u" request = client.post("http://www.skitai.com/do4/1?b=1", {'a': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a b u" request = client.post("http://www.skitai.com/do5/1?b=1", {'a': 1}) resp = assert_request(vh, request, 400) request = client.post("http://www.skitai.com/do5/1?a=1", {'b': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a b u" request = client.postjson("http://www.skitai.com/do5/1?a=1", {'b': 1}) resp = assert_request(vh, request, 200) assert resp.text == "a b u"
def test_futures (app, dbpath): @app.route ("/") def index (was): def respond (was, rss): return the_was.response.API (status_code = [rs.status_code for rs in rss.dispatch ()], a = rss.a) reqs = [ the_was.get ("@pypi/project/skitai/"), the_was.get ("@pypi/project/rs4/"), the_was.backend ("@sqlite").execute ('SELECT * FROM stocks WHERE symbol=?', ('RHAT',)) ] return the_was.Tasks (reqs, a = 100).then (respond) @app.route ("/3") def index3 (was): def respond (was, rss): datas = str (rss [0].fetch ()) + str (rss [1].one ()) return datas reqs = [ the_was.get ("@pypi/project/rs4/"), the_was.backend ("@sqlite").execute ('SELECT * FROM stocks WHERE symbol=?', ('RHAT',)) ] return the_was.Tasks (reqs).then (respond) @app.route ("/4") def index4 (was): def respond (was, rss): return str (rss [0].one ()) reqs = [ the_was.backend ("@sqlite").execute ('SELECT * FROM stocks WHERE symbol=?', ('---',)) ] return the_was.Tasks (reqs).then (respond) @app.route ("/12") def index12 (was): a = the_was.Tasks ([was.backend ("@sqlite").execute ('SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT',))]) b = the_was.Tasks ([was.backend ("@sqlite").execute ('SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT',))]) a.add (b) return str (a.one ()) @app.route ("/13") def index13 (was): def respond (was, rss): return str (rss.one ()) a = was.Tasks ([the_was.backend ("@sqlite").execute ('SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT',))]) b = was.Tasks ([the_was.backend ("@sqlite").execute ('SELECT symbol FROM stocks WHERE symbol=? limit 1', ('RHAT',))]) a.merge (b) return a.then (respond) app.alias ("@pypi", skitai.PROTO_HTTPS, "pypi.org") app.alias ("@sqlite", skitai.DB_SQLITE3, dbpath) with app.test_client ("/", confutil.getroot ()) as cli: resp = cli.get ("/") assert resp.data ['status_code'] == [200, 200, 200] assert resp.data ['a'] == 100 resp = cli.get ("/3") assert "hansroh" in resp.text assert "RHAT" in resp.text resp = cli.get ("/4") assert resp.status_code == 410 resp = cli.get ("/12") assert resp.data == "[{'symbol': 'RHAT'}, [{'symbol': 'RHAT'}]]" resp = cli.get ("/13") assert resp.data == "[{'symbol': 'RHAT'}, {'symbol': 'RHAT'}]"
def test_error_handler(app): @app.route("/") @app.require("URL", ["limit"]) def index(was, limit): return "" @app.route("/2") @app.require("FORM", ["limit"]) def index2(was, limit): return "" @app.route("/3") @app.require("JSON", ["limit"]) def index3(was, limit): return "" @app.route("/4") @app.require("ARGS", ["limit"]) def index4(was, limit): return "" @app.route("/5") @app.require("ARGS", emails=["email"], uuids=["uuid"]) def index5(was, email=None, uuid=None): return "" @app.route("/6") @app.require("ARGS", a__gte=5, b__between=(-4, -1), c__in=(1, 2)) def index6(was, **url): return "" @app.route("/7") @app.require("ARGS", a=re.compile("^hans"), b__len__between=(4, 8)) def index7(was, a=None, b=None): return "" @app.route("/8") @app.require("DATA", ["limit"]) def index8(was, limit): return "" with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.status_code == 400 resp = cli.get("/?limit=4") assert resp.status_code == 200 resp = cli.get("/2?limit=4") assert resp.status_code == 200 resp = cli.post("/2", {"limit": 4}) assert resp.status_code == 200 resp = cli.post("/2", {}) assert resp.status_code == 400 api = cli.api() resp = api("2").post({"limit": 4}) assert resp.status_code == 400 api = cli.api() resp = api("3").post({"limit": 4}) assert resp.status_code == 200 api = cli.api() resp = api("4").post({"limit": 4}) assert resp.status_code == 200 resp = cli.get("/4?limit=4") assert resp.status_code == 200 resp = cli.post("/4", {"limit": 4}) assert resp.status_code == 200 resp = cli.post("/5", {"email": "*****@*****.**"}) assert resp.status_code == 200 resp = cli.post("/5", {"email": "hansroh@gmail"}) assert resp.status_code == 400 resp = cli.post("/5", {"uuid": "123e4567-e89b-12d3-a456-426655440000"}) assert resp.status_code == 200 resp = cli.post("/5", {"uuid": "123e4567-e89b-12d3-a456-42665544000"}) assert resp.status_code == 400 resp = cli.post("/5", {"uuid": "123e4567-e89b-12d3-g456-426655440000"}) assert resp.status_code == 400 resp = cli.post("/6", {"a": "5"}) assert resp.status_code == 200 resp = cli.post("/6", {"a": "4"}) assert resp.status_code == 400 resp = cli.post("/6", {"b": "-3"}) assert resp.status_code == 200 resp = cli.post("/6", {"b": "4"}) assert resp.status_code == 400 resp = cli.post("/6", {"c": "1"}) assert resp.status_code == 200 resp = cli.post("/6", {"c": "3"}) assert resp.status_code == 400 resp = cli.post("/7", {"a": "hansroh"}) assert resp.status_code == 200 resp = cli.post("/7", {"a": "xxxx"}) assert resp.status_code == 400 resp = cli.post("/7", {"b": "xxxx"}) assert resp.status_code == 200 resp = cli.post("/7", {"b": "xxx"}) assert resp.status_code == 400 resp = cli.api()("7").post({"b": "xxx"}) assert resp.status_code == 400 resp = cli.post("/8", {"limit": 4}) assert resp.status_code == 200 resp = cli.api()("8").post({"limit": 4}) assert resp.status_code == 200
def test_futures(app, dbpath): @app.route("/") def index(was): def respond(was, rss, a): return was.response.API(status_code=[rs.status_code for rs in rss], a=a) reqs = [ was.get("@pypi/project/skitai/"), was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return was.futures(reqs).then(respond, a=100) @app.route("/2") def index2(was): def repond(was, rss, b, status_code): return was.response.API( status_code_db=[rs.status_code for rs in rss], b=b, status_code=status_code) def checkdb(was, rss, a): reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return was.futures(reqs).then( repond, b=a + 100, status_code=[rs.status_code for rs in rss]) def begin(): reqs = [ was.get("@pypi/project/skitai/"), was.get("@pypi/project/rs4/") ] return was.futures(reqs).then(checkdb, a=100) begin() @app.route("/3") def index3(was): def respond(was, rss): datas = str(rss[0].fetch()) + str(rss[1].one()) return datas reqs = [ was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return was.futures(reqs).then(respond) @app.route("/4") def index4(was): def respond(was, rss): rss[0].one() reqs = [ was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('---', )) ] return was.futures(reqs).then(respond) @app.route("/5") def index5(was): reqs = [ was.get("@pypi/project/rs4/"), was.backend("@sqlite").execute( 'SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) ] return str([rs.fetch() for rs in was.Tasks(reqs)]) app.alias("@pypi", skitai.PROTO_HTTPS, "pypi.org") app.alias("@sqlite", skitai.DB_SQLITE3, dbpath) with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.data['status_code'] == [200, 200, 200] assert resp.data['a'] == 100 resp = cli.get("/2") assert resp.data['status_code'] == [200, 200] assert resp.data['status_code_db'] == [200] assert resp.data['b'] == 200 resp = cli.get("/3") assert "hansroh" in resp.text assert "RHAT" in resp.text resp = cli.get("/4") assert resp.status_code == 404 resp = cli.get("/5") assert "hansroh" in resp.text assert "RHAT" in resp.text
def test_cli(app, dbpath): @app.route("/hello") @app.route("/") def index(was): return "Hello, World" @app.route("/petse/<int:id>") def pets_error(was): return "Pets" @app.route("/pets/<int:id>", methods=["GET", "POST"]) def pets(was, id=None): return "Pets{}".format(id) @app.route("/pets2/<int:id>", methods=["POST"]) def pets2(was, id=None): return "Pets{}".format(id) @app.route("/pets3/<int:id>") def pets3(was, id=None): return "Pets{}".format(id) @app.route("/echo") def echo(was, m): return m @app.route("/json") def json(was, m): return was.response.api(data=m) @app.route("/pypi") def pypi(was): req = was.get("@pypi/project/skitai/") res = req.dispatch() return was.response.api(data=res.text) @app.route("/pypi3") def pypi3(was): req = was.getjson("https://pypi.org/project/skitai/") res = req.dispatch() return was.response.api(data=res.text) @app.route("/pypi2") def pypi2(was): req = was.get("https://pypi.org/project/skitai/") res = req.dispatch() return was.response.api(data=res.text) @app.route("/db") def db(was): stub = was.backend("@sqlite") req = stub.execute('SELECT * FROM stocks WHERE symbol=?', ('RHAT', )) res = req.dispatch() return was.response.api(data=res.data) @app.route('/jwt') @app.authorization_required("bearer") def jwt(was): return was.response.api(was.request.JWT) @app.route("/db2") def db2(was): stub = was.db("@sqlite") req = stub.select("stocks").filter(symbol='RHAT').execute() res = req.dispatch() return was.response.api(data=res.data) @app.maintain def increase(was, now, count): if "total-user" in app.store: app.store.set("total-user", app.store.get("total-user") + 100) @app.route("/getval") def getval(was): ret = str(app.store.get("total-user")) return ret app.alias("@pypi", skitai.PROTO_HTTPS, "pypi.org") app.alias("@sqlite", skitai.DB_SQLITE3, dbpath) app.alias("@postgres", skitai.DB_POSTGRESQL, "postgres:[email protected]/coin_core") with app.test_client("/", confutil.getroot()) as cli: resp = cli.get("/") assert resp.text == "Hello, World" resp = cli.get("/hello") assert resp.text == "Hello, World" resp = cli.get("/petse/1") assert resp.status_code == 530 resp = cli.get("/pets/1") assert resp.status_code == 200 assert resp.text == "Pets1" resp = cli.post("/pets", {"a": 1}) assert resp.status_code == 200 assert resp.text == "PetsNone" resp = cli.get("/pets") assert resp.status_code == 200 resp = cli.get("/pets2/1") assert resp.status_code == 405 resp = cli.post("/pets2/1", {"id": 1}) assert resp.status_code == 200 resp = cli.post("/pets2", {"a": 1}) assert resp.status_code == 200 assert resp.text == "PetsNone" resp = cli.get("/pets2") assert resp.status_code == 405 resp = cli.get("/pets3") assert resp.text == "PetsNone" resp = cli.get("/pets3/1") print(resp) assert resp.text == "Pets1" resp = cli.get("/echo?m=GET") assert resp.text == "GET" resp = cli.post("/json", {"m": "POST"}) assert '"data": "POST"' in resp.text resp = cli.post("/json", {"m": "POST"}) assert '"data": "POST"' in resp.text resp = cli.get("/db2") assert resp.data["data"][0]['symbol'] == 'RHAT' resp = cli.get("/db") assert resp.data["data"][0]['symbol'] == 'RHAT' resp = cli.get("/pypi3") assert resp.status_code == 502 resp = cli.get("/pypi2") assert "skitai" in resp.text resp = cli.get("/pypi") assert "skitai" in resp.text app.securekey = "securekey" resp = cli.get("/jwt", headers={ "Authorization": "Bearer {}".format( jwt_.gen_token(app.salt, { "exp": 3000000000, "username": "******" })) }) assert resp.data == {'exp': 3000000000, 'username': '******'} resp = cli.get("/jwt", headers={ "Authorization": "Bearer {}".format( jwt_.gen_token(app.salt, { "exp": 1, "username": "******" })) }) assert resp.code == 401 assert resp.get_header( "WWW-Authenticate") == 'Bearer realm="App", error="token expired"' app.securekey = None app.config.maintain_interval = 1 app.store.set("total-user", 100) time.sleep(2) resp = cli.get("/getval") assert int(resp.text) >= 200
def test_producers(client): def g(): for i in range(10): yield ("A" * 10).encode("utf8") def l(): return ([("A" * 10).encode("utf8")] * 10) class s: def __init__(self): self.d = list(range(10)) self.closed = 0 def close(self): self.closed = 1 def read(self, size): if not self.d: return b"" self.d.pop() return ("A" * size).encode("utf8") response = make_response(client) jpg = open(os.path.join(confutil.getroot(), "statics", "reindeer.jpg"), "rb") response("200 OK", "", headers=[("Content-Type", "application/octet-stream")]) response.push_and_done(producers.file_producer(jpg)) assert response.get("content-encoding") is None assert response.get("transfer-encoding") == "chunked" assert jpg.closed response = make_response(client) response("200 OK", "", headers=[("Content-Type", "text/html")]) response.push_and_done(producers.iter_producer(g())) assert response.get("content-encoding") == "gzip" assert response.get("transfer-encoding") == "chunked" response = make_response(client) response("200 OK", "", headers=[("Content-Type", "text/html")]) response.push_and_done(producers.list_producer(l())) assert response.get("content-encoding") is None assert response.get("transfer-encoding") == "chunked" response = make_response(client) response("200 OK", "", headers=[("Content-Type", "text/html")]) producer = s() response.push_and_done(producers.closing_stream_producer(producer)) assert response.get("content-encoding") == "gzip" assert response.get("transfer-encoding") == "chunked" assert producer.closed response = make_response(client) response("200 OK", "", headers=[("Content-Type", "text/html")]) jpg = open(os.path.join(confutil.getroot(), "statics", "reindeer.jpg"), "rb") response.push(producers.closing_stream_producer(s())) response.push(producers.list_producer(l())) response.push(producers.iter_producer(g())) response.push(producers.file_producer(jpg)) response.done() assert response.get("content-encoding") == "gzip" assert response.get("transfer-encoding") == "chunked" assert producer.closed assert jpg.closed response = make_response(client) response("200 OK", "", headers=[("Content-Type", "text/html")]) jpg = open(os.path.join(confutil.getroot(), "statics", "reindeer.jpg"), "rb") response.push(producers.closing_stream_producer(s())) response.push(producers.list_producer(l())) response.push(producers.iter_producer(g())) response.push(producers.file_producer(jpg)) response.done() response = make_response(client, version="2.0") response("200 OK", "", headers=[("Content-Type", "text/html")]) jpg = open(os.path.join(confutil.getroot(), "statics", "reindeer.jpg"), "rb") conn = MagicMock() conn.data_to_send.return_value = jpg.read() p = h2frame_producer(1, 0, 1, producers.file_producer(jpg), conn, threading.Lock()) response.push_and_done(p) assert response.get("content-encoding") is None rprint(response.reply_headers) assert response.get("transfer-encoding") is None
def test_was (wasc, app, client): @app.route ("/do6/<u>") def index6 (was, u = "hansroh"): return z (was) @app.route ("/index5/<u>") def index5 (was, u, a, b = 3): return z (was) @app.route ("/index7/<u>") @app.authorization_required ("digest") def index7 (was, u, a, b = 3): return z (was) # WSGI vh = testutil.install_vhost_handler () root = confutil.getroot () pref = skitai.pref () vh.add_route ("default", ("/", app, root), pref) was = wasc () was.app = app for each in ("index5", "index7"): assert was.urlfor (each, "hans", "roh") == "/{}/hans?a=roh".format (each) assert was.urlfor (each, "hans", "roh") == "/{}/hans?a=roh".format (each) assert was.baseurl (each) == "/{}/".format (each) assert was.urlfor (each, "hans", "roh", b = 3) in ("/{}/hans?b=3&a=roh".format (each), "/{}/hans?a=roh&b=3".format (each)) assert was.urlfor (each, "hans", a = "roh", b = 3) in ("/{}/hans?b=3&a=roh".format (each), "/{}/hans?a=roh&b=3".format (each)) with pytest.raises(AssertionError): assert was.ab (each, b = 3) was.request = client.get ("http://www.skitai.com/{}/hans?a=roh".format (each)) was.request.args = {"u": "hans", "a": "roh"} assert was.partial (each, a = "vans") == "/{}/hans?a=vans".format (each) assert was.partial (each, b = 3) in ("/{}/hans?b=3&a=roh".format (each), "/{}/hans?a=roh&b=3".format (each)) assert was.urlfor ("index6") == "/do6" assert was.urlfor ("index6", "jenny") == "/do6/jenny" assert was.urlfor ("index6", u = "jenny") == "/do6/jenny" was.request.args = {"u": "hans"} assert was.partial ("index6") == "/do6/hans" assert was.gentemp ().startswith ("/var/tmp") was.add_cluster (skitai.PROTO_HTTP, "@test", "127.0.0.1:5000") assert "@test" in was.clusters_for_distcall was.add_cluster (skitai.PROTO_HTTP, "@test-1", "127.0.0.1:5000 10") assert "@test-1" in was.clusters_for_distcall was.add_cluster (skitai.PROTO_HTTP, "@test-1", ["127.0.0.1:5000 10"]) assert "@test-1" in was.clusters_for_distcall assert len (str (was.timestamp)) == 13 assert len (was.uniqid) == 20 with pytest.raises(AssertionError): was.session del was.cookie app.securekey = "securekey" assert isinstance (was.cookie, Cookie) assert isinstance (was.session, NamedSession) assert isinstance (was.mbox, NamedSession) assert was.txnid ().endswith ("/1000") assert was.rebuild_header ({}, "get") ["X-Ltxn-Id"] == "1001" x = was.rebuild_header ({"a": "b"}, "get") assert "a" in x assert x ["X-Ltxn-Id"] == "1002" x = was.rebuild_header ([("a", "b")], "get") assert "a" in x assert x ["X-Ltxn-Id"] == "1003" assert was.tempfile.find ("skitai-gentemp") > 0 class Response: def __init__ (self, *args): self.args = args was.response = Response r = was.redirect ("/to") assert r.args [0].startswith ("302 ") assert r.args [1].startswith ("<html>") assert ('Location', '/to') in r.args [2] was.render ("index.html").startswith ('<!DOCTYPE html>') assert isinstance (was.email ("test", "*****@*****.**", "*****@*****.**"), composer.Composer) # tokens ------------------------------------------ assert was.dejwt (was.mkjwt ({"a": 1, "exp": 3000000000})) == {"a": 1, "exp": 3000000000} assert was.dejwt (was.mkjwt ({"a": 1, "exp": 1})) == {'err': 'token expired'} t = was.mktoken ({"a": 1}) assert was.detoken (t) == {"a": 1} t = was.mktoken ({"a": 1}, session_key = "test") assert was.session ["_test_token"] assert was.detoken (t) == {"a": 1} was.session ["_test_token"] = 0x00 assert was.detoken (t) is None assert was.session ["_test_token"] is None t = was.mktoken ({"a": 1}, session_key = "test") assert was.detoken (t) == {"a": 1} was.rmtoken (t) assert was.session ["_test_token"] is None assert was.detoken (t) is None t = was.mktoken ([1, 2]) assert was.detoken (t) == [1, 2] t = was.csrf_token was.csrf_token_input.find (was.session [was.CSRF_NAME]) > 0 class Request: args = {was.CSRF_NAME: t} was.request = Request was.request.args [was.CSRF_NAME] = 0x00 assert not was.csrf_verify (True) was.request.args [was.CSRF_NAME] = t assert was.csrf_verify (True) assert was.session [was.CSRF_NAME] == t assert was.csrf_verify () assert was.session [was.CSRF_NAME] is None with pytest.raises(AttributeError): was.django