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}")