test_task_base.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import pytest
  2. from cq2_sdk.tasks.base import Task, TaskResult
  3. from cq2_sdk.tasks.registry import TaskRegistry
  4. from cq2_sdk.tasks.context import TaskContext
  5. from cq2_sdk.tasks.stubs import (
  6. T01CreateRole, T02DismissHint, T13Activity, _REGISTRY,
  7. )
  8. class FakeCtx:
  9. """Minimal stand-in for TaskContext (we only need it to construct the registry)."""
  10. pass
  11. @pytest.mark.asyncio
  12. async def test_task_subclass_runs():
  13. class T(Task):
  14. id = "fake"
  15. name = "Fake"
  16. async def run(self, ctx):
  17. return TaskResult(success=True, elapsed=0.123, error=None)
  18. t = T()
  19. r = await t.run(ctx=None)
  20. assert r.success
  21. assert r.elapsed == 0.123
  22. assert r.error is None
  23. @pytest.mark.asyncio
  24. async def test_task_failure_reported():
  25. class T(Task):
  26. id = "fail"
  27. name = "Fail"
  28. async def run(self, ctx):
  29. return TaskResult(success=False, elapsed=0.5, error="boom")
  30. t = T()
  31. r = await t.run(ctx=None)
  32. assert not r.success
  33. assert r.error == "boom"
  34. def test_all_13_tasks_registered():
  35. # All 13 in-game task IDs must be present
  36. for i in range(1, 14):
  37. tid = f"t{i:02d}"
  38. assert tid in _REGISTRY, f"missing {tid}"
  39. def test_task_ids_and_names():
  40. assert T01CreateRole.id == "t01"
  41. assert T01CreateRole.name == "Create role"
  42. assert T02DismissHint.id == "t02"
  43. assert T13Activity.id == "t13"
  44. def test_registry_lazy_instantiation():
  45. ctx = FakeCtx() # type: ignore[arg-type]
  46. reg = TaskRegistry(ctx) # type: ignore[arg-type]
  47. t1a = reg.t01
  48. t1b = reg.t01
  49. # Same instance returned (cached)
  50. assert t1a is t1b
  51. # Different tasks are different instances
  52. t2 = reg.t02
  53. assert t1a is not t2
  54. def test_registry_unknown_id_raises():
  55. ctx = FakeCtx() # type: ignore[arg-type]
  56. reg = TaskRegistry(ctx) # type: ignore[arg-type]
  57. with pytest.raises(AttributeError, match="No task"):
  58. reg.t99
  59. def test_registry_private_attr_raises():
  60. ctx = FakeCtx() # type: ignore[arg-type]
  61. reg = TaskRegistry(ctx) # type: ignore[arg-type]
  62. with pytest.raises(AttributeError):
  63. reg.__internal # double underscore triggers __getattr__
  64. def test_registry_all_ids_returns_13():
  65. ctx = FakeCtx() # type: ignore[arg-type]
  66. reg = TaskRegistry(ctx) # type: ignore[arg-type]
  67. assert len(reg.all_ids()) == 13
  68. assert "t01" in reg.all_ids()
  69. assert "t13" in reg.all_ids()