| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import shutil |
| 5 |
import threading |
| 6 |
import typing |
| 7 |
import wsgiref.simple_server |
| 8 |
from pathlib import Path |
| 9 |
from typing import Any |
| 10 |
|
| 11 |
import bottle |
| 12 |
import pytest |
| 13 |
|
| 14 |
if typing.TYPE_CHECKING: |
| 15 |
import wsgiref.types # added in 3.11 |
| 16 |
|
| 17 |
|
| 18 |
@pytest.fixture(scope="function") |
| 19 |
def testing_workdir(tmpdir, request): |
| 20 |
"""Create a workdir in a safe temporary folder; cd into dir above before test, cd out after |
| 21 |
|
| 22 |
:param tmpdir: py.test fixture, will be injected |
| 23 |
:param request: py.test fixture-related, will be injected (see pytest docs) |
| 24 |
""" |
| 25 |
|
| 26 |
saved_path = os.getcwd() |
| 27 |
|
| 28 |
tmpdir.chdir() |
| 29 |
# temporary folder for profiling output, if any |
| 30 |
tmpdir.mkdir("prof") |
| 31 |
|
| 32 |
def return_to_saved_path(): |
| 33 |
if os.path.isdir(os.path.join(saved_path, "prof")): |
| 34 |
profdir = tmpdir.join("prof") |
| 35 |
files = profdir.listdir("*.prof") if profdir.isdir() else [] |
| 36 |
|
| 37 |
for f in files: |
| 38 |
shutil.copy(str(f), os.path.join(saved_path, "prof", f.basename)) |
| 39 |
os.chdir(saved_path) |
| 40 |
|
| 41 |
request.addfinalizer(return_to_saved_path) |
| 42 |
|
| 43 |
return str(tmpdir) |
| 44 |
|
| 45 |
|
| 46 |
datadir = Path(__file__).parent / "data" |
| 47 |
|
| 48 |
|
| 49 |
@bottle.route("/<filename>", "GET") |
| 50 |
def serve_file(filename): |
| 51 |
mimetype = "auto" |
| 52 |
# from https://repo.anaconda.com/ behavior: |
| 53 |
if filename.endswith(".tar.bz2"): |
| 54 |
mimetype = "application/x-tar" |
| 55 |
elif filename.endswith(".conda"): |
| 56 |
mimetype = "binary/octet-stream" |
| 57 |
return bottle.static_file(filename, root=datadir.as_posix(), mimetype=mimetype) |
| 58 |
|
| 59 |
|
| 60 |
class ServerThread(threading.Thread): |
| 61 |
server: Any |
| 62 |
app: Any |
| 63 |
|
| 64 |
|
| 65 |
def get_server_thread(): |
| 66 |
""" |
| 67 |
Return test server thread with additional .server, .app properties. |
| 68 |
|
| 69 |
Call .start() to serve in the background. |
| 70 |
""" |
| 71 |
app: wsgiref.types.WSGIApplication = bottle.app() |
| 72 |
server = wsgiref.simple_server.make_server("127.0.0.1", 0, app) |
| 73 |
t = ServerThread(daemon=True, target=server.serve_forever) |
| 74 |
t.app = app |
| 75 |
t.server = server # server.application == app |
| 76 |
return t |
| 77 |
|
| 78 |
|
| 79 |
@pytest.fixture(scope="session") |
| 80 |
def localserver(): |
| 81 |
thread = get_server_thread() |
| 82 |
thread.start() |
| 83 |
yield f"http://{thread.server.server_address[0]}:{thread.server.server_address[1]}" |
| 84 |
|
| 85 |
|
| 86 |
if __name__ == "__main__": |
| 87 |
bottle.run(port=8080) |