feat: Initial commit with full deployment architecture and scripts

This commit is contained in:
super committed 2026-02-24 16:45:11 +08:00
commit abb3efe114
96 files changed
+16789

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
import pytest
from app import create_app, db
from app.models import User
@pytest.fixture
def app():
app = create_app('testing')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def admin_headers():
return {
'X-Username': 'admin',
'X-Role': 'admin',
'Content-Type': 'application/json'
}
@pytest.fixture
def user_headers():
return {
'X-Username': 'user',
'X-Role': 'user',
'Content-Type': 'application/json'
}
+71
View File
@@ -0,0 +1,71 @@
import requests
import json
import sys
BASE_URL = "http://127.0.0.1:5001/api"
HEADERS = {
"X-Username": "admin",
"X-Role": "admin",
"Content-Type": "application/json"
}
def test_create_iframe_agent():
print("\n--- Testing Iframe Agent Creation ---")
payload = {
"name": "Test Iframe Agent",
"type": "iframe",
"description": "Auto-test Iframe Agent",
"extra_config": {
"iframe_url": "http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg"
}
}
try:
response = requests.post(f"{BASE_URL}/admin/agents", headers=HEADERS, json=payload)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
if response.status_code == 201:
print("SUCCESS: Iframe Agent created")
return response.json()['id']
else:
print("FAILURE: Could not create Iframe Agent")
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
def test_create_api_agent():
print("\n--- Testing API Agent Creation ---")
payload = {
"name": "Test API Agent",
"type": "api",
"description": "Auto-test API Agent",
"dify_app_id": "test-app-id-123", # Dummy ID for testing constraint
"dify_api_key": "app-xdiejQibWQy8ZQWXcdxJjS9I",
"api_base_url": "http://127.0.0.1:5001/v1"
}
try:
response = requests.post(f"{BASE_URL}/admin/agents", headers=HEADERS, json=payload)
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
if response.status_code == 201:
print("SUCCESS: API Agent created")
return response.json()['id']
else:
# Handle unique constraint if it already exists from previous run
if "integrity error" in response.text.lower() or "unique" in response.text.lower():
print("WARNING: Agent likely already exists (Integrity Error).")
else:
print("FAILURE: Could not create API Agent")
sys.exit(1)
except Exception as e:
print(f"ERROR: {e}")
sys.exit(1)
if __name__ == "__main__":
iframe_id = test_create_iframe_agent()
api_id = test_create_api_agent()
print("\nAll automated tests passed!")
+112
View File
@@ -0,0 +1,112 @@
import pytest
from app import create_app, db
from app.models import Agent, User
import json
@pytest.fixture
def client():
# Use 'testing' config to ensure SQLite in-memory DB is used
app = create_app('testing')
with app.app_context():
db.create_all()
# Create admin user for auth
# Ensure all required fields are provided
admin = User(
username='admin',
email='admin@example.com',
role='admin'
)
admin.set_password('admin')
db.session.add(admin)
db.session.commit()
yield app.test_client()
db.session.remove()
db.drop_all()
def get_headers():
return {
'X-Username': 'admin',
'X-Role': 'admin',
'Content-Type': 'application/json'
}
def test_create_iframe_agent(client):
"""
Test creating an Iframe agent with user provided data.
"""
data = {
"name": "Test Iframe Agent",
"type": "iframe",
"description": "Auto-test Iframe Agent",
"iframe_url": "http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg"
}
# Frontend logic: extra_config = { iframe_url: ... }
payload = {
"name": data["name"],
"type": data["type"],
"description": data["description"],
"dify_app_id": "", # Frontend sends empty string
"dify_api_key": "", # Frontend sends empty string
"extra_config": {
"iframe_url": data["iframe_url"]
}
}
response = client.post('/api/admin/agents', json=payload, headers=get_headers())
assert response.status_code == 201, f"Failed to create Iframe agent: {response.text}"
resp_data = response.get_json()
assert 'id' in resp_data
# Verify DB
# Need to access DB within app context or use client application context if possible
# But db.session is bound to the app context.
# We can use client.application.app_context() if needed, but db.session should work if we are in the same thread/process and using shared memory (for sqlite).
# Since we yielded app.test_client(), the app context in fixture is gone.
# But we can access the app from client.application
with client.application.app_context():
agent = db.session.get(Agent, resp_data['id'])
assert agent is not None
assert agent.type == 'iframe'
# Ensure empty string was converted to None
assert agent.dify_app_id is None
assert agent.extra_config['iframe_url'] == data['iframe_url']
def test_create_api_agent(client):
"""
Test creating an API agent with user provided data.
"""
data = {
"name": "Test API Agent",
"type": "api",
"api_base_url": "http://127.0.0.1:5001/v1",
"dify_api_key": "app-xdiejQibWQy8ZQWXcdxJjS9I"
}
# We need to provide a dify_app_id because it is required for API agents
payload = {
"name": data["name"],
"type": data["type"],
"dify_app_id": "test-api-agent-id", # Dummy ID
"dify_api_key": data["dify_api_key"],
"api_base_url": data["api_base_url"]
}
response = client.post('/api/admin/agents', json=payload, headers=get_headers())
assert response.status_code == 201, f"Failed to create API agent: {response.text}"
resp_data = response.get_json()
assert 'id' in resp_data
# Verify DB
with client.application.app_context():
agent = db.session.get(Agent, resp_data['id'])
assert agent is not None
assert agent.type == 'api'
assert agent.dify_api_key == data['dify_api_key']
assert agent.api_base_url == data['api_base_url']
+91
View File
@@ -0,0 +1,91 @@
import requests
import json
from app import create_app, db
from app.models import Agent, ChatLog, User
def setup_data():
app = create_app()
with app.app_context():
# Create a user first (needed for chat log)
user = User.query.filter_by(username="repro_user").first()
if not user:
user = User(username="repro_user", email="repro@test.com", role="admin")
user.set_password("password")
db.session.add(user)
db.session.commit()
# Create the "Test Agent Report" agent
agent = Agent.query.filter_by(name="Test Agent Report").first()
if not agent:
agent = Agent(
name="Test Agent Report",
type="api",
dify_app_id="repro_app_id",
dify_api_key="repro_key",
is_active=True
)
db.session.add(agent)
db.session.commit()
print(f"Created Agent: {agent.id}")
else:
print(f"Agent exists: {agent.id}")
# Create a ChatLog to enforce FK constraint
chat = ChatLog(
user_id=user.id,
agent_id=agent.id,
query="test",
answer="test"
)
db.session.add(chat)
db.session.commit()
print("Created ChatLog dependency.")
return agent.id, user.username
def test_delete(agent_id, username):
print(f"\n--- Testing DELETE Agent {agent_id} ---")
headers = {
"X-Username": username,
"X-Role": "admin"
}
url = f"http://127.0.0.1:5000/api/admin/agents/{agent_id}"
try:
res = requests.delete(url, headers=headers)
print(f"Status: {res.status_code}")
print(f"Content: {res.text}")
except Exception as e:
print(f"Request failed: {e}")
def test_update(agent_id, username):
print(f"\n--- Testing UPDATE Agent {agent_id} ---")
headers = {
"X-Username": username,
"X-Role": "admin",
"Content-Type": "application/json"
}
url = f"http://127.0.0.1:5000/api/admin/agents/{agent_id}"
data = {
"dify_api_key": "updated_key_123",
"name": "Test Agent Report", # Send name as well
"dify_app_id": "repro_app_id",
"type": "api",
"is_active": True
}
try:
res = requests.put(url, headers=headers, json=data)
print(f"Status: {res.status_code}")
print(f"Content: {res.text}")
except Exception as e:
print(f"Request failed: {e}")
if __name__ == "__main__":
# Ensure data exists
try:
agent_id, username = setup_data()
# Test Delete (Expect fail due to FK)
test_delete(agent_id, username)
# Test Update (Expect success)
test_update(agent_id, username)
except Exception as e:
print(f"Setup failed: {e}")
@@ -0,0 +1,51 @@
import pytest
from app import create_app, db
from app.models import Agent, User
@pytest.fixture
def client():
app = create_app('testing')
with app.app_context():
db.create_all()
# Create an active agent
agent = Agent(name="Test Agent", type="api", is_active=True)
db.session.add(agent)
# Create a regular user (no permissions)
user = User(username='test_user', role='user', email='test@example.com')
db.session.add(user)
db.session.commit()
yield app.test_client()
db.session.remove()
db.drop_all()
def test_user_home_agents_visibility(client):
"""
Test that a regular user can see active agents in /api/user/home
even if they don't have explicit permission (visibility vs access).
"""
# Login as regular user
client.post('/api/user/login', json={'username': 'test_user', 'password': ''})
# Mock headers for auth (since login might not set session in test client depending on implementation)
# user.py uses _get_current_user which checks headers
headers = {
'X-Username': 'test_user',
'X-Role': 'user'
}
response = client.get('/api/user/home', headers=headers)
assert response.status_code == 200
data = response.get_json()
agents = data.get('agents', [])
# Current behavior (Bug): agents is empty for regular user
# Desired behavior: agents should contain the active agent
print(f"Agents found: {len(agents)}")
assert len(agents) > 0, "Agents list should not be empty for regular user"
+116
View File
@@ -0,0 +1,116 @@
import pytest
from app.models import Agent, User
from app import db
import uuid
def test_delete_user_success(client, admin_headers):
"""
Verify DELETE /api/admin/users/<id> works (after fix).
"""
# Create a user to delete
user = User(username=f"del_{uuid.uuid4().hex[:8]}", email=f"del_{uuid.uuid4().hex[:8]}@test.com", role="user")
user.set_password("password")
db.session.add(user)
db.session.commit()
user_id = user.id
print(f"\nCreated user {user_id} for DELETE test.")
# Test DELETE Endpoint
res = client.delete(f'/api/admin/users/{user_id}', headers=admin_headers)
print(f"DELETE /users/{user_id} status: {res.status_code}")
if res.status_code == 200:
print("DELETE /api/admin/users/<id> success.")
# Verify user is gone
assert User.query.get(user_id) is None
else:
print(f"DELETE failed with {res.status_code}: {res.text}")
pytest.fail(f"DELETE failed: {res.status_code}")
def test_update_agent_api_key_scenarios(client, admin_headers):
"""
Test various Agent API Key update scenarios.
"""
# Create an agent
app_id = f"app-{uuid.uuid4().hex[:8]}"
agent = Agent(
name="UpdateKeyTest",
type="api",
dify_app_id=app_id,
dify_api_key="orig_key",
is_active=True
)
db.session.add(agent)
db.session.commit()
agent_id = agent.id
print(f"\nCreated agent {agent_id} for update test.")
# Scenario 1: Update Key Success
new_key = "new_secret_key"
data = {
"dify_api_key": new_key
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
assert res.status_code == 200
updated_agent = Agent.query.get(agent_id)
assert updated_agent.dify_api_key == new_key
print("Scenario 1 (Success): Key updated.")
# Scenario 2: Update with Empty String (Should allow it? Or ignore?)
# Current behavior: updates to empty string.
data = {
"dify_api_key": ""
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
assert res.status_code == 200
updated_agent = Agent.query.get(agent_id)
assert updated_agent.dify_api_key == ""
print("Scenario 2 (Empty String): Key updated to empty string.")
# Scenario 3: Update with Duplicate App ID (Should fail)
# Create another agent first
other_app_id = f"app-{uuid.uuid4().hex[:8]}"
other_agent = Agent(
name="OtherAgent",
type="api",
dify_app_id=other_app_id,
dify_api_key="key2",
is_active=True
)
db.session.add(other_agent)
db.session.commit()
# Try to update first agent to use second agent's App ID
data = {
"dify_app_id": other_app_id
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
print(f"Scenario 3 (Duplicate App ID) status: {res.status_code}")
# This should fail with 400 (caught exception) or 500
# Our code catches Exception and returns 400
assert res.status_code == 400
assert "error" in res.json
print("Scenario 3 (Duplicate App ID): Correctly failed.")
# Scenario 4: Update with Very Long Key (Should fail if > 100)
long_key = "a" * 101
data = {
"dify_api_key": long_key
}
res = client.put(f'/api/admin/agents/{agent_id}', json=data, headers=admin_headers)
print(f"Scenario 4 (Long Key) status: {res.status_code}")
# Should fail due to DB constraint (String(100))
# Caught by try-except block -> 400
if res.status_code == 400:
print("Scenario 4 (Long Key): Correctly failed.")
else:
print(f"Scenario 4 (Long Key): Unexpected success? Status: {res.status_code}")
# If SQLite, it might not enforce length. If Postgres, it will.
# We are using SQLite (implied by file structure/lack of PG setup in context, but wait, env says postgres?)
# "mcp_PostgreSQL_query" tool suggests Postgres.
# But locally it might be SQLite.
pass
+194
View File
@@ -0,0 +1,194 @@
import pytest
from app.models import Agent, User, PermissionRequest
from app import db
def test_agent_lifecycle(client, admin_headers):
"""
Test complete lifecycle of an Agent: Create -> Read -> Update -> Delete
"""
# 1. Create Agent
new_agent = {
"name": "Test Agent",
"description": "Initial Description",
"type": "api",
"dify_app_id": "app-123",
"dify_api_key": "key-123",
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
assert response.status_code == 201
agent_id = response.json['id']
# 2. Read Agent List
response = client.get('/api/admin/agents', headers=admin_headers)
assert response.status_code == 200
agents = response.json
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
# 3. Update Agent
updated_data = {
"name": "Updated Agent",
"description": "Updated Description"
}
response = client.put(f'/api/admin/agents/{agent_id}', json=updated_data, headers=admin_headers)
assert response.status_code == 200
# Verify Update
response = client.get('/api/admin/agents', headers=admin_headers)
agents = response.json
assert agents[0]['name'] == "Updated Agent"
assert agents[0]['description'] == "Updated Description"
# 4. Delete Agent
response = client.delete(f'/api/admin/agents/{agent_id}', headers=admin_headers)
assert response.status_code == 200
# Verify Deletion
response = client.get('/api/admin/agents', headers=admin_headers)
assert len(response.json) == 0
def test_user_management(client, admin_headers):
"""
Test user creation, approval, and permission assignment
"""
# 1. Create User
new_user = {
"username": "newuser",
"email": "new@example.com",
"role": "user",
"password": "password123",
"real_name": "Test User",
"employee_id": "EMP001"
}
response = client.post('/api/admin/users', json=new_user, headers=admin_headers)
assert response.status_code == 201
user_id = response.json['id']
# 2. Approve User
response = client.post(f'/api/admin/users/{user_id}/approve', headers=admin_headers)
assert response.status_code == 200
# Verify Status and Fields
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
target_user = next(u for u in users if u['id'] == user_id)
assert target_user['status'] == 'active'
assert target_user['real_name'] == "Test User"
assert target_user['employee_id'] == "EMP001"
# 3. Assign Permissions (needs an Agent first)
agent_res = client.post('/api/admin/agents', json={
"name": "Permission Agent",
"type": "api",
"dify_app_id": "p1",
"dify_api_key": "k1"
}, headers=admin_headers)
agent_id = agent_res.json['id']
response = client.post(f'/api/admin/users/{user_id}/permissions', json={
"agent_ids": [agent_id]
}, headers=admin_headers)
assert response.status_code == 200
# Verify Permissions
response = client.get('/api/admin/users', headers=admin_headers)
target_user = next(u for u in response.json if u['id'] == user_id)
assert agent_id in target_user['agent_ids']
# 4. Delete User (New Endpoint)
response = client.delete(f'/api/admin/users/{user_id}', headers=admin_headers)
assert response.status_code == 200
# Verify Deletion
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
assert not any(u['id'] == user_id for u in users)
def test_agent_update_validation(client, admin_headers):
"""
Test validation when updating agents (especially API mode constraints)
"""
# Create Agent
new_agent = {
"name": "Validation Agent",
"type": "api",
"dify_app_id": "v-app-1",
"dify_api_key": "v-key-1",
"is_active": True
}
response = client.post('/api/admin/agents', json=new_agent, headers=admin_headers)
agent_id = response.json['id']
# 1. Update with Valid Data
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": "new-key"}, headers=admin_headers)
assert response.status_code == 200
# 2. Try to Clear Key for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_api_key": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify API Key" in response.json['error']
# 3. Try to Clear App ID for API Agent (Should Fail)
response = client.put(f'/api/admin/agents/{agent_id}', json={"dify_app_id": ""}, headers=admin_headers)
assert response.status_code == 400
assert "API mode requires Dify App ID" in response.json['error']
def test_permission_requests(client, app, admin_headers):
"""
Test permission request approval/rejection flow
"""
# Setup: Create User, Agent, and Request manually
with app.app_context():
user = User(username="requester", email="req@example.com", role="user")
agent = Agent(name="Requested Agent", type="api", dify_app_id="r1", dify_api_key="k1", is_active=True)
db.session.add(user)
db.session.add(agent)
db.session.commit()
req = PermissionRequest(user_id=user.id, agent_id=agent.id, reason="Need access", status="pending")
db.session.add(req)
db.session.commit()
req_id = req.id
user_id = user.id
agent_id = agent.id
# 1. List Requests
response = client.get('/api/admin/permission-requests', headers=admin_headers)
assert response.status_code == 200
requests = response.json
assert len(requests) == 1
assert requests[0]['reason'] == "Need access"
# 2. Approve Request
response = client.post(f'/api/admin/permission-requests/{req_id}/approve', headers=admin_headers)
assert response.status_code == 200
# Verify Request Status
response = client.get('/api/admin/permission-requests', headers=admin_headers)
requests = response.json
assert requests[0]['status'] == 'approved'
# Verify User Permission Updated
response = client.get('/api/admin/users', headers=admin_headers)
users = response.json
target_user = next(u for u in users if u['id'] == user_id)
assert agent_id in target_user['agent_ids']
def test_reports(client, admin_headers):
"""
Test report endpoints
"""
response = client.get('/api/admin/reports/usage', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert 'total' in data
assert 'by_user' in data
assert 'by_agent' in data
response = client.get('/api/admin/reports/feedback', headers=admin_headers)
assert response.status_code == 200
data = response.json
assert 'avg_score' in data
assert 'distribution' in data
+149
View File
@@ -0,0 +1,149 @@
import pytest
from app import create_app, db
from app.models import User, Agent, Department, PermissionRequest
@pytest.fixture
def client():
app = create_app()
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 admin user
admin = User(username='admin', role='admin', email='admin@example.com')
admin.set_password('admin')
db.session.add(admin)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client, username='admin', password='admin'):
res = client.post('/api/user/login', json={'username': username, 'password': password})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
}
def test_department_crud(client):
headers = get_headers(client)
# Create
res = client.post('/api/admin/departments', json={
'name': 'IT Dept',
'code': 'IT001',
'company': 'Tech Corp',
'description': 'Information Technology'
}, headers=headers)
assert res.status_code == 201
dept_id = res.get_json()['id']
# List
res = client.get('/api/admin/departments', headers=headers)
assert res.status_code == 200
depts = res.get_json()
assert len(depts) == 1
assert depts[0]['code'] == 'IT001'
assert depts[0]['company'] == 'Tech Corp'
# Update
res = client.put(f'/api/admin/departments/{dept_id}', json={
'name': 'IT Department',
'code': 'IT002'
}, headers=headers)
assert res.status_code == 200
# Verify Update
res = client.get('/api/admin/departments', headers=headers)
depts = res.get_json()
assert depts[0]['name'] == 'IT Department'
assert depts[0]['code'] == 'IT002'
# Delete
res = client.delete(f'/api/admin/departments/{dept_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/departments', headers=headers)
assert len(res.get_json()) == 0
def test_agent_crud(client):
headers = get_headers(client)
# Create
res = client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123',
'description': 'Test Description'
}, headers=headers)
assert res.status_code == 201
agent_id = res.get_json()['id']
# List
res = client.get('/api/admin/agents', headers=headers)
assert res.status_code == 200
agents = res.get_json()
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
'name': 'Updated Agent'
}, headers=headers)
assert res.status_code == 200
# Verify Update
res = client.get('/api/admin/agents', headers=headers)
assert res.get_json()[0]['name'] == 'Updated Agent'
# Delete
res = client.delete(f'/api/admin/agents/{agent_id}', headers=headers)
assert res.status_code == 200
res = client.get('/api/admin/agents', headers=headers)
assert len(res.get_json()) == 0
def test_permission_flow(client):
admin_headers = get_headers(client)
# Create Agent
client.post('/api/admin/agents', json={
'name': 'Test Agent',
'dify_app_id': 'app-123'
}, headers=admin_headers)
agent_id = 1
# Create User
client.post('/api/user/register', json={
'username': 'user1', 'password': 'password', 'email': 'u1@example.com',
'real_name': 'User One', 'employee_id': 'U001', 'phone_number': '1234567890'
})
# Approve User
client.post('/api/admin/users/2/approve', headers=admin_headers) # ID 2 because admin is 1
# User Login
user_headers = get_headers(client, 'user1', 'password')
# Request Permission
res = client.post('/api/user/permission-requests', json={
'agent_id': agent_id,
'reason': 'I need it'
}, headers=user_headers)
assert res.status_code == 201
req_id = res.get_json()['id']
# Admin List Requests
res = client.get('/api/admin/permission-requests', headers=admin_headers)
assert len(res.get_json()) == 1
# Admin Approve
res = client.post(f'/api/admin/permission-requests/{req_id}/approve', headers=admin_headers)
assert res.status_code == 200
# User Check Home (should have agent now)
res = client.get('/api/user/home', headers=user_headers)
data = res.get_json()
assert len(data['agents']) == 1
assert data['agents'][0]['id'] == agent_id
+131
View File
@@ -0,0 +1,131 @@
import pytest
from app import create_app, db
from app.models import User, Agent
from flask import json
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create Admin
admin = User(username='admin', role='admin', email='admin@example.com')
admin.set_password('password')
db.session.add(admin)
# Create Users
u1 = User(username='u1', role='user', email='u1@example.com')
u2 = User(username='u2', role='user', email='u2@example.com')
db.session.add_all([u1, u2])
# Create Agents
a1 = Agent(name='a1', dify_app_id='1', dify_api_key='1')
a2 = Agent(name='a2', dify_app_id='2', dify_api_key='2')
db.session.add_all([a1, a2])
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def login(client, username, password):
return client.post('/api/user/login', json={'username': username, 'password': password})
def test_batch_update_users(client):
login_res = login(client, 'admin', 'password')
token_headers = {
'X-Username': 'admin',
'X-Role': 'admin',
'X-User-Id': str(login_res.json['id'])
}
# Get user IDs
u1 = User.query.filter_by(username='u1').first()
u2 = User.query.filter_by(username='u2').first()
# Batch update
res = client.put('/api/admin/users/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'data': {'department': 'Engineering', 'status': 'disabled'}
})
assert res.status_code == 200
# Verify
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert u1.department == 'Engineering'
assert u1.status == 'disabled'
assert u2.department == 'Engineering'
assert u2.status == 'disabled'
def test_batch_update_permissions(client):
login_res = login(client, 'admin', 'password')
token_headers = {
'X-Username': 'admin',
'X-Role': 'admin',
'X-User-Id': str(login_res.json['id'])
}
u1 = User.query.filter_by(username='u1').first()
u2 = User.query.filter_by(username='u2').first()
a1 = Agent.query.filter_by(name='a1').first()
a2 = Agent.query.filter_by(name='a2').first()
# Grant a1 to u1 initially
u1.agents.append(a1)
db.session.commit()
# Batch Add a2 to u1, u2
res = client.post('/api/admin/permissions/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'agent_ids': [a2.id],
'action': 'add'
})
assert res.status_code == 200
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert a1 in u1.agents
assert a2 in u1.agents
assert a2 in u2.agents
# Batch Set a1 for u1, u2 (should remove a2)
res = client.post('/api/admin/permissions/batch', headers=token_headers, json={
'user_ids': [u1.id, u2.id],
'agent_ids': [a1.id],
'action': 'set'
})
assert res.status_code == 200
u1 = User.query.get(u1.id)
u2 = User.query.get(u2.id)
assert len(u1.agents) == 1
assert u1.agents[0].id == a1.id
assert len(u2.agents) == 1
assert u2.agents[0].id == a1.id
def test_user_default_agent(client):
# Login as u1
u1 = User.query.filter_by(username='u1').first()
u1.set_password('password')
db.session.commit()
login_res = login(client, 'u1', 'password')
token_headers = {
'X-Username': 'u1',
'X-Role': 'user',
'X-User-Id': str(u1.id)
}
a1 = Agent.query.filter_by(name='a1').first()
# Set default agent
res = client.put('/api/user/profile', headers=token_headers, json={
'default_agent_id': a1.id
})
assert res.status_code == 200
# Verify via Home API
res = client.get('/api/user/home', headers=token_headers)
data = res.json
assert data['user']['default_agent_id'] == a1.id
+237
View File
@@ -0,0 +1,237 @@
import pytest
import json
from app.models import User, Agent
# -----------------------------------------------------------------------------
# Test File: backend/tests/test_comprehensive.py
# Purpose: Comprehensive automated tests for backend functionalities including
# User Management, Agent Management, and Permissions.
# References: backend/app/api/admin.py, backend/app/api/user.py, backend/app/models.py
# Logic:
# 1. Test User Registration (with new fields)
# 2. Test Admin User Approval
# 3. Test Admin User Rejection
# 4. Test Agent CRUD (Create, Update, Delete)
# 5. Test Permission Assignment (User-Agent linkage)
# -----------------------------------------------------------------------------
@pytest.fixture
def auth_headers(client):
"""
Helper fixture to get auth headers for a standard user.
Note: In real app, we might need a token, but here we use mock headers from conftest
or simulate login if needed. For admin, we use admin_headers fixture.
"""
return {
'Content-Type': 'application/json'
}
def test_user_registration_flow(client):
"""
Test the user registration process with all new fields.
Steps:
1. Register a new user with phone_number, real_name, employee_id.
2. Verify successful response.
3. Verify data in database.
4. Try to register with duplicate phone_number/employee_id and verify failure.
"""
# 1. Register a new user
payload = {
'username': 'testuser_new',
'password': 'password123',
'email': 'testuser_new@example.com',
'real_name': 'Test User Real',
'employee_id': 'EMP001',
'phone_number': '13800138000'
}
# Call /api/user/register (Assuming this is the public registration endpoint)
# If not, we might use /api/admin/users for admin creation.
# Let's check api/user.py for register endpoint, usually it is /api/user/register
response = client.post('/api/user/register', json=payload)
# 2. Verify response
assert response.status_code == 201 or response.status_code == 200
data = response.get_json()
assert 'id' in data or 'status' in data
# 3. Verify database
user = User.query.filter_by(username='testuser_new').first()
assert user is not None
assert user.real_name == 'Test User Real'
assert user.employee_id == 'EMP001'
assert user.phone_number == '13800138000'
assert user.status == 'pending' # Default status for registration
# 4. Duplicate checks
# Duplicate Phone
payload_dup_phone = payload.copy()
payload_dup_phone['username'] = 'testuser_dup_phone'
payload_dup_phone['email'] = 'dup_phone@example.com'
payload_dup_phone['employee_id'] = 'EMP002' # Different ID
# Same phone '13800138000'
response = client.post('/api/user/register', json=payload_dup_phone)
assert response.status_code == 400
assert 'Phone number already exists' in response.get_json()['error']
# Duplicate Employee ID
payload_dup_emp = payload.copy()
payload_dup_emp['username'] = 'testuser_dup_emp'
payload_dup_emp['email'] = 'dup_emp@example.com'
payload_dup_emp['phone_number'] = '13900139000' # Different phone
# Same employee_id 'EMP001'
response = client.post('/api/user/register', json=payload_dup_emp)
assert response.status_code == 400
assert 'Employee ID already exists' in response.get_json()['error']
def test_admin_approve_reject_user(client, admin_headers):
"""
Test Admin approval and rejection of users.
Steps:
1. Create two pending users (via register endpoint or direct DB).
2. Admin approves User A. Verify status 'active'.
3. Admin rejects User B. Verify status 'rejected'.
"""
# 1. Create users
# We can use the register endpoint or admin create endpoint
user_a = User(username='user_a', email='a@test.com', status='pending', role='user')
user_a.set_password('123')
user_b = User(username='user_b', email='b@test.com', status='pending', role='user')
user_b.set_password('123')
# Need to access db session. conftest app fixture handles db creation/drop
# but we need to import db from app to add
from app import db
db.session.add(user_a)
db.session.add(user_b)
db.session.commit()
# 2. Approve User A
response = client.post(f'/api/admin/users/{user_a.id}/approve', headers=admin_headers)
assert response.status_code == 200
# Refresh from DB
db.session.refresh(user_a)
assert user_a.status == 'active'
# 3. Reject User B
response = client.post(f'/api/admin/users/{user_b.id}/reject', headers=admin_headers)
assert response.status_code == 200
db.session.refresh(user_b)
assert user_b.status == 'rejected'
def test_agent_management(client, admin_headers):
"""
Test CRUD operations for Agents.
Steps:
1. Admin creates a new Agent.
2. Admin updates the Agent.
3. Admin deletes the Agent.
"""
from app import db
# 1. Create Agent
payload = {
'name': 'Test Agent',
'dify_app_id': 'app-uuid-123',
'dify_api_key': 'key-secret-123',
'description': 'A test agent',
'type': 'api'
}
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
assert response.status_code == 201
data = response.get_json()
agent_id = data['id']
# Verify DB
agent = Agent.query.get(agent_id)
assert agent.name == 'Test Agent'
# 2. Update Agent
update_payload = {
'name': 'Updated Agent Name',
'description': 'Updated description'
}
response = client.put(f'/api/admin/agents/{agent_id}', json=update_payload, headers=admin_headers)
assert response.status_code == 200
db.session.refresh(agent)
assert agent.name == 'Updated Agent Name'
assert agent.description == 'Updated description'
# 3. Delete Agent
response = client.delete(f'/api/admin/agents/{agent_id}', headers=admin_headers)
assert response.status_code == 200
agent = Agent.query.get(agent_id)
assert agent is None
def test_permission_management(client, admin_headers):
"""
Test assigning Agents to Users (Permissions).
Steps:
1. Create a User and an Agent.
2. Verify User initially has no agents.
3. Admin updates User to assign the Agent.
4. Verify User has the Agent.
5. Admin removes the Agent.
6. Verify User has no agents.
"""
from app import db
# 1. Setup Data
user = User(username='perm_user', email='perm@test.com', role='user', status='active')
user.set_password('123')
agent = Agent(name='Perm Agent', dify_app_id='app-perm', dify_api_key='key-perm')
db.session.add(user)
db.session.add(agent)
db.session.commit()
user_id = user.id
agent_id = agent.id
# 2. Verify initial state
assert len(user.agents) == 0
# 3. Assign Agent
# The update_user endpoint accepts 'agent_ids' list
payload = {
'agent_ids': [agent_id]
}
response = client.put(f'/api/admin/users/{user_id}', json=payload, headers=admin_headers)
assert response.status_code == 200
# 4. Verify assignment
# Need to expire/refresh to see changes in relationship
db.session.expire(user)
# Or query again
user = User.query.get(user_id)
assert len(user.agents) == 1
assert user.agents[0].id == agent_id
# 5. Remove Agent (assign empty list)
payload = {
'agent_ids': []
}
response = client.put(f'/api/admin/users/{user_id}', json=payload, headers=admin_headers)
assert response.status_code == 200
# 6. Verify removal
db.session.expire(user)
user = User.query.get(user_id)
assert len(user.agents) == 0
+56
View File
@@ -0,0 +1,56 @@
import pytest
from app import create_app, db
from app.models import Agent
@pytest.fixture
def app():
app = create_app('testing')
with app.app_context():
db.create_all()
yield app
db.session.remove()
db.drop_all()
@pytest.fixture
def client(app):
return app.test_client()
def test_public_agents_access(client):
"""
测试未登录用户访问公开应用列表
"""
# 1. 初始状态:无应用
res = client.get('/api/user/public-agents')
assert res.status_code == 200
assert len(res.json) == 0
# 2. 创建应用
with client.application.app_context():
a1 = Agent(name="Public Agent 1", dify_app_id="p1", dify_api_key="k1", is_active=True)
a2 = Agent(name="Public Agent 2", dify_app_id="p2", dify_api_key="k2", is_active=True)
a3 = Agent(name="Private Agent", dify_app_id="p3", dify_api_key="k3", is_active=False)
db.session.add_all([a1, a2, a3])
db.session.commit()
# 3. 再次访问,应只返回 Active 的应用
res = client.get('/api/user/public-agents')
assert res.status_code == 200
data = res.json
assert len(data) == 2
names = [a['name'] for a in data]
assert "Public Agent 1" in names
assert "Public Agent 2" in names
assert "Private Agent" not in names
def test_user_home_access_denied(client):
"""
测试未登录用户访问 /api/user/home 返回 Guest 身份
"""
# 无 Header 访问
res = client.get('/api/user/home')
assert res.status_code == 200
data = res.json
assert data['user']['role'] == 'guest'
# Guest 用户通常没有 Agents 权限
assert len(data['agents']) == 0
+55
View File
@@ -0,0 +1,55 @@
import pytest
from app import create_app, db
from app.models import User, Agent, QuickQuestion
@pytest.fixture
def client():
app = create_app()
app.config['TESTING'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
with app.test_client() as client:
with app.app_context():
db.create_all()
yield client
db.session.remove()
db.drop_all()
def test_quick_question_crud(client):
# Setup
user = User(username='testuser', email='test@example.com', role='user')
user.set_password('password')
agent = Agent(name='Test Agent', dify_app_id='app-123', dify_api_key='key-123')
db.session.add(user)
db.session.add(agent)
db.session.commit()
# Login
login_res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'password'})
assert login_res.status_code == 200
user_data = login_res.get_json()
headers = {'X-User-Id': str(user_data['id']), 'X-Username': user_data['username'], 'X-Role': user_data['role']}
# Create
res = client.post('/api/user/quick-questions', json={
'title': 'Test Q',
'question': 'How are you?',
'agent_id': agent.id
}, headers=headers)
assert res.status_code == 201
qq_id = res.get_json()['id']
# Read (via Home)
res = client.get('/api/user/home', headers=headers)
assert res.status_code == 200
data = res.get_json()
assert len(data['quick_questions']) == 1
assert data['quick_questions'][0]['title'] == 'Test Q'
# Delete
res = client.delete(f'/api/user/quick-questions/{qq_id}', headers=headers)
assert res.status_code == 200
# Verify Delete
res = client.get('/api/user/home', headers=headers)
assert len(res.get_json()['quick_questions']) == 0
+624
View File
@@ -0,0 +1,624 @@
"""
backend/tests/test_unit_mock.py
文件用途:自动化单元测试,使用 Mock 技术隔离外部依赖
测试范围:User, Admin, Agent, Chat, Permission, QuickQuestion 等核心模块
技术栈:pytest, unittest.mock, flask
设计原则:AAA 模式 (Arrange-Act-Assert),全面 Mock,独立性
"""
import pytest
import json
from unittest.mock import MagicMock, patch
from flask import g
from app import create_app, db
from app.models import User, Agent, ChatLog, Feedback, PermissionRequest, QuickQuestion
# -----------------------------------------------------------------------------
# Fixtures (Setup & Teardown)
# -----------------------------------------------------------------------------
@pytest.fixture
def app_instance():
"""
创建 Flask 应用实例,配置为测试模式
"""
app = create_app('testing')
app.config['TESTING'] = True
# 禁用反馈功能检查,方便测试
app.config['FEEDBACK_ENABLED'] = True
return app
@pytest.fixture(autouse=True)
def app_context(app_instance):
"""
自动激活应用上下文,解决 "Working outside of application context" 问题
"""
with app_instance.app_context():
yield
@pytest.fixture
def client(app_instance):
"""
Flask 测试客户端
"""
return app_instance.test_client()
@pytest.fixture
def mock_db_session(mocker):
"""
Mock 数据库 Session
用途:拦截 db.session.add, commit, rollback, delete 等操作
"""
return mocker.patch('app.db.session')
@pytest.fixture
def mock_user_query(mocker):
"""Mock User.query"""
return mocker.patch('app.models.User.query')
@pytest.fixture
def mock_agent_query(mocker):
"""Mock Agent.query"""
return mocker.patch('app.models.Agent.query')
@pytest.fixture
def mock_chat_log_query(mocker):
"""Mock ChatLog.query"""
return mocker.patch('app.models.ChatLog.query')
@pytest.fixture
def mock_permission_request_query(mocker):
"""Mock PermissionRequest.query"""
return mocker.patch('app.models.PermissionRequest.query')
@pytest.fixture
def mock_quick_question_query(mocker):
"""Mock QuickQuestion.query"""
return mocker.patch('app.models.QuickQuestion.query')
@pytest.fixture
def admin_headers():
return {
'Content-Type': 'application/json',
'X-Role': 'admin',
'X-Username': 'admin'
}
@pytest.fixture
def user_headers():
return {
'Content-Type': 'application/json',
'X-Role': 'user',
'X-Username': 'test_user',
'X-User-Id': '1'
}
# -----------------------------------------------------------------------------
# 1. User Authentication & Management Tests
# -----------------------------------------------------------------------------
def test_user_register_success(client, mock_user_query, mock_db_session):
"""
[User] 注册成功 (Happy Path)
"""
# Arrange
payload = {
"username": "new_user",
"password": "password123",
"email": "new@example.com",
"real_name": "New User",
"employee_id": "EMP001",
"phone_number": "13800000001"
}
# Mock query to return None (no duplicate)
mock_user_query.filter_by.return_value.first.return_value = None
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
data = response.get_json()
assert data['status'] == 'pending'
def test_user_register_missing_fields(client):
"""
[User] 注册失败 - 缺少必填字段 (Boundary)
"""
# Arrange
payload = {
"username": "new_user"
# Missing password, email, etc.
}
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 400
assert "required" in response.get_json()['error']
def test_user_register_duplicate_username(client, mock_user_query):
"""
[User] 注册失败 - 用户名重复 (Error)
"""
# Arrange
payload = {
"username": "dup_user",
"password": "pwd",
"email": "dup@example.com",
"real_name": "Dup User",
"employee_id": "EMP002",
"phone_number": "13800000002"
}
# Mock existing user
mock_user_query.filter_by.return_value.first.return_value = User(username="dup_user")
# Act
response = client.post('/api/user/register', json=payload)
# Assert
assert response.status_code == 400
assert "Username already exists" in response.get_json()['error']
def test_user_login_success(client, mock_user_query):
"""
[User] 登录成功 (Happy Path)
"""
# Arrange
mock_user = User(id=1, username="test_user", role="user", status="active", password_hash="hashed_pwd")
mock_user_query.filter_by.return_value.first.return_value = mock_user
# Mock check_password_hash via class method or instance
# Note: User.check_password logic uses check_password_hash internally.
# We can mock check_password method on the instance.
mock_user.check_password = MagicMock(return_value=True)
# Act
response = client.post('/api/user/login', json={"username": "test_user", "password": "correct_pwd"})
# Assert
assert response.status_code == 200
data = response.get_json()
assert data['username'] == "test_user"
assert data['role'] == "user"
def test_user_login_invalid_password(client, mock_user_query):
"""
[User] 登录失败 - 密码错误 (Error)
"""
# Arrange
mock_user = User(id=1, username="test_user", status="active", password_hash="hashed")
mock_user_query.filter_by.return_value.first.return_value = mock_user
# Ensure check_password returns False
mock_user.check_password = MagicMock(return_value=False)
# Act
response = client.post('/api/user/login', json={"username": "test_user", "password": "wrong_pwd"})
# Assert
assert response.status_code == 401
assert "Invalid password" in response.get_json()['error']
def test_user_login_inactive_user(client, mock_user_query):
"""
[User] 登录失败 - 账号未激活 (Error)
"""
# Arrange
# Explicitly set status to pending.
# Note: User constructor might set default 'active' if not handled by init (SQLAlchemy magic).
# So we set it explicitly after creation or ensure it's respected.
mock_user = User(id=1, username="pending_user", status="pending", password_hash="hashed")
mock_user_query.filter_by.return_value.first.return_value = mock_user
mock_user.check_password = MagicMock(return_value=True)
# Act
response = client.post('/api/user/login', json={"username": "pending_user", "password": "pwd"})
# Assert
assert response.status_code == 403
assert "Account is not active" in response.get_json()['error']
def test_get_user_home(client, mocker):
"""
[User] 获取首页数据 (Happy Path)
"""
# Arrange
mock_user = User(id=1, role='user', agents=[])
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
# Mock related queries using patching of models directly if fixtures not used,
# OR better: mock the DB session query if the code uses db.session.query
# app/api/user.py uses:
# agents = Agent.query.filter_by...
# quick_questions = db.session.query(QuickQuestion)...
# permission_requests = PermissionRequest.query...
# total_calls = db.session.query(ChatLog)...
# Mock Agent.query
mock_agent_query = mocker.patch('app.models.Agent.query')
mock_agent_query.filter_by.return_value.order_by.return_value.all.return_value = []
# Mock db.session.query for QuickQuestion and ChatLog
mock_query = mocker.patch('app.db.session.query')
# We need to handle different calls to db.session.query
# Since it's hard to distinguish by arg, we can make it return a generic mock that returns empty list/0
mock_query_obj = MagicMock()
mock_query.return_value = mock_query_obj
mock_query_obj.filter.return_value.count.return_value = 0
mock_query_obj.filter_by.return_value.order_by.return_value.all.return_value = []
mock_query_obj.filter_by.return_value.count.return_value = 0
mock_query_obj.filter_by.return_value.order_by.return_value.first.return_value = None
# Mock PermissionRequest.query
mock_pr_query = mocker.patch('app.models.PermissionRequest.query')
mock_pr_query.filter_by.return_value.order_by.return_value.all.return_value = []
# Act
response = client.get('/api/user/home')
# Assert
assert response.status_code == 200
data = response.get_json()
assert 'user' in data
assert 'agents' in data
assert 'report' in data
# -----------------------------------------------------------------------------
# 2. Admin Management Tests
# -----------------------------------------------------------------------------
def test_admin_create_agent_success(client, admin_headers, mock_db_session, mocker):
"""
[Admin] 创建 Agent (Happy Path)
"""
# Arrange
payload = {
"name": "HR Bot",
"type": "api",
"dify_app_id": "app-uuid",
"dify_api_key": "sk-secret"
}
# Mock _get_current_user for require_admin
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_admin_create_agent_missing_fields(client, admin_headers, mocker):
"""
[Admin] 创建 Agent 失败 - 缺少必要字段 (Boundary)
"""
# Arrange
payload = {
"name": "Bad Bot",
"type": "api"
# Missing dify_app_id and dify_api_key
}
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
# Assert
assert response.status_code == 400
assert "API mode requires app_id" in response.get_json()['error']
def test_admin_delete_agent(client, admin_headers, mock_agent_query, mock_db_session, mocker):
"""
[Admin] 删除 Agent (Happy Path)
"""
# Arrange
mock_agent = Agent(id=1, name="Old Bot")
mock_agent_query.get.return_value = mock_agent
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.delete('/api/admin/agents/1', headers=admin_headers)
# Assert
assert response.status_code == 200
mock_db_session.delete.assert_called_once_with(mock_agent)
mock_db_session.commit.assert_called_once()
def test_admin_approve_user(client, admin_headers, mock_user_query, mock_db_session, mocker):
"""
[Admin] 审批用户 (Happy Path)
"""
# Arrange
mock_user = User(id=2, status="pending")
mock_user_query.get.return_value = mock_user
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/users/2/approve', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_user.status == 'active'
mock_db_session.commit.assert_called_once()
def test_admin_reject_user(client, admin_headers, mock_user_query, mock_db_session, mocker):
"""
[Admin] 拒绝用户 (Happy Path)
"""
# Arrange
mock_user = User(id=3, status="pending")
mock_user_query.get.return_value = mock_user
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/users/3/reject', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_user.status == 'rejected'
mock_db_session.commit.assert_called_once()
# -----------------------------------------------------------------------------
# 3. Chat System Tests (Mocking External API)
# -----------------------------------------------------------------------------
def test_chat_completions_stream_success(client, mocker, mock_agent_query):
"""
[Chat] 发送消息并流式返回 (Happy Path)
核心:Mock requests.post 以避免真实网络请求
"""
# Arrange
mock_post = mocker.patch('requests.post')
mock_response = MagicMock()
mock_response.status_code = 200
# Mock SSE stream lines
mock_response.iter_lines.return_value = [
b'data: {"event": "message", "answer": "Hello"}',
b'',
b'data: {"event": "message", "answer": " World"}',
b'',
b'data: {"event": "message_end", "metadata": {"usage": {"total_tokens": 10}}}'
]
mock_post.return_value.__enter__.return_value = mock_response
# Mock DB logging
mocker.patch('app.services.dify.DifyService._log_chat')
# Setup decorator mocks
mock_user = User(id=1, username="test_user")
mock_agent = Agent(id=1, name="Test Agent", dify_api_key="key", api_base_url="http://mock-api")
mock_user.agents = [mock_agent] # Grant permission
# Mock decorator dependencies
# IMPORTANT: require_agent_permission calls _get_current_user() from app.decorators
# We use side_effect to ensure g.current_user is set, as the real function does
def mock_get_user():
g.current_user = mock_user
return mock_user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
# Mock Agent.query.get used in require_agent_permission
mock_agent_query.get.return_value = mock_agent
# Act
payload = {
"query": "Hello",
"agent_id": 1,
"response_mode": "streaming"
}
headers = {'Content-Type': 'application/json'}
response = client.post('/api/chat/completions', json=payload, headers=headers)
# Assert
assert response.status_code == 200
assert response.mimetype == 'text/event-stream'
assert b'data: {"event": "message", "answer": "Hello"}' in response.data
def test_chat_completions_no_permission(client, mocker, mock_agent_query):
"""
[Chat] 无权限访问 Agent (Error)
"""
# Arrange
mock_user = User(id=1, username="test_user")
mock_agent = Agent(id=2, name="Restricted Agent")
mock_user.agents = [] # No permission
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Act
payload = {"query": "Hello", "agent_id": 2}
response = client.post('/api/chat/completions', json=payload)
# Assert
assert response.status_code == 403
assert "Permission denied" in response.get_json()['error']
def test_submit_feedback_success(client, mocker, mock_chat_log_query, mock_agent_query, mock_db_session):
"""
[Chat] 提交反馈 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mock_agent = Agent(id=1)
mock_user.agents = [mock_agent]
def mock_get_user():
g.current_user = mock_user
return mock_user
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
mock_agent_query.get.return_value = mock_agent
# Mock ChatLog query
mock_log = ChatLog(id=100, user_id=1, agent_id=1, feedback=None)
mock_chat_log_query.filter_by.return_value.filter_by.return_value.order_by.return_value.first.return_value = mock_log
# Act
payload = {
"agent_id": 1,
"conversation_id": "conv_123",
"score": 5,
"comment": "Great!"
}
response = client.post('/api/chat/feedback', json=payload)
# Assert
assert response.status_code == 200
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_submit_feedback_invalid_score(client, mocker, mock_agent_query):
"""
[Chat] 提交反馈 - 分数无效 (Boundary)
"""
# Arrange
mock_user = User(id=1)
mock_agent = Agent(id=1)
mock_user.agents = [mock_agent]
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Act
payload = {"agent_id": 1, "score": 6} # Score > 5
response = client.post('/api/chat/feedback', json=payload)
# Assert
assert response.status_code == 400
assert "between 1 and 5" in response.get_json()['error']
# -----------------------------------------------------------------------------
# 4. Permission Request Tests
# -----------------------------------------------------------------------------
def test_create_permission_request(client, mocker, mock_db_session, mock_agent_query, mock_permission_request_query):
"""
[Permission] 用户申请权限 (Happy Path)
"""
# Arrange
mock_user = User(id=1, agents=[])
mock_agent = Agent(id=5)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Ensure no existing pending request
mock_permission_request_query.filter_by.return_value.first.return_value = None
# Act
payload = {"agent_id": 5, "reason": "Need access"}
response = client.post('/api/user/permission-requests', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_create_permission_request_already_exists(client, mocker, mock_agent_query, mock_permission_request_query):
"""
[Permission] 用户重复申请权限 (Error)
"""
# Arrange
mock_user = User(id=1, agents=[])
mock_agent = Agent(id=5)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_agent_query.get.return_value = mock_agent
# Mock existing pending request
mock_permission_request_query.filter_by.return_value.first.return_value = PermissionRequest(id=1)
# Act
payload = {"agent_id": 5}
response = client.post('/api/user/permission-requests', json=payload)
# Assert
assert response.status_code == 400
assert "Request already pending" in response.get_json()['error']
def test_admin_approve_permission_request(client, admin_headers, mock_permission_request_query, mock_user_query, mock_agent_query, mock_db_session, mocker):
"""
[Admin] 同意权限申请 (Happy Path)
"""
# Arrange
mock_pr = PermissionRequest(id=1, user_id=2, agent_id=5, status='pending')
mock_user = User(id=2, agents=[])
mock_agent = Agent(id=5)
# Mock PermissionRequest.query.get
mock_permission_request_query.get.return_value = mock_pr
# Mock User.query.get
mock_user_query.get.return_value = mock_user
# Mock Agent.query.get
mock_agent_query.get.return_value = mock_agent
admin_user = User(role='admin', username='admin')
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
# Act
response = client.post('/api/admin/permission-requests/1/approve', headers=admin_headers)
# Assert
assert response.status_code == 200
assert mock_pr.status == 'approved'
assert mock_agent in mock_user.agents
mock_db_session.commit.assert_called_once()
# -----------------------------------------------------------------------------
# 5. Quick Question Tests
# -----------------------------------------------------------------------------
def test_add_quick_question(client, mocker, mock_db_session):
"""
[QuickQuestion] 添加常用问题 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
# Act
payload = {
"title": "Daily Report",
"question": "Generate report...",
"agent_id": 1
}
response = client.post('/api/user/quick-questions', json=payload)
# Assert
assert response.status_code == 201
mock_db_session.add.assert_called_once()
mock_db_session.commit.assert_called_once()
def test_delete_quick_question(client, mocker, mock_db_session):
"""
[QuickQuestion] 删除常用问题 (Happy Path)
"""
# Arrange
mock_user = User(id=1)
mocker.patch('app.api.user._get_current_user', return_value=mock_user)
mock_qq = QuickQuestion(id=10, user_id=1)
# Mock query: filter_by(id=10, user_id=1).first() -> mock_qq
mocker.patch('app.db.session.query').return_value.filter_by.return_value.first.return_value = mock_qq
# Act
response = client.delete('/api/user/quick-questions/10')
# Assert
assert response.status_code == 200
mock_db_session.delete.assert_called_once_with(mock_qq)
mock_db_session.commit.assert_called_once()
+114
View File
@@ -0,0 +1,114 @@
import pytest
from app import create_app, db
from app.models import User, Agent, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig
@pytest.fixture
def client():
app = create_app('testing')
with app.test_client() as client:
with app.app_context():
db.create_all()
# Create user
user = User(username='testuser', role='user', email='test@example.com')
user.set_password('password')
db.session.add(user)
# Create agents
a1 = Agent(name='Agent 1', dify_app_id='app-1', dify_api_key='key-1')
a2 = Agent(name='Agent 2', dify_app_id='app-2', dify_api_key='key-2')
a3 = Agent(name='Agent 3', dify_app_id='app-3', dify_api_key='key-3')
db.session.add_all([a1, a2, a3])
# Grant permission
user.agents.append(a1)
user.agents.append(a2)
user.agents.append(a3)
db.session.commit()
yield client
db.session.remove()
db.drop_all()
def get_headers(client):
res = client.post('/api/user/login', json={'username': 'testuser', 'password': 'password'})
data = res.get_json()
return {
'X-User-Id': str(data['id']),
'X-Username': data['username'],
'X-Role': data['role']
}
def get_agent_id(client, name):
# Helper to get agent ID by name (since we can't query DB directly easily outside context without binding)
# But we can use the API
# Or just rely on order since we are in a fresh DB
# Let's assume IDs are 1, 2, 3 for now if using SQLite.
# To be safe, let's fetch from public-agents or user-home
# But we need headers for user-home.
pass
def test_favorites(client):
headers = get_headers(client)
# Get agent ID
res = client.get('/api/user/home', headers=headers)
agents = res.get_json()['agents']
agent_id = agents[0]['id']
# Add favorite
res = client.post(f'/api/user/favorites/{agent_id}', headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert agent_id in data['favorite_agent_ids']
# Remove favorite
res = client.delete(f'/api/user/favorites/{agent_id}', headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert agent_id not in data['favorite_agent_ids']
def test_homepage_layout(client):
headers = get_headers(client)
layout = {'sections': [{'id': 'favorites'}, {'id': 'all_agents'}]}
# Update layout
res = client.put('/api/user/homepage-layout', json={'layout': layout}, headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert data['layout']['sections'][0]['id'] == 'favorites'
def test_embedded_agents(client):
headers = get_headers(client)
# Get agent IDs
res = client.get('/api/user/home', headers=headers)
agents = res.get_json()['agents']
id1 = agents[0]['id']
id2 = agents[1]['id']
id3 = agents[2]['id']
# Update embedded agents
res = client.put('/api/user/embedded-agents', json={'agent_ids': [id1, id2]}, headers=headers)
assert res.status_code == 200
# Check home
res = client.get('/api/user/home', headers=headers)
data = res.get_json()
assert len(data['embedded_agents']) == 2
assert data['embedded_agents'][0]['id'] == id1
assert data['embedded_agents'][1]['id'] == id2
# Try more than 2
res = client.put('/api/user/embedded-agents', json={'agent_ids': [id1, id2, id3]}, headers=headers)
assert res.status_code == 400
+87
View File
@@ -0,0 +1,87 @@
import pytest
from app.models import User
from app import db
def test_register_fields_validation(client):
"""
Test user registration field validation
"""
# 1. Missing fields
response = client.post('/api/user/register', json={
"username": "missing",
"password": "pwd",
"email": "m@e.com"
})
assert response.status_code == 400
assert "Real name and Employee ID are required" in response.json['error']
# 2. Duplicate Employee ID
# First create a user (via admin to bypass check or register with valid data)
# Let's register one valid user
valid_user = {
"username": "user1",
"password": "pwd",
"email": "u1@e.com",
"real_name": "User One",
"employee_id": "EMP100",
"phone_number": "13800000001"
}
response = client.post('/api/user/register', json=valid_user)
assert response.status_code == 201
# Now try to register another user with SAME employee_id
dup_user = {
"username": "user2",
"password": "pwd",
"email": "u2@e.com",
"real_name": "User Two",
"employee_id": "EMP100",
"phone_number": "13800000002"
}
response = client.post('/api/user/register', json=dup_user)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
def test_admin_duplicate_employee_id(client, admin_headers):
"""
Test admin user creation duplicate employee_id check
"""
# 1. Create first user
u1 = {
"username": "adm_u1",
"password": "pwd",
"email": "au1@e.com",
"real_name": "Admin User 1",
"employee_id": "ADM001"
}
response = client.post('/api/admin/users', json=u1, headers=admin_headers)
assert response.status_code == 201
# 2. Create second user with same ID
u2 = {
"username": "adm_u2",
"password": "pwd",
"email": "au2@e.com",
"real_name": "Admin User 2",
"employee_id": "ADM001"
}
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
assert response.status_code == 400
assert "Employee ID already exists" in response.json['error']
# 3. Update user to duplicate ID
# Create u3 with valid ID
u3 = {
"username": "adm_u3",
"password": "pwd",
"email": "au3@e.com",
"real_name": "Admin User 3",
"employee_id": "ADM003"
}
res = client.post('/api/admin/users', json=u3, headers=admin_headers)
u3_id = res.json['id']
# Update u3 to ADM001 (which exists)
res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers)
assert res.status_code == 400
assert "Employee ID already exists" in res.json['error']