test_gateway_runtime.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import unittest
  2. from datetime import datetime, timedelta
  3. from app import GatewayApp
  4. from services.token_store import InMemoryTokenStore
  5. class DummyAuthClient:
  6. def __init__(self, token_store):
  7. self.token_store = token_store
  8. self.refresh_calls = []
  9. def refresh(self, mcp_token):
  10. self.refresh_calls.append(mcp_token)
  11. self.token_store.save('MT_refresh', '2099-01-02T00:00:00')
  12. return {
  13. 'code': 'MCP_0000',
  14. 'msg': 'success',
  15. 'data': {
  16. 'mcp_token': 'MT_refresh',
  17. 'expire_time': '2099-01-02T00:00:00',
  18. },
  19. }
  20. class DummyApiClient:
  21. def __init__(self):
  22. self.calls = []
  23. def call_tool(self, tool_code, route_path, payload, request_id):
  24. self.calls.append(
  25. {
  26. 'tool_code': tool_code,
  27. 'route_path': route_path,
  28. 'payload': payload,
  29. 'request_id': request_id,
  30. }
  31. )
  32. return {
  33. 'code': 'MCP_0000',
  34. 'msg': 'success',
  35. 'data': {
  36. 'summary': 'ok',
  37. 'records': [],
  38. 'tips': [],
  39. },
  40. 'meta': {
  41. 'request_id': request_id,
  42. },
  43. }
  44. class GatewayRuntimeTest(unittest.TestCase):
  45. def test_list_tools_does_not_include_bind_auth_code(self):
  46. store = InMemoryTokenStore(refresh_skew_seconds=60)
  47. app = GatewayApp(
  48. auth_client=DummyAuthClient(store),
  49. api_client=DummyApiClient(),
  50. token_store=store,
  51. )
  52. names = [tool['name'] for tool in app.list_tools()]
  53. self.assertIn('query_order', names)
  54. self.assertIn('query_track', names)
  55. self.assertNotIn('bind_auth_code', names)
  56. self.assertFalse(hasattr(app, 'bind'))
  57. def test_call_tool_refreshes_expiring_token_and_generates_request_id(self):
  58. store = InMemoryTokenStore(refresh_skew_seconds=60)
  59. expiring_time = (datetime.now() + timedelta(seconds=10)).isoformat(timespec='seconds')
  60. store.save('MT_old', expiring_time)
  61. auth_client = DummyAuthClient(store)
  62. api_client = DummyApiClient()
  63. app = GatewayApp(
  64. auth_client=auth_client,
  65. api_client=api_client,
  66. token_store=store,
  67. )
  68. response = app.call_tool('query_order', {'keyword': 'SO20260706001'})
  69. self.assertEqual(['MT_old'], auth_client.refresh_calls)
  70. self.assertEqual('MT_refresh', store.get()['token'])
  71. self.assertEqual('query_order', api_client.calls[0]['tool_code'])
  72. self.assertTrue(api_client.calls[0]['request_id'].startswith('rq_'))
  73. self.assertEqual(api_client.calls[0]['request_id'], response['meta']['request_id'])
  74. if __name__ == '__main__':
  75. unittest.main()