import pytest from flask import g from app import create_app, db from app.models import Agent, ChatSession, User @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 user = User(username='testuser', role='user', email='test@example.com') user.set_password('password') db.session.add(user) # Create agent with trailing slash in URL (to test strip logic) agent = Agent( name='Test Agent', dify_api_key='test-key', api_base_url='http://dify.example.com/v1/chat-messages', # Intentionally wrong to simulate user error type='api' ) db.session.add(agent) # Grant permission user.agents.append(agent) 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'], 'Content-Type': 'application/json' } def test_chat_url_logic(client): """ Test that the backend correctly constructs the Dify URL Note: We can't easily mock the external request in this integration test without 'requests_mock', but we can verify the logic in a unit test style or assume the service handles it. Here we verify the permission check passes. """ headers = get_headers(client) with client.application.app_context(): agent_id = Agent.query.first().id # Test permission (should be allowed) # We send a request. It will fail at the requests.post stage (connection error), # but that means it passed the permission check. # If permission denied, it would return 403 immediately. try: res = client.post('/api/chat/completions', headers=headers, json={ 'agent_id': agent_id, 'query': 'Hello' }) except: # Expected connection error to fake URL pass # To truly verify permission, we can check the decorator logic via a mocked endpoint or just rely on the status code not being 403 # Since requests.post raises exception, we can't check status code easily here without mocking. # Let's test the permission check explicitly via another endpoint that uses the same decorator res = client.get(f'/api/chat/sessions?agent_id={agent_id}', headers=headers, json={'agent_id': agent_id}) # GET request with json body is weird but allowed in Flask test client, # but the decorator reads `request.get_json()`. # `get_chat_sessions` uses `g.current_agent` which is set by the decorator. # Actually, `require_agent_permission` expects agent_id in JSON body. # Standard GET requests don't have body. # But let's try sending body with GET. res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': agent_id}) assert res.status_code == 200 # Should succeed (empty list) # Now remove permission with client.application.app_context(): user = User.query.filter_by(username='testuser').first() agent = Agent.query.first() user.agents.remove(agent) db.session.commit() res = client.get('/api/chat/sessions', headers=headers, json={'agent_id': agent_id}) assert res.status_code == 403 assert res.get_json()['error'] == 'Permission denied for this agent' def test_chat_completions_stream_reads_session_snapshot_after_commit(client, monkeypatch): """ 提交会话后消费 SSE 时使用标量快照,避免已脱离 Session 的 ORM 实例被延迟刷新。 关键断言:生成器在请求返回后仍能产出 session_created 事件,而不会抛出 DetachedInstanceError。 """ with client.application.app_context(): user = User(username='stream-user', role='admin', email='stream-user@example.com') agent = Agent(name='Stream Agent', dify_api_key='test-key', api_base_url='http://dify.invalid') db.session.add_all([user, agent]) db.session.commit() user_id = user.id agent_id = agent.id monkeypatch.setattr( 'app.services.chat.executors.stream_chat_via_executor', lambda _context: iter(['data: {"event": "message_end"}\n\n']), ) from app.api.chat import completions captured_session = None original_ensure_chat_session = completions._ensure_chat_session def capture_ensured_session(*args, **kwargs): nonlocal captured_session captured_session = original_ensure_chat_session(*args, **kwargs) return captured_session monkeypatch.setattr(completions, '_ensure_chat_session', capture_ensured_session) def get_current_user(): current_user = db.session.get(User, user_id) g.current_user = current_user return current_user monkeypatch.setattr('app.core.decorators._get_current_user', get_current_user) with client.application.test_request_context( '/api/chat/completions', method='POST', json={'agent_id': agent_id, 'query': '测试流式会话'}, ): response = client.application.view_functions['chat.chat_completions']() # 模拟生产环境:流式处理中的事务令 ORM 属性过期,随后请求 scoped Session 被清理。 assert captured_session is not None db.session.expire(captured_session) db.session.remove() body = ''.join(response.response).encode() assert response.status_code == 200 assert b'"event": "session_created"' in body assert b'DetachedInstanceError' not in body with client.application.app_context(): assert ChatSession.query.filter_by(user_id=user_id, agent_id=agent_id).count() == 1