|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Integration test for chat endpoint logging to S3. |
| 4 | +
|
| 5 | +Sends a chat request with a known ?id= value, then reads the daily S3 log |
| 6 | +file and verifies that the record was written with the correct fields. |
| 7 | +
|
| 8 | +Usage: |
| 9 | + python test_log_integration.py --env local |
| 10 | + python test_log_integration.py --env prod |
| 11 | +
|
| 12 | +Requires: |
| 13 | + - A running server (local or prod). |
| 14 | + - AWS credentials with s3:GetObject / s3:PutObject on |
| 15 | + s3://aind-scratch-data/aind-metadata-viz-logs/*. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import json |
| 21 | +import sys |
| 22 | +import uuid |
| 23 | +from datetime import datetime, timezone |
| 24 | + |
| 25 | +import boto3 |
| 26 | +import requests |
| 27 | + |
| 28 | +from test_config import parse_test_args |
| 29 | + |
| 30 | +_S3_BUCKET = "aind-scratch-data" |
| 31 | +_S3_PREFIX = "aind-metadata-viz-logs" |
| 32 | + |
| 33 | + |
| 34 | +def check(label: str, condition: bool, detail: str = "") -> bool: |
| 35 | + status = "OK " if condition else "FAIL" |
| 36 | + print(f"[{status}] {label}" + (f": {detail}" if detail else "")) |
| 37 | + return condition |
| 38 | + |
| 39 | + |
| 40 | +def _log_key(date_str: str) -> str: |
| 41 | + return f"{_S3_PREFIX}/chat_log_{date_str}.json" |
| 42 | + |
| 43 | + |
| 44 | +def _read_log_lines(date_str: str) -> list[dict]: |
| 45 | + s3 = boto3.client("s3") |
| 46 | + try: |
| 47 | + resp = s3.get_object(Bucket=_S3_BUCKET, Key=_log_key(date_str)) |
| 48 | + raw = resp["Body"].read().decode() |
| 49 | + except s3.exceptions.NoSuchKey: |
| 50 | + return [] |
| 51 | + except Exception as exc: |
| 52 | + print(f"[WARN] Could not read S3 log: {exc}") |
| 53 | + return [] |
| 54 | + records = [] |
| 55 | + for line in raw.splitlines(): |
| 56 | + line = line.strip() |
| 57 | + if line: |
| 58 | + try: |
| 59 | + records.append(json.loads(line)) |
| 60 | + except json.JSONDecodeError: |
| 61 | + pass |
| 62 | + return records |
| 63 | + |
| 64 | + |
| 65 | +def run_log_tests(base_url: str) -> bool: |
| 66 | + all_passed = True |
| 67 | + chat_url = f"{base_url}/chat" |
| 68 | + requester_id = f"log-integration-test-{uuid.uuid4().hex[:8]}" |
| 69 | + today_utc = datetime.now(timezone.utc).strftime("%Y-%m-%d") |
| 70 | + |
| 71 | + print(f"\n--- Chat log integration tests (id={requester_id}) ---") |
| 72 | + |
| 73 | + print("\n[Test 1] POST /chat with ?id= writes a log record to S3") |
| 74 | + resp = requests.post( |
| 75 | + chat_url, |
| 76 | + params={"id": requester_id}, |
| 77 | + json={"message": "Say the word 'hello' and nothing else."}, |
| 78 | + timeout=120, |
| 79 | + ) |
| 80 | + passed = check("Status 200", resp.status_code == 200, str(resp.status_code)) |
| 81 | + if not passed: |
| 82 | + print(f" Response: {resp.text[:200]}") |
| 83 | + all_passed = False |
| 84 | + return all_passed |
| 85 | + |
| 86 | + agent_response = resp.json().get("response", "") |
| 87 | + passed &= check("response non-empty", bool(agent_response)) |
| 88 | + all_passed &= passed |
| 89 | + |
| 90 | + print("\n[Test 2] Log record exists in S3 with correct fields") |
| 91 | + records = _read_log_lines(today_utc) |
| 92 | + matching = [r for r in records if r.get("requester_id") == requester_id] |
| 93 | + passed = check( |
| 94 | + "at least one log record with requester_id", |
| 95 | + len(matching) >= 1, |
| 96 | + f"{len(matching)} found", |
| 97 | + ) |
| 98 | + all_passed &= passed |
| 99 | + |
| 100 | + if matching: |
| 101 | + record = matching[-1] |
| 102 | + all_passed &= check( |
| 103 | + "timestamp present", |
| 104 | + bool(record.get("timestamp")), |
| 105 | + record.get("timestamp", ""), |
| 106 | + ) |
| 107 | + all_passed &= check( |
| 108 | + "message matches", |
| 109 | + record.get("message") == "Say the word 'hello' and nothing else.", |
| 110 | + ) |
| 111 | + all_passed &= check( |
| 112 | + "response matches agent response", |
| 113 | + record.get("response") == agent_response, |
| 114 | + ) |
| 115 | + all_passed &= check( |
| 116 | + "stop_reason present", bool(record.get("stop_reason")) |
| 117 | + ) |
| 118 | + all_passed &= check( |
| 119 | + "iterations is int", isinstance(record.get("iterations"), int) |
| 120 | + ) |
| 121 | + all_passed &= check( |
| 122 | + "tool_call_count is int", |
| 123 | + isinstance(record.get("tool_call_count"), int), |
| 124 | + ) |
| 125 | + |
| 126 | + print("\n[Test 3] POST /chat without ?id= logs requester_id as null") |
| 127 | + null_id_marker = f"null-id-test-{uuid.uuid4().hex[:8]}" |
| 128 | + resp2 = requests.post( |
| 129 | + chat_url, |
| 130 | + json={"message": f"Reply with the exact phrase: {null_id_marker}"}, |
| 131 | + timeout=120, |
| 132 | + ) |
| 133 | + passed = check("Status 200", resp2.status_code == 200, str(resp2.status_code)) |
| 134 | + if passed: |
| 135 | + records2 = _read_log_lines(today_utc) |
| 136 | + null_id_records = [ |
| 137 | + r |
| 138 | + for r in records2 |
| 139 | + if r.get("requester_id") is None |
| 140 | + and null_id_marker in r.get("message", "") |
| 141 | + ] |
| 142 | + all_passed &= check( |
| 143 | + "record with null requester_id written", |
| 144 | + len(null_id_records) >= 1, |
| 145 | + f"{len(null_id_records)} found", |
| 146 | + ) |
| 147 | + all_passed &= passed |
| 148 | + |
| 149 | + return all_passed |
| 150 | + |
| 151 | + |
| 152 | +def main() -> None: |
| 153 | + args = parse_test_args() |
| 154 | + base_url = ( |
| 155 | + "https://metadata-portal.allenneuraldynamics-test.org" |
| 156 | + if args.env == "prod" |
| 157 | + else "http://localhost:5006" |
| 158 | + ) |
| 159 | + |
| 160 | + print(f"Testing chat logging against: {base_url}") |
| 161 | + print(f"S3 log bucket: s3://{_S3_BUCKET}/{_S3_PREFIX}/") |
| 162 | + print("=" * 80) |
| 163 | + |
| 164 | + ok = run_log_tests(base_url) |
| 165 | + |
| 166 | + print("\n" + "=" * 80) |
| 167 | + if ok: |
| 168 | + print("All log integration tests passed.") |
| 169 | + else: |
| 170 | + print("Some log integration tests failed.") |
| 171 | + sys.exit(1) |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == "__main__": |
| 175 | + main() |
0 commit comments