サーバーがバックグラウンドで実行されているときにテストを起動するコンテキストマネージャーを作成できます。
if __name__ == '__main__':
with background_server():
print('Server loaded, launching the tests...')
unittest.main(exit=False)
私が使用するコードbackground_server
:
@contextlib.contextmanager
def background_server():
# Launching the server
pid_server = os.fork()
if not pid_server: # Child code
launch_server() # Blocking call (until signal.SIGINT)
print('Interuption detected, server closed...')
sys.exit() # Closing the process
# HACK: Wait for the server to be launched
while True:
try:
requests.get("http://localhost:5000/", timeout=0.5)
break
except requests.exceptions.ConnectionError:
pass
time.sleep(0.3)
try:
yield
finally:
# Closing the server
os.kill(pid_server, signal.SIGINT)