"""运行测试 - 写入项目目录"""
import subprocess
import sys
import os
import shutil

# 清除所有 __pycache__
backend_dir = r"C:\Users\simon\wecom_it_smart_desk\backend"
for root, dirs, files in os.walk(backend_dir):
    for d in dirs:
        if d == "__pycache__":
            try:
                shutil.rmtree(os.path.join(root, d))
            except:
                pass

python = r"C:\Users\simon\.workbuddy\binaries\python\envs\default\Scripts\python.exe"
env = {**os.environ, "PYTHONPATH": backend_dir, "PYTHONDONTWRITEBYTECODE": "1"}

result = subprocess.run(
    [python, "-B", "-m", "pytest",
     os.path.join(backend_dir, "tests"),
     "-v", "--tb=short", "-x", "--cache-clear"],
    capture_output=True, text=True,
    env=env,
    cwd=backend_dir
)

# 写到项目 deliverables 目录
out_dir = r"C:\Users\simon\wecom_it_smart_desk\deliverables"
os.makedirs(out_dir, exist_ok=True)

output = f"EXIT CODE: {result.returncode}\n\n=== STDOUT ===\n{result.stdout}\n\n=== STDERR ===\n{result.stderr}\n"

with open(os.path.join(out_dir, "test_results.txt"), "w", encoding="utf-8") as f:
    f.write(output)
