Debian Codegraph @

tests/server.py

raw
1 """
2 Test web server.
3 """
4
5 import logging
6 import threading
7 import wsgiref.simple_server
8 from pathlib import Path
9 from typing import Any
10
11 import bottle
12 import conftest
13
14 log = logging.getLogger(__name__)
15
16
17 def get_app(pkgs_dir):
18 """
19 Bottle conveniently supports Range requests.
20
21 Server may block if browser etc. keeps connection open.
22 """
23 app = bottle.Bottle()
24 app.pkgs_dir = pkgs_dir
25
26 def serve_file(filename):
27 mimetype = "auto"
28 # from https://repo.anaconda.com/ behavior:
29 if filename.endswith(".tar.bz2"):
30 mimetype = "application/x-tar"
31 elif filename.endswith(".conda"):
32 mimetype = "binary/octet-stream"
33 return bottle.static_file(filename, root=pkgs_dir, mimetype=mimetype)
34
35 app.route("/pkgs/<filename>", "GET", serve_file)
36 return app
37
38
39 def selftest():
40 """
41 Run server in a thread that will die when the application exits.
42 """
43 t = get_server_thread(conftest.find_packages_dirs())
44 t.start()
45
46 import time
47
48 time.sleep(300)
49
50
51 class ServerThread(threading.Thread):
52 server: wsgiref.simple_server.WSGIServer
53 app: Any
54
55
56 def get_server_thread(pkgs_dir: Path):
57 """
58 Return test server thread with additional .server, .app properties.
59
60 Call .start() to serve in the background.
61 """
62 app = get_app(pkgs_dir)
63 server = wsgiref.simple_server.make_server("127.0.0.1", 0, app)
64 log.info(f"serving {app.pkgs_dir} on {server.server_address}/pkgs")
65 t = ServerThread(daemon=True, target=server.serve_forever)
66 t.app = app
67 t.server = server # server.application == app
68 return t
69
70
71 if __name__ == "__main__":
72 import logging
73
74 logging.basicConfig(
75 level=logging.INFO,
76 format="%(asctime)s %(message)s",
77 datefmt="%Y-%m-%dT%H:%M:%S",
78 )
79 log.setLevel(logging.DEBUG)
80 selftest()