import pytest from flask import Flask from app import create_app, db from app.models import ChatLog, Agent, User from app.services.integrations.dify import DifyService import json @pytest.fixture def app(): app = create_app('testing') app.config['TESTING'] = True app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' with app.app_context(): db.create_all() yield app db.session.remove() db.drop_all() def test_log_chat_context(app): """ Verify that _log_chat writes to DB correctly when called within app context. This simulates the fix in DifyService.stream_chat where we added `with current_app.app_context():` """ with app.app_context(): # Setup data user = User(username='test', role='user', email='test@example.com') agent = Agent(name='test_agent', dify_app_id='123') db.session.add_all([user, agent]) db.session.commit() user_id = user.id agent_id = agent.id # Simulate logging DifyService._log_chat( user_id=user_id, agent_id=agent_id, conversation_id='conv_123', query='Hello', answer='Hi there', tokens=10, latency=100 ) # Verify log = ChatLog.query.filter_by(conversation_id='conv_123').first() assert log is not None assert log.query == 'Hello' assert log.answer == 'Hi there' assert log.tokens_used == 10 assert log.latency == 100 def test_feedback_config_logic(): """ Verify frontend config logic (simulation) Since we can't test TS file directly in python, we verify the backend logic if any. Backend /feedback endpoint checks FEEDBACK_ENABLED config. """ # This is covered by app/config.py having FEEDBACK_ENABLED default to True from app.core.config.settings import Config assert Config.FEEDBACK_ENABLED is True