57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
|
|
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
|