lazy_serve/test_lazy_serve.py

47 lines
1.3 KiB
Python
Raw Normal View History

2024-01-25 16:39:48 +00:00
import os
import subprocess
import tempfile
import time
from multiprocessing import Process
import pytest
from lazy_serve import serve # Replace with the name of your script
@pytest.fixture(scope="module")
def server_directories():
temp_dirs = []
for _ in range(2):
temp_dir = tempfile.TemporaryDirectory()
index_path = os.path.join(temp_dir.name, "index.html")
with open(index_path, "w") as file:
file.write("<html><body>Hello World</body></html>")
temp_dirs.append((9090 + len(temp_dirs), temp_dir))
yield [(port, dir.name) for port, dir in temp_dirs]
for _, temp_dir in temp_dirs:
temp_dir.cleanup()
@pytest.mark.parametrize("handle_signals", (True, False))
def test_serve(server_directories, handle_signals):
args = (server_directories, handle_signals)
server_process = Process(target=serve, args=args)
server_process.start()
time.sleep(3) # Allow servers to start
server_process.terminate()
server_process.join()
for port, _ in server_directories:
with pytest.raises(subprocess.CalledProcessError):
subprocess.check_call(
["python", "-m", "http.server", str(port)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if __name__ == "__main__":
test_serve(server_directories())