Files
douyin_guaji-main/tools/test_web_gui.py
T
Your Name c67f22f76f feat: Refactor and reorganize project structure with new modules and files
- Deleted obsolete files including test scripts and configuration files to streamline the project.
- Introduced new modules for handling Douyin functionalities, including core operations, logging, and GUI components.
- Updated import paths to reflect the new module structure, enhancing code organization and maintainability.
- Added configuration files and documentation to support the new structure and improve user guidance.
2025-12-28 14:16:40 +08:00

329 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Web 端自動化巡檢腳本
====================
用途:
- 打開 Web GUI(預設 http://127.0.0.1:8000/)
- 點擊「開始運行」
- 週期性採集:
- 日誌區域:<pre id="log">
- 實時截圖:<img id="liveShot">
- 在本地保留整個測試期間的所有截圖,並將每次截圖時的日誌文本一併保存,方便一一對應排查。
依賴:
pip install playwright
playwright install
用法示例(PowerShell)::
cd C:\\Users\\12742\\Desktop\\douyin_guaji-main
python -m tools.test_web_gui ^
--url http://127.0.0.1:8000 ^
--duration-seconds 300 ^
--interval-seconds 5 ^
--output-dir web_test_artifacts
注意:
- 本腳本只負責 Web 前端監控,不會啟動後端服務;
請先確保你的 Web GUI(例如 web_gui.py / webgui_launcher.py)已經在本機監聽 8000 埠。
- 爲了測得更全面,建議在測試前先配置好 Web GUI 的各種選項(福袋條件、定時禁搶、預約、高價值回訪等),
然後再跑本腳本。
"""
from __future__ import annotations
import argparse
import asyncio
import json
import textwrap
from dataclasses import dataclass, asdict
from datetime import datetime
from pathlib import Path
from typing import List, Optional
import shutil
from playwright.async_api import async_playwright, Page
LOG_SELECTOR = "pre#log"
SHOT_SELECTOR = "img#liveShot"
@dataclass
class SampleRecord:
index: int
timestamp: str
screenshot_path: str
log_path: str
log_tail: str
async def _click_button_if_exists(page: Page, name: str) -> bool:
"""按 aria-label/文字內容尋找對應按鈕並點擊。"""
try:
button = page.get_by_role("button", name=name)
if await button.count() > 0:
await button.first.click()
return True
except Exception:
# 測試腳本不因一次點擊失敗而中止
return False
return False
async def _ensure_started(page: Page) -> None:
"""嘗試點擊「開始運行」啟動 Web GUI 後端任務。"""
# 先嘗試點「刷新設備」,避免沒有設備時直接失敗
await _click_button_if_exists(page, "刷新设备")
await asyncio.sleep(2.0) # 增加等待時間,確保設備列表刷新完成
# 檢查是否有設備可用
try:
# 嘗試讀取日誌,看是否有設備相關信息
log_element = await page.query_selector(LOG_SELECTOR)
if log_element:
log_text = await log_element.inner_text()
if "未检测到设备" in log_text or "未发现设备" in log_text:
print("[警告] Web GUI 顯示未檢測到設備,請確認:")
print(" 1. 手機已通過 USB 連接電腦")
print(" 2. 已開啟 USB 調試並授權")
print(" 3. 在命令行運行 'adb devices' 能看到設備")
except Exception:
pass
# 點擊「開始運行」
clicked = await _click_button_if_exists(page, "开始运行")
if clicked:
print("[測試腳本] 已點擊「開始運行」按鈕")
await asyncio.sleep(3.0) # 等待後端啟動子進程
# 再次檢查日誌,確認是否真的啟動了
try:
log_element = await page.query_selector(LOG_SELECTOR)
if log_element:
log_text = await log_element.inner_text()
if "[啟動]" in log_text or "[主循環]" in log_text or "設備分辨率" in log_text:
print("[測試腳本] ✓ 掛機進程似乎已啟動(日誌中有啟動相關信息)")
elif "already running" in log_text or "已在運行" in log_text:
print("[測試腳本] ⚠ Web GUI 顯示任務已在運行中")
else:
print("[測試腳本] ⚠ 未在日誌中看到明顯的啟動信息,可能:")
print(" - 設備未選擇或未連接")
print(" - 後端啟動子進程失敗")
print(" - 請手動在瀏覽器中檢查 Web GUI 的日誌區域")
except Exception:
pass
else:
print("[測試腳本] ⚠ 未能點擊「開始運行」按鈕,可能按鈕不存在或頁面未完全加載")
async def _ensure_stopped(page: Page) -> None:
"""測試結束時,嘗試點擊「停止」按鈕。"""
await _click_button_if_exists(page, "停止")
async def run_web_test(
url: str,
duration_seconds: int,
interval_seconds: float,
output_dir: Path,
) -> List[SampleRecord]:
"""主測試邏輯。
- 打開頁面並嘗試點「開始運行」
- 在整個 duration_seconds 期間,每 interval_seconds:
- 讀取 #log 文字並寫入 .log 檔
- 對 #liveShot 做元素截圖,保存為 .png
- 記錄 index / timestamp / 檔名 / 日誌尾部(方便快速總覽)
"""
output_dir.mkdir(parents=True, exist_ok=True)
screenshots_dir = output_dir / "screenshots"
logs_dir = output_dir / "logs"
screenshots_dir.mkdir(exist_ok=True)
logs_dir.mkdir(exist_ok=True)
meta_records: List[SampleRecord] = []
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto(url)
# 等頁面穩定
await page.wait_for_timeout(2000)
# 儘量確保任務已經啟動
await _ensure_started(page)
start = datetime.utcnow()
end_time = start.timestamp() + duration_seconds
index = 0
last_log_text: Optional[str] = None
while datetime.utcnow().timestamp() < end_time:
now = datetime.utcnow()
timestamp_str = now.strftime("%Y-%m-%d_%H-%M-%S")
# 抓取日誌
log_element = await page.query_selector(LOG_SELECTOR)
log_text = ""
if log_element is not None:
try:
log_text = await log_element.inner_text()
except Exception:
log_text = ""
# 取日誌尾部幾行方便總覽
log_tail = ""
if log_text:
lines = [ln for ln in log_text.splitlines() if ln.strip()]
tail_lines = lines[-10:] if len(lines) > 10 else lines
log_tail = "\n".join(tail_lines)
# 保存完整日誌到檔案
log_filename = f"log_{index:04d}_{timestamp_str}.log"
log_path = logs_dir / log_filename
log_path.write_text(log_text, encoding="utf-8", errors="ignore")
# 抓取實時截圖元素
shot_element = await page.query_selector(SHOT_SELECTOR)
screenshot_filename = f"screenshot_{index:04d}_{timestamp_str}.png"
screenshot_path = screenshots_dir / screenshot_filename
if shot_element is not None:
try:
await shot_element.screenshot(path=str(screenshot_path))
except Exception:
# 如果元素截圖失敗,退而求其次截整頁
await page.screenshot(path=str(screenshot_path))
else:
# 找不到元素,同樣退回整頁截圖
await page.screenshot(path=str(screenshot_path))
record = SampleRecord(
index=index,
timestamp=timestamp_str,
screenshot_path=str(screenshot_path),
log_path=str(log_path),
log_tail=log_tail,
)
meta_records.append(record)
# 簡單在控制台輸出概況,幫助快速觀察測試是否卡死
has_new_log = log_text != last_log_text
last_log_text = log_text
summary_tail = textwrap.shorten(
log_tail.replace("\n", " / "), width=120, placeholder="..."
)
print(
f"[{index:04d}] {timestamp_str} "
f"new_log={has_new_log} "
f"screenshot={screenshot_filename} "
f"log_tail={summary_tail}"
)
index += 1
await asyncio.sleep(interval_seconds)
# 測試結束,嘗試點「停止」
await _ensure_stopped(page)
await browser.close()
# 把所有採樣記錄寫入 summary.json,方便後續分析
summary_path = output_dir / "summary.json"
summary_path.write_text(
json.dumps([asdict(r) for r in meta_records], ensure_ascii=False, indent=2),
encoding="utf-8",
)
print(f"\n測試完成,共生成 {len(meta_records)} 組截圖+日誌樣本,詳見:{output_dir}")
return meta_records
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="針對 Web GUI 的自動化巡檢腳本,監控 #log 與 #liveShot 並保存全部截圖。"
)
parser.add_argument(
"--url",
default="http://127.0.0.1:8000/",
help="Web GUI 的地址(預設: http://127.0.0.1:8000/)",
)
parser.add_argument(
"--duration-seconds",
type=int,
default=300,
help="整體測試時長(秒),預設 300 秒(5分鐘)",
)
parser.add_argument(
"--interval-seconds",
type=float,
default=5.0,
help="採樣間隔(秒),預設 5 秒保存一次截圖與日誌",
)
parser.add_argument(
"--output-dir",
type=str,
default="web_test_runs",
help="測試根目錄(會在其中按時間自動建立子目錄),用於保存本次測試的所有資料",
)
return parser.parse_args()
def _snapshot_context_files(run_root: Path) -> None:
"""在每次測試目錄下備份當前關鍵配置與狀態,方便之後一併打包分析。"""
project_root = Path(".").resolve()
context_dir = run_root / "context"
context_dir.mkdir(parents=True, exist_ok=True)
# 一些關鍵單檔:當前配置與入口/主流程
important_files = [
"config/config.json",
"run_cli.py",
"douyin/core/douyin_fudai.py",
"douyin/stage/douyin_stage.py",
"douyin_fudai_core.py",
"douyin_reservation.py",
"douyin_robot.py",
]
for name in important_files:
src = project_root / name
if src.exists():
shutil.copy2(src, context_dir / src.name)
# state 目錄(包括 reservations.json / high_value_rooms.json 等)
state_src = project_root / "state"
if state_src.is_dir():
state_dst = context_dir / "state"
shutil.copytree(state_src, state_dst, dirs_exist_ok=True)
def main() -> None:
args = parse_args()
root_dir = Path(args.output_dir)
# 爲每次測試建立單獨的子目錄,名稱帶時間戳,方便你直接整個資料夾打包給我分析
ts = datetime.now().strftime("run_%Y%m%d_%H%M%S")
run_root = root_dir / ts
run_root.mkdir(parents=True, exist_ok=True)
# 備份當前配置與狀態
_snapshot_context_files(run_root)
# 再在該目錄下建立 web 測試輸出
output_dir = run_root / "web_artifacts"
asyncio.run(
run_web_test(
url=args.url,
duration_seconds=args.duration_seconds,
interval_seconds=args.interval_seconds,
output_dir=output_dir,
)
)
if __name__ == "__main__":
main()