test_scheduler.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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_schedule_two_arg_repeats():
  35. """Schedule 两参调用(第三参缺省)按循环语义注册。"""
  36. rt = lj.LuaRuntime()
  37. install_scheduler(rt, Scheduler())
  38. rt.execute("n = 0; id = Schedule(function() n = n + 1 end, 0.05)")
  39. for _ in range(3):
  40. s = rt.globals()["SL_getScheduler"]()
  41. s.tick(0.05)
  42. assert rt.eval("n") == 3
  43. def test_cross_unschedule_within_tick():
  44. """A 到期回调里 UnSchedule(B) 不崩, 且 B 不再触发。"""
  45. rt = lj.LuaRuntime()
  46. s = Scheduler()
  47. install_scheduler(rt, s)
  48. rt.execute(
  49. "hits = 0; "
  50. "id_b = Schedule(function() hits = hits + 1 end, 0.05); "
  51. "Schedule(function() UnSchedule(id_b) end, 0.05)"
  52. )
  53. s.tick(0.05) # A、B 同时到期: A 先注册先遍历, 回调里取消 B
  54. s.tick(0.05)
  55. s.tick(0.05)
  56. assert rt.eval("hits") == 1
  57. def test_unschedule():
  58. s = Scheduler()
  59. hits = []
  60. eid = s.schedule(lambda: hits.append(1), 0.05)
  61. s.unschedule(eid)
  62. s.tick(0.05)
  63. assert hits == []