Files

201 lines
7.5 KiB
Python
Raw Permalink 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.
# -*- coding: utf-8 -*-
"""v1.0.36:抓拍存到 D 盘 + 定期清理。
覆盖:目录解析、不可写回退、按天数淘汰、keep_min 保护、总量上限、
10 分钟内新文件不动、due/stamp 节拍、flow.snap_settings 读配置。
"""
import os
import sys
import time
import shutil
import tempfile
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
os.chdir(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from core.evidence import retention as R
from core.evidence import frames as F
from core.flow import FlowEngine
ok = fail = 0
def check(name, cond, extra=''):
global ok, fail
if cond:
ok += 1
print(' ✓', name)
else:
fail += 1
print(' ✗', name, extra)
def mk(d, n, size=1000, age_days=0.0):
"""造 n 个文件,age_days 越大越旧"""
made = []
base = time.time() - age_days * 86400
for i in range(n):
p = os.path.join(d, 'f%03d.jpg' % i)
with open(p, 'wb') as f:
f.write(b'x' * size)
t = base - i * 60
os.utime(p, (t, t))
made.append(p)
return made
print('① 目录解析')
cfg1 = {'storage': {'snapshot_dir': 'D:/入库分拣抓拍'}}
cfg2 = {'capture_dir': 'data/snapshots'}
cfg3 = {'storage': {'snapshot_dir': ''}, 'capture_dir': 'D:\\抓拍'}
check('绝对路径原样返回', F.snapshot_dir(cfg1) == os.path.normpath('D:/入库分拣抓拍'),
F.snapshot_dir(cfg1))
check('相对路径挂到程序目录', F.snapshot_dir(cfg2) == os.path.normpath(
os.path.join(F._ROOT, 'data/snapshots')), F.snapshot_dir(cfg2))
check('storage 优先于 capture_dir',
F.snapshot_dir({'storage': {'snapshot_dir': 'D:/a'}, 'capture_dir': 'data/b'})
== os.path.normpath('D:/a'))
check('storage 为空时退回 capture_dir',
F.snapshot_dir(cfg3) == os.path.normpath('D:\\抓拍'), F.snapshot_dir(cfg3))
check('都没有时用默认相对目录',
F.snapshot_dir({}) == os.path.normpath(os.path.join(F._ROOT, 'data/snapshots')))
check('相对路径结果是绝对路径', os.path.isabs(F.snapshot_dir(cfg2)))
print('② 不可写目录回退')
d_tmp = tempfile.mkdtemp(prefix='snap_')
# 造一个「父级是文件」的路径,必然建不出来
bad_parent = os.path.join(d_tmp, 'blocked')
open(bad_parent, 'wb').close()
bad = os.path.join(bad_parent, 'snap')
fs = F.FrameSource.__new__(F.FrameSource)
fs.snap_dir = bad
fs.snap_note = ''
fs._snap_ready = False
real = fs._snap_target()
check('回退到 data/snapshots',
os.path.normpath(real) == os.path.normpath(
os.path.join(F._ROOT, 'data', 'snapshots')), real)
check('留下说明文字', '不可写' in fs.snap_note, fs.snap_note)
check('只判定一次(第二次同结果)', fs._snap_target() == real and fs._snap_ready)
fs2 = F.FrameSource.__new__(F.FrameSource)
fs2.snap_dir = os.path.join(d_tmp, 'good')
fs2.snap_note = ''
fs2._snap_ready = False
check('可写目录直接使用', fs2._snap_target() == os.path.join(d_tmp, 'good'))
check('可写时不写说明', fs2.snap_note == '')
print('③ 按天数淘汰')
d1 = os.path.join(d_tmp, 'd1')
os.makedirs(d1)
mk(d1, 10, age_days=40) # 全超过 30 天
st = R.cleanup(d1, keep_days=30, keep_min=0, max_mb=0)
check('10 张全删(keep_min=0)', st['removed'] == 10, st)
check('目录清空', R.usage(d1)[0] == 0)
check('释放字节数正确', st['freed'] == 10 * 1000, st['freed'])
d2 = os.path.join(d_tmp, 'd2')
os.makedirs(d2)
mk(d2, 10, age_days=40)
st = R.cleanup(d2, keep_days=30, keep_min=3, max_mb=0)
check('keep_min=3 保住最新 3 张', st['removed'] == 7 and st['kept'] == 3, st)
check('剩下的确实是最新的',
all(os.path.exists(os.path.join(d2, 'f%03d.jpg' % i)) for i in range(3)),
sorted(os.listdir(d2)))
print('④ 10 分钟内新文件不动')
d3 = os.path.join(d_tmp, 'd3')
os.makedirs(d3)
mk(d3, 5, age_days=40)
fresh = os.path.join(d3, 'now.jpg')
open(fresh, 'wb').write(b'x' * 500)
st = R.cleanup(d3, keep_days=1, keep_min=0, max_mb=0)
check('刚写的文件保留', os.path.exists(fresh))
check('其余照删', st['removed'] == 5, st)
print('⑤ 总量上限')
d4 = os.path.join(d_tmp, 'd4')
os.makedirs(d4)
mk(d4, 20, size=100 * 1024, age_days=2) # 共 2MB
st = R.cleanup(d4, keep_days=365, keep_min=4, max_mb=1)
check('降到 1MB 左右', st['bytes_after'] <= 1024 * 1024, st['bytes_after'])
check('至少留 keep_min=4 张', st['kept'] >= 4, st['kept'])
check('删的是最旧的(新的还在)',
os.path.exists(os.path.join(d4, 'f000.jpg')))
print('⑥ 不超上限时一张不删')
d5 = os.path.join(d_tmp, 'd5')
os.makedirs(d5)
mk(d5, 5, size=1000, age_days=1)
st = R.cleanup(d5, keep_days=30, keep_min=0, max_mb=10)
check('removed=0', st['removed'] == 0, st)
check('全在', R.usage(d5)[0] == 5)
print('⑦ dry_run 不删')
d6 = os.path.join(d_tmp, 'd6')
os.makedirs(d6)
mk(d6, 4, age_days=99)
st = R.cleanup(d6, keep_days=1, keep_min=0, max_mb=0, dry_run=True)
check('dry_run 报 4 张', st['removed'] == 4, st)
check('文件还在', R.usage(d6)[0] == 4)
print('⑧ 定时节拍')
sdir = os.path.join(d_tmp, 'state')
os.makedirs(sdir)
sp = os.path.join(sdir, 'cleanup_state.json')
check('没记录时算到期', R.due(6.0, now=1000.0, path=sp) is True)
R.stamp({'dir': 'x', 'removed': 1, 'freed': 10, 'kept': 2,
'bytes_after': 20}, now=1000.0, path=sp)
check('刚清完不到期', R.due(6.0, now=2000.0, path=sp) is False)
check('6 小时后到期', R.due(6.0, now=1000.0 + 6 * 3600, path=sp) is True)
check('间隔 0 = 关闭定时', R.due(0, now=999999.0, path=sp) is False)
check('状态文件可回读', R.read_state(sp).get('removed') == 1)
print('⑨ flow.snap_settings')
e = FlowEngine.__new__(FlowEngine)
e.frames = type('F', (), {'snap_dir': 'D:/x'})()
e.cfg = {'storage': {'snapshot_dir': 'D:/入库分拣抓拍', 'keep_days': 7,
'keep_min': 50, 'max_mb': 800,
'clean_interval_h': 3},
'snapshot_keep_days': 30}
d, days, kmin, mb, iv = e.snap_settings()
check('目录取 frames.snap_dir', d == 'D:/x', d)
check('天数取 storage', days == 7, days)
check('keep_min/max_mb/间隔', (kmin, mb, iv) == (50, 800, 3), (kmin, mb, iv))
e.cfg = {'snapshot_keep_days': 12}
d, days, kmin, mb, iv = e.snap_settings()
check('无 storage 段用旧键', days == 12, days)
check('默认 keep_min=200', kmin == 200, kmin)
check('默认 max_mb=3000', mb == 3000, mb)
check('默认间隔 6 小时', iv == 6, iv)
e.cfg = {'storage': {'keep_days': 'abc', 'keep_min': None}}
d, days, kmin, mb, iv = e.snap_settings()
check('非法值回退默认', days == 30 and kmin == 200, (days, kmin))
print('⑩ 中文路径也能写(cv2.imwrite 会静默失败的那种路径)')
import numpy as np
cn = os.path.join(d_tmp, '入库分拣抓拍')
fs3 = F.FrameSource.__new__(F.FrameSource)
fs3.snap_dir = cn
fs3.snap_note = ''
fs3._snap_ready = False
img = np.full((120, 160, 3), 180, dtype=np.uint8)
p_cn = fs3._save(img, 88)
check('文件真的生成了', os.path.exists(p_cn), p_cn)
check('字节数 > 0', os.path.exists(p_cn) and os.path.getsize(p_cn) > 0,
os.path.getsize(p_cn) if os.path.exists(p_cn) else 0)
check('路径在中文目录下', os.path.dirname(p_cn) == cn, os.path.dirname(p_cn))
print('⑪ 人类可读体积')
check('KB', R.human(1536) == '1.5 KB',
R.human(1536))
check('MB', 'MB' in R.human(5 * 1024 * 1024), R.human(5 * 1024 * 1024))
check('GB', R.human(3 * 1024 ** 3).endswith('GB'), R.human(3 * 1024 ** 3))
check('0 不炸', R.human(0) == '0 B', R.human(0))
shutil.rmtree(d_tmp, ignore_errors=True)
print('\n%d 项通过,%d 项失败' % (ok, fail))
sys.exit(1 if fail else 0)