website_content / backend /tests /run_tests.py
titusgiap's picture
Claude Opus 4.8
feat(analytics): tab "Quản lý thời lượng" theo dõi người dùng cho quản trị
00d2c12
Raw History Blame Contribute Delete
3.45 kB
#!/usr/bin/env python3
"""Bộ chạy test tự chứa — KHÔNG cần pytest.
Cách chạy:
cd backend && python3 tests/run_tests.py
Chỉ cần python3 + numpy + ffmpeg/ffprobe (đã có sẵn trong môi trường).
Quét mọi test_*.py trong thư mục tests/, chạy mọi hàm test_*; in PASS/FAIL.
Thoát mã != 0 nếu có test hỏng (để CI/đối tác biết là chưa đạt).
Nếu bạn có cài pytest, có thể chạy thay bằng: cd backend && pytest -q
"""
from __future__ import annotations
import importlib
import os
import sys
import traceback
HERE = os.path.dirname(os.path.abspath(__file__))
BACKEND = os.path.dirname(HERE)
if BACKEND not in sys.path:
sys.path.insert(0, BACKEND)
# VÙNG LÀM VIỆC RIÊNG CHO TEST — đặt TRƯỚC khi import bất kỳ module app nào.
# Không ép thì test dùng STORAGE_DIR thật trong .env: mỗi lần chạy vừa đổ thư mục
# rác vào đó, vừa kích hoạt cleanup_old xoá mất phiên làm việc thật của người dùng.
# Chỉ set biến môi trường là chưa đủ vì config load .env với override=True.
import tempfile # noqa: E402
_TEST_STORAGE = tempfile.mkdtemp(prefix="tnt_tests_")
os.environ["STORAGE_DIR"] = _TEST_STORAGE
try:
from app.config import settings as _settings
_settings.STORAGE_DIR = _TEST_STORAGE
except Exception: # pragma: no cover - thiếu deps thì để test tự báo lỗi
pass
GREEN, RED, DIM, BOLD, RESET = "\033[32m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"
def discover():
mods = []
for fn in sorted(os.listdir(HERE)):
if fn.startswith("test_") and fn.endswith(".py"):
mods.append("tests." + fn[:-3])
return mods
def main() -> int:
# đảm bảo import được gói "tests"
pkg_init = os.path.join(HERE, "__init__.py")
if not os.path.exists(pkg_init):
open(pkg_init, "w").close()
modules = discover()
total = passed = failed = 0
failures = []
print(f"{BOLD}TNT Content AI — bộ test luồng backend{RESET}")
print(f"{DIM}vùng làm việc test: {_TEST_STORAGE}{RESET}")
print(f"{DIM}python {sys.version.split()[0]} · {len(modules)} file test{RESET}\n")
for modname in modules:
try:
mod = importlib.import_module(modname)
except Exception:
print(f"{RED}✗ {modname} (lỗi import){RESET}")
traceback.print_exc()
failed += 1
failures.append(modname)
continue
tests = [getattr(mod, n) for n in dir(mod)
if n.startswith("test_") and callable(getattr(mod, n))]
short = modname.split(".")[-1]
print(f"{BOLD}{short}{RESET}")
for fn in tests:
total += 1
try:
fn()
passed += 1
print(f" {GREEN}✓{RESET} {fn.__name__}")
except Exception as e:
failed += 1
failures.append(f"{short}.{fn.__name__}")
print(f" {RED}✗ {fn.__name__} — {e}{RESET}")
traceback.print_exc()
print()
bar = GREEN if not failed else RED
print(f"{bar}{BOLD}Kết quả: {passed}/{total} PASS"
+ (f", {failed} FAIL" if failed else "") + RESET)
if failures:
print(f"{RED}Hỏng: {', '.join(failures)}{RESET}")
return 0 if failed == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())