我正在后台线程中启动 Waitress Web 服务器以运行功能测试。如何以干净(ish)的方式在测试运行结束时清理和退出女服务员?公共女服务员 API 仅提供一种方式入口点,期望KeyboardInterrupt
作为退出信号。
目前我只是在守护线程中运行服务器,所有新的 Web 服务器都在等待清理,直到测试运行程序退出。
我的测试网络服务器代码:
"""py.test fixtures for spinning up a WSGI server for functional test run."""
import threading
import time
from pyramid.router import Router
from waitress import serve
from urllib.parse import urlparse
import pytest
from backports import typing
#: The URL where WSGI server is run from where Selenium browser loads the pages
HOST_BASE = "http://localhost:8521"
class ServerThread(threading.Thread):
"""Run WSGI server on a background thread.
This thread starts a web server for a given WSGI application. Then the Selenium WebDriver can connect to this web server, like to any web server, for running functional tests.
"""
def __init__(self, app:Router, hostbase:str=HOST_BASE):
threading.Thread.__init__(self)
self.app = app
self.srv = None
self.daemon = True
self.hostbase = hostbase
def run(self):
"""Start WSGI server on a background to listen to incoming."""
parts = urlparse(self.hostbase)
domain, port = parts.netloc.split(":")
try:
# TODO: replace this with create_server call, so we can quit this later
serve(self.app, host='127.0.0.1', port=int(port))
except Exception as e:
# We are a background thread so we have problems to interrupt tests in the case of error. Try spit out something to the console.
import traceback
traceback.print_exc()
def quit(self):
"""Stop test webserver."""
# waitress has no quit
# if self.srv:
# self.srv.shutdown()