87 lines
2.8 KiB
Python
87 lines
2.8 KiB
Python
import pytest
|
|
from datetime import datetime
|
|
from app import create_app, db
|
|
from app.models import Agent, User, ChatLog
|
|
|
|
@pytest.fixture
|
|
def client():
|
|
app = create_app('testing')
|
|
app.config['TESTING'] = True
|
|
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
|
|
|
|
with app.test_client() as client:
|
|
with app.app_context():
|
|
db.create_all()
|
|
# Create user and agent
|
|
user = User(username='testuser', role='user', email='test@example.com')
|
|
db.session.add(user)
|
|
|
|
agent = Agent(name='Test Agent', type='api')
|
|
db.session.add(agent)
|
|
user.agents.append(agent)
|
|
|
|
db.session.flush()
|
|
|
|
# Add some chat logs
|
|
log1 = ChatLog(
|
|
user_id=user.id, agent_id=agent.id,
|
|
conversation_id='conv1',
|
|
query='Hi', answer='Hello',
|
|
created_at=datetime(2026, 1, 1)
|
|
)
|
|
db.session.add(log1)
|
|
|
|
db.session.commit()
|
|
|
|
yield client
|
|
|
|
db.session.remove()
|
|
db.drop_all()
|
|
|
|
def get_headers(client):
|
|
return {
|
|
'X-User-Id': '1',
|
|
'X-Username': 'testuser',
|
|
'X-Role': 'user',
|
|
'Content-Type': 'application/json'
|
|
}
|
|
|
|
def test_chat_history_with_query_param(client):
|
|
"""
|
|
Verify that /api/chat/sessions accepts agent_id as query parameter
|
|
(This tests the fix in decorators.py)
|
|
"""
|
|
headers = get_headers(client)
|
|
|
|
# 1. Test without agent_id (Should fail with 400)
|
|
res = client.get('/api/chat/sessions', headers=headers)
|
|
assert res.status_code == 400
|
|
assert 'agent_id is required' in res.get_json()['error']
|
|
|
|
# 2. Test with agent_id in query string (Should succeed)
|
|
res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
|
|
assert res.status_code == 200
|
|
data = res.get_json()
|
|
assert len(data) == 1
|
|
assert data[0]['conversation_id'] == 'conv1'
|
|
|
|
# 3. Test with agent_id in JSON body (Should still work if GET allows body, but requests/fetch usually don't)
|
|
# Flask test client allows GET with body
|
|
res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': 1})
|
|
assert res.status_code == 200
|
|
assert len(res.get_json()) == 1
|
|
|
|
def test_chat_messages_history(client):
|
|
"""
|
|
Verify getting messages for a conversation
|
|
"""
|
|
headers = get_headers(client)
|
|
|
|
# Need agent_id now
|
|
res = client.get('/api/chat/messages?conversation_id=conv1&agent_id=1', headers=headers)
|
|
assert res.status_code == 200
|
|
msgs = res.get_json()
|
|
assert len(msgs) == 2 # User + Assistant
|
|
assert msgs[0]['content'] == 'Hi'
|
|
assert msgs[1]['content'] == 'Hello'
|