test_s1_message_routes.py 2.77 KB
#!/usr/bin/env python3
"""Test S1: GET /messages and GET /message/<talker> routes."""
import subprocess, sys, urllib.parse

BASE = "http://127.0.0.1:5000"
PASS = 0
FAIL = 0

def check(name, condition, detail=""):
    global PASS, FAIL
    if condition:
        PASS += 1
        print(f"  ✅ {name}")
    else:
        FAIL += 1
        print(f"  ❌ {name} -- {detail}")
    return condition

def curl(url, follow_redirect=False):
    """Curl and return (status_code, headers_dict, body)."""
    args = ["curl", "-s", "-i", "-o", "-", "-w", "",
            "--connect-timeout", "5", "--max-time", "10"]
    args.append(url)
    r = subprocess.run(args, capture_output=True, text=True, timeout=15)
    raw = r.stdout
    # Parse headers and body
    if "\r\n\r\n" in raw:
        parts = raw.split("\r\n\r\n", 1)
    else:
        parts = raw.split("\n\n", 1)
    header_section = parts[0]
    body = parts[1] if len(parts) > 1 else ""
    # Parse status line
    lines = header_section.split("\n")
    status_line = lines[0] if lines else ""
    status_code = 0
    if "HTTP" in status_line:
        parts_status = status_line.split()
        if len(parts_status) >= 2:
            try:
                status_code = int(parts_status[1])
            except:
                pass
    headers = {}
    for line in lines[1:]:
        if ":" in line:
            k, v = line.split(":", 1)
            headers[k.strip().lower()] = v.strip()
    # For redirect, follow with -L
    if follow_redirect and status_code in (301, 302, 303, 307, 308):
        location = headers.get("location", "")
        if location:
            code2, h2, body2 = curl(location)
            return code2, h2, body2
    return status_code, headers, body

# TC1: GET /messages → 200
code, _, body = curl(f"{BASE}/messages")
check("TC1: GET /messages → 200", code == 200, f"got {code}")

# TC2: GET /message/<talker> → 302
code, headers, _ = curl(f"{BASE}/message/wxid_test123")
check("TC2: GET /message/<talker> → 302", code == 302, f"got {code}")

# TC3: Redirect Location points to /chat/<talker>
location = headers.get("location", "")
check("TC3: Location → /chat/wxid_test123", "/chat/wxid_test123" in location, f"got {location}")

# TC4: GET / → 200 (unaffected)
code, _, _ = curl(f"{BASE}/")
check("TC4: GET / → 200 still works", code == 200, f"got {code}")

# TC5: GET /chat/<talker> → 200 (unaffected)
code, _, _ = curl(f"{BASE}/chat/wxid_foo")
check("TC5: GET /chat/<talker> → 200 still works", code == 200, f"got {code}")

# TC6: /messages page has "消息浏览" in content
code, _, body = curl(f"{BASE}/messages")
check("TC6: /messages page contains 消息浏览", "消息浏览" in body, "page content mismatch")

print(f"\n{'='*40}")
print(f"Results: {PASS} passed, {FAIL} failed, {PASS+FAIL} total")
sys.exit(0 if FAIL == 0 else 1)