78 lines
2.6 KiB
Python
78 lines
2.6 KiB
Python
import threading
|
|
|
|
import jwt
|
|
import uvicorn
|
|
|
|
from config import Config
|
|
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_create_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/chat', json={'name': 'test_chat'}, headers={'Authorization': f'Bearer {token}'})
|
|
print(resp.json())
|
|
assert resp.status_code == 201
|
|
assert 'id' in resp.json()
|
|
assert resp.json()['id'] > 0
|
|
assert 'name' in resp.json()
|
|
assert resp.json()['name'] == 'test_chat'
|
|
|
|
|
|
def test_user_chats():
|
|
resp = client.post('/api/v1/auth', json={'username': 1})
|
|
token = resp.json()['access_token']
|
|
resp = client.get('/api/v1/chat', headers={'Authorization': f'Bearer {token}'})
|
|
assert resp.status_code == 200
|
|
assert isinstance(resp.json(), list)
|
|
|
|
|
|
def test_user_forbidden_chat():
|
|
resp = client.post('/api/v1/auth', json={'username': 1})
|
|
token = resp.json()['access_token']
|
|
resp = client.get('/api/v1/chat/1', headers={'Authorization': f'Bearer {token}'})
|
|
assert resp.status_code == 403
|
|
|
|
|
|
def test_user_retrieve_chat():
|
|
resp = client.post('/api/v1/auth', json={'username': 1})
|
|
token = resp.json()['access_token']
|
|
resp = client.get('/api/v1/chat', headers={'Authorization': f'Bearer {token}'})
|
|
resp = client.get(f"/api/v1/chat/{resp.json()[0]['id']}", headers={'Authorization': f'Bearer {token}'})
|
|
assert resp.status_code == 200
|
|
|
|
|
|
def test_not_found_chat():
|
|
resp = client.post('/api/v1/auth', json={'username': 1})
|
|
token = resp.json()['access_token']
|
|
resp = client.get(f"/api/v1/chat/-1", headers={'Authorization': f'Bearer {token}'})
|
|
assert resp.status_code == 404
|
|
|
|
|
|
# Testing auth tokens
|
|
|
|
def test_create_chat_no_token():
|
|
resp = client.post(f"/api/v1/chat", json={'name': 'chat no token'})
|
|
assert resp.status_code == 422
|
|
|
|
|
|
def test_create_chat_invalid_token():
|
|
resp = client.post(f"/api/v1/chat", json={'name': 'chat invalid token'}, headers={'Authorization': 'Bearer 123'})
|
|
assert resp.status_code == 401
|
|
|
|
|
|
def test_create_chat_expired_token():
|
|
token = jwt.encode({'user_id': 1, "exp": 1715940028}, Config.secret, algorithm='HS256')
|
|
resp = client.post(f"/api/v1/chat", json={'name': 'chat expired token'}, headers={f"Authorization": f"Bearer {token}"})
|
|
assert resp.status_code == 401 |