test_scheduler.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # tests/test_scheduler.py
  2. import lupa.luajit21 as lj
  3. from apilot.stubs.scheduler import Scheduler, install_scheduler
  4. def test_interval_and_oneshot():
  5. s = Scheduler()
  6. hits = []
  7. s.schedule(lambda: hits.append("i"), 0.05)
  8. s.delay(lambda: hits.append("d"), 0.1)
  9. for _ in range(30):
  10. s.tick(0.05)
  11. assert hits.count("i") >= 2
  12. assert hits.count("d") == 1
  13. def test_lua_side_globals():
  14. rt = lj.LuaRuntime()
  15. from apilot.stubs.noop import install_noop_globals
  16. install_noop_globals(rt)
  17. s = Scheduler()
  18. install_scheduler(rt, s)
  19. rt.execute("global = global or {}; global.Scheduler = SL_getScheduler()")
  20. # install_scheduler 需暴露一个 Lua 可达引用; 简化: 直接用注入的全局函数
  21. rt.execute("n = 0; id = PerformWithDelayGlobal(function() n = n + 1 end, 0)")
  22. for _ in range(3):
  23. s.tick(0.05)
  24. assert rt.eval("n") == 1
  25. def test_schedule_repeats():
  26. """Schedule 第三参为 nil 时按循环语义注册。"""
  27. rt = lj.LuaRuntime()
  28. install_scheduler(rt, Scheduler())
  29. rt.execute("n = 0; id = Schedule(function() n = n + 1 end, 0.05, nil)")
  30. for _ in range(3):
  31. s = rt.globals()["SL_getScheduler"]()
  32. s.tick(0.05)
  33. assert rt.eval("n") == 3
  34. def test_unschedule():
  35. s = Scheduler()
  36. hits = []
  37. eid = s.schedule(lambda: hits.append(1), 0.05)
  38. s.unschedule(eid)
  39. s.tick(0.05)
  40. assert hits == []