2022-06-03 11:52:18 -04:00
|
|
|
"""Fixture for setting up a single server."""
|
|
|
|
|
|
|
|
from asyncio import create_subprocess_exec, get_event_loop, sleep
|
|
|
|
from pathlib import Path
|
2022-06-11 18:10:23 -04:00
|
|
|
from socket import socket
|
|
|
|
|
2022-06-03 11:52:18 -04:00
|
|
|
|
|
|
|
class Server:
|
|
|
|
"""Setup a single server."""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
"""Initialization of a server."""
|
2022-06-07 13:53:13 -04:00
|
|
|
self.env = {}
|
2022-06-03 11:52:18 -04:00
|
|
|
self.process = None
|
|
|
|
self.loop = get_event_loop()
|
|
|
|
|
2022-06-07 13:53:13 -04:00
|
|
|
@property
|
|
|
|
def address(self):
|
|
|
|
"""Get the server address."""
|
|
|
|
address = "127.0.0.1"
|
|
|
|
if "MMT_ADDRESS" in self.env:
|
|
|
|
address = self.env["MMT_ADDRESS"]
|
|
|
|
return address
|
|
|
|
|
|
|
|
@address.setter
|
|
|
|
def address(self, addr):
|
|
|
|
"""Sets the server address."""
|
|
|
|
self.env["MTT_ADDRESS"] = addr
|
|
|
|
|
|
|
|
@property
|
|
|
|
def port(self):
|
|
|
|
"""Get the port of the server."""
|
2022-06-12 09:07:06 -04:00
|
|
|
port = "9090"
|
2022-06-07 13:53:13 -04:00
|
|
|
if "MTT_PORT" in self.env:
|
|
|
|
port = self.env["MTT_PORT"]
|
|
|
|
return port
|
|
|
|
|
|
|
|
@port.setter
|
|
|
|
def port(self, num):
|
|
|
|
"""Set the port for the server."""
|
2022-06-11 18:10:23 -04:00
|
|
|
self.env["MTT_PORT"] = str(num)
|
2022-06-07 13:53:13 -04:00
|
|
|
|
2022-06-03 11:52:18 -04:00
|
|
|
async def __start(self):
|
|
|
|
"""async start of the server."""
|
2022-06-11 18:10:23 -04:00
|
|
|
print(self.env)
|
2022-06-03 11:52:18 -04:00
|
|
|
self.process = await create_subprocess_exec(
|
2022-06-11 18:10:23 -04:00
|
|
|
Path.cwd().joinpath("target", "release", "morethantext_web"), env=self.env
|
|
|
|
)
|
2022-06-03 11:52:18 -04:00
|
|
|
await sleep(1)
|
|
|
|
|
|
|
|
async def __stop(self):
|
|
|
|
"""async stop of the server."""
|
|
|
|
if self.process is not None and self.process.returncode is None:
|
|
|
|
self.process.terminate()
|
|
|
|
await self.process.wait()
|
|
|
|
|
|
|
|
def start(self):
|
|
|
|
"""Start the server."""
|
|
|
|
self.loop.run_until_complete(self.__start())
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
"""Stop the server."""
|
|
|
|
self.loop.run_until_complete(self.__stop())
|
|
|
|
|
|
|
|
def destroy(self):
|
|
|
|
"""Removes the server instance."""
|
|
|
|
self.stop()
|
2022-06-11 18:10:23 -04:00
|
|
|
|
|
|
|
def set_safe_port(self):
|
|
|
|
"""Set the server port to something not being used."""
|
2022-06-12 09:07:06 -04:00
|
|
|
while self.port == "9090":
|
|
|
|
sock = socket()
|
|
|
|
sock.bind((self.address, 0))
|
|
|
|
self.port = sock.getsockname()[1]
|
|
|
|
sock.close()
|