Files

63 lines
2.2 KiB
Python

# -*- coding: utf-8 -*-
"""测试用的临时目录。
契约:**不要**写进仓库目录(`tests/_tmp`)——CI、只读挂载、沙箱都会让你挂掉,
而且会把垃圾留在 git 里。
挑法:先看 QINGLING_TEST_TMP,再试系统临时目录,最后才退到仓库内;
每个候选都真建一次 sqlite 文件,确认「能读能写能建库」才采用。
退到仓库内(沙箱不许写系统临时目录时)会先把 `tests/_tmp` 清空:那里的库是
上一次跑的,里面**体验授权早就过期**,留着会让 `require_active` 报
`ENTITLEMENT_EXPIRED`,看起来像代码坏了,其实是旧数据。
"""
from __future__ import annotations
import os
import shutil
import sqlite3
import tempfile
from pathlib import Path
_PICKED: Path | None = None
def _usable(p: Path) -> bool:
try:
p.mkdir(parents=True, exist_ok=True)
db = p / "_probe.db"
conn = sqlite3.connect(str(db))
try:
conn.execute("CREATE TABLE IF NOT EXISTS t (x INTEGER)")
conn.execute("INSERT INTO t VALUES (1)")
conn.commit()
finally:
conn.close()
db.unlink(missing_ok=True)
return True
except Exception:
return False
def workdir(name: str = "shared") -> Path:
"""返回一个确定可写的测试目录(进程内复用)。"""
global _PICKED
if _PICKED is None:
candidates = []
env = os.environ.get("QINGLING_TEST_TMP")
if env:
candidates.append(Path(env))
candidates.append(Path(tempfile.mkdtemp(prefix="qingling_test_")))
candidates.append(Path(__file__).resolve().parent / "_tmp")
for c in candidates:
if _usable(c):
_PICKED = c
break
else: # pragma: no cover
raise RuntimeError("找不到可写的测试目录,请设置 QINGLING_TEST_TMP")
if _PICKED == Path(__file__).resolve().parent / "_tmp":
shutil.rmtree(_PICKED, ignore_errors=True) # 清掉上一次的旧库(授权会过期)
p = _PICKED / name
p.mkdir(parents=True, exist_ok=True)
return p