File size: 2,444 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import subprocess
import time
import os
import pathlib
import sys
import importlib
root = pathlib.Path(__file__).resolve().parents[1]
candidate_roots = [
pathlib.Path.cwd(),
root / 'environment' / 'code',
root / 'solution' / 'code',
root,
]
base = next((p for p in candidate_roots if p.exists()), root)
assert (base / 'original_go' / 'cron.go').exists(), f'missing original_go/cron.go in {base}'
assert (base / 'pycron').exists(), f'missing pycron package in {base}'
assert (base / 'example' / 'example.py').exists(), f'missing example/example.py in {base}'
assert (base / 'README.md').exists() and (base / 'README.md').stat().st_size > 0, f'missing README.md in {base}'
sys.path.insert(0, str(base))
mod = importlib.import_module('pycron')
assert hasattr(mod, 'CronScheduler'), 'pycron should expose CronScheduler'
assert hasattr(mod, 'IntervalSchedule'), 'pycron should expose IntervalSchedule'
env = os.environ.copy()
env["PYTHONPATH"] = str(base) + (os.pathsep + env.get("PYTHONPATH", ""))
proc = subprocess.run(
[sys.executable, str(base / 'example' / 'example.py')],
cwd=base,
env=env,
capture_output=True,
text=True,
timeout=5,
)
assert proc.returncode == 0, 'example/example.py should run successfully: ' + proc.stderr
assert proc.stdout.strip(), 'example output should show that the scheduled callback ran'
counter = {'count': 0}
scheduler = mod.CronScheduler()
assert hasattr(scheduler, 'add_interval_job'), 'CronScheduler missing add_interval_job'
assert hasattr(scheduler, 'start') and hasattr(scheduler, 'stop'), 'CronScheduler missing start/stop'
scheduler.add_interval_job(0.05, lambda: counter.__setitem__('count', counter['count'] + 1))
scheduler.start()
deadline = time.monotonic() + 2.0
while counter['count'] < 2 and time.monotonic() < deadline:
time.sleep(0.01)
scheduler.stop()
assert counter['count'] >= 2, f'interval job did not repeat within the execution budget: {counter["count"]}'
# stop() must actually halt the scheduler: no further ticks after stopping
count_at_stop = counter['count']
time.sleep(0.3)
assert counter['count'] == count_at_stop, (
f'stop() should halt the scheduler: ticked from {count_at_stop} to {counter["count"]} after stop'
)
readme = (base / 'README.md').read_text(encoding='utf-8', errors='ignore').lower()
assert any(term in readme for term in ('usage', '使用', '用法', '示例')), 'README should explain how to use the scheduler'
|