79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
import unittest
|
|
import threading
|
|
import subprocess
|
|
import time
|
|
import os
|
|
import signal
|
|
import requests
|
|
|
|
server_process = None
|
|
API_URL = "http://localhost:7000/api"
|
|
def setUpModule():
|
|
"""Start the API server in a separate process before running tests"""
|
|
def run_server():
|
|
global server_process
|
|
# Needet to get python3 dir
|
|
env = os.environ.copy()
|
|
env.update({
|
|
"DATABASE_URL": "sqlite:///./data/TEST.sqlite",
|
|
"CREATE_OPTIONAL_DEFAULT_USER": "true"
|
|
})
|
|
|
|
server_process = subprocess.Popen(
|
|
["python3", "-m", "simple_chat_api"],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
env=env
|
|
)
|
|
|
|
# Start server in a separate thread
|
|
server_thread = threading.Thread(target=run_server)
|
|
server_thread.daemon = True
|
|
server_thread.start()
|
|
|
|
# Wait for server to start
|
|
time.sleep(2)
|
|
|
|
def tearDownModule():
|
|
global server_process
|
|
"""Kill the API server after all tests have executed"""
|
|
if server_process:
|
|
server_process.send_signal(signal.SIGTERM)
|
|
server_process.wait()
|
|
|
|
class TestServer(unittest.TestCase):
|
|
|
|
def test_online(self):
|
|
"""Test if the server is running"""
|
|
response = requests.get(API_URL)
|
|
self.assertEqual(response.status_code, 404, "Server is not running or not reachable")
|
|
|
|
|
|
class TestAuthEndpoints(unittest.TestCase):
|
|
def __init__(self, methodName = "runTest"):
|
|
super().__init__(methodName)
|
|
self.users = {
|
|
"admin": "admin",
|
|
"max": "12345"
|
|
}
|
|
self.userSessions = {}
|
|
|
|
def test_get_token(self):
|
|
"""Test the /token endpoint"""
|
|
for user,password in self.users.items():
|
|
with self.subTest(user=user):
|
|
self.userSessions[user] = requests.Session()
|
|
response = self.userSessions[user].post(f"{API_URL}/user/token", json={
|
|
"user": user,
|
|
"password": password
|
|
})
|
|
self.assertEqual(response.status_code, 200, f"Failed to get token for user {user}; {response.text}")
|
|
data = response.json()
|
|
excepted = {
|
|
"sub": {
|
|
"user": user,
|
|
"role": "admin" if user == "admin" else "user"
|
|
},
|
|
}
|
|
self.assertEqual(data["sub"], excepted["sub"], f"Token content mismatch for user {user}")
|