test_avatar_s2.py 2.83 KB
#!/usr/bin/env python3
"""GREEN test for S2: /media/avatar/<username> endpoint."""
import subprocess, sys, hashlib

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

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

print("=== S2 GREEN: /media/avatar/<username> ===")

# Test known user with avatar
username = "wxid_51ap3m6p9xs722"
h = hashlib.md5(username.encode()).hexdigest()
avatar_dir = "/data/data/com.tencent.mm/MicroMsg/653cdc2320abb089e149a3f7a7683fcf/avatar"
path = f"{avatar_dir}/{h[:2]}/{h[2:4]}/user_hd_{h}.png"

# Verify file exists
r = subprocess.run(["su", "-c", f"test -f '{path}' && echo YES || echo NO"],
    capture_output=True, text=True, timeout=5)
disk_exists = "YES" in r.stdout
check(f"avatar file exists on disk", disk_exists)

# Call endpoint
r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}\n%{content_type}",
    f"{BASE}/media/avatar/{username}",
    "--connect-timeout", "5", "--max-time", "15"],
    capture_output=True, text=True, timeout=20)
lines = r.stdout.strip().split("\n")
code = int(lines[0]) if lines and lines[0].isdigit() else 0
ct = lines[1] if len(lines) > 1 else ""

check(f"/media/avatar/{username} → 200 + image",
      code == 200 and ct.startswith("image/"),
      f"got code={code}, ct={ct}")

# Test nonexistent user → 404
r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
    f"{BASE}/media/avatar/z_definitely_not_a_user_xyz",
    "--connect-timeout", "5", "--max-time", "10"],
    capture_output=True, text=True, timeout=15)
code = int(r.stdout.strip()) if r.stdout.strip().isdigit() else 0
check("nonexistent user → 404", code == 404, f"got {code}")

# Test filehelper (has avatar too)
r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}\n%{content_type}",
    f"{BASE}/media/avatar/filehelper",
    "--connect-timeout", "5", "--max-time", "10"],
    capture_output=True, text=True, timeout=15)
lines = r.stdout.strip().split("\n")
code = int(lines[0]) if lines and lines[0].isdigit() else 0
ct = lines[1] if len(lines) > 1 else ""
check("filehelper → 200 or 404 (depends on disk)", code in (200, 404), f"got {code}")

# Test content length > 0
if code == 200:
    r = subprocess.run(["curl", "-s", "-o", "/dev/null", "-w", "%{size_download}",
        f"{BASE}/media/avatar/{username}",
        "--connect-timeout", "5", "--max-time", "15"],
        capture_output=True, text=True, timeout=20)
    size = int(r.stdout.strip()) if r.stdout.strip().isdigit() else 0
    check(f"avatar has content (size={size})", size > 0, f"size={size}")

print(f"\n{'='*40}")
print(f"Results: {PASS} passed, {FAIL} failed")
if FAIL > 0:
    print("FAIL: Tests failed!")
    sys.exit(1)
else:
    print("GREEN: All tests passing!")
    sys.exit(0)