import threading import time import pytest import uvicorn from faker import Faker from main import app from httpx import Client server_thread = threading.Thread(target=uvicorn.run, args=(app,), daemon=True, kwargs={"host": "127.0.0.1", "port": 8000, "reload": False}) server_thread.start() client = Client(base_url="http://127.0.0.1:8000", timeout=60 * 60 * 60) def test__message_send(): # Complete authorization resp = client.post('/api/v1/auth', json={'username': 1}) assert resp.status_code == 200 token = resp.json()['access_token'] chat_id = client.get('/api/v1/chat', headers={'Authorization': f'Bearer {token}'}).json()[0]["id"] resp = client.post('/api/v1/message', json={ "chat_id": chat_id, "content": "test__message_send"}, headers={'Authorization': f'Bearer {token}'}) assert resp.status_code == 201 assert resp.json()["content"] == "test__message_send" assert resp.json()["id"] > 0 def test__message_send_without_auth(): resp = client.post('/api/v1/message', json={ "chat_id": 70, "content": "test__message_send_without_auth"}, headers={'Authorization': f'Bearer 123'}) assert resp.status_code == 401 def test__message_send_without_chat(): # Complete authorization resp = client.post('/api/v1/auth', json={'username': 1}) assert resp.status_code == 200 token = resp.json()['access_token'] resp = client.post('/api/v1/message', json={ "chat_id": -1, "content": "test__message_send_without_chat"}, headers={'Authorization': f'Bearer {token}'}) assert resp.status_code == 404 @pytest.mark.skip(reason="Stress test. Should be run separately") def test_stress(): # Complete authorization resp = client.post('/api/v1/auth', json={'username': 1}) fake = Faker() assert resp.status_code == 200 token = resp.json()['access_token'] chat_id = client.get('/api/v1/chat', headers={'Authorization': f'Bearer {token}'}).json()[0]["id"] for i in range(10000): text = fake.text() start = time.time() * 1000 resp = client.post('/api/v1/message', json={ "chat_id": chat_id, "content": text}, headers={'Authorization': f'Bearer {token}'}) _ = client.get(f'/api/v1/message', headers={'Authorization': f'Bearer {token}'}, params={"chat_id": chat_id}) end = time.time() * 1000 print(f"Time: {end - start}") assert end - start < 100 assert resp.status_code == 201 assert resp.json()["content"] == text assert resp.json()["id"] > 0