You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
1.9 KiB

  1. package testutils
  2. import (
  3. "fmt"
  4. lucifer3 "git.aiterp.net/lucifer3/server"
  5. "log"
  6. "math/rand"
  7. "sync/atomic"
  8. "testing"
  9. )
  10. type syncEvent struct {
  11. id uint64
  12. }
  13. func (s syncEvent) EventDescription() string {
  14. return fmt.Sprintf("syncEvent(%d)", s.id)
  15. }
  16. type TestEventLogger struct {
  17. entries []any
  18. syncN uint64
  19. syncCh chan struct{}
  20. }
  21. func (l *TestEventLogger) Active() bool {
  22. return true
  23. }
  24. func (l *TestEventLogger) Sync(bus *lucifer3.EventBus) {
  25. l.syncCh = make(chan struct{})
  26. v := rand.Int63()
  27. atomic.StoreUint64(&l.syncN, uint64(v))
  28. bus.RunEvent(syncEvent{id: uint64(v)})
  29. <-l.syncCh
  30. }
  31. func (l *TestEventLogger) AssertEvent(t *testing.T, eventStr string) {
  32. for i, entry := range l.entries {
  33. if event, ok := entry.(lucifer3.Event); ok && eventStr == event.EventDescription() {
  34. l.entries = l.entries[i+1:]
  35. return
  36. }
  37. }
  38. t.Errorf("Event not found: %s", eventStr)
  39. }
  40. func (l *TestEventLogger) AssertCommand(t *testing.T, commandStr string) {
  41. for i, entry := range l.entries {
  42. if cmd, ok := entry.(lucifer3.Command); ok {
  43. log.Println(cmd.CommandDescription() == commandStr)
  44. }
  45. if command, ok := entry.(lucifer3.Command); ok && commandStr == command.CommandDescription() {
  46. l.entries = l.entries[i+1:]
  47. return
  48. }
  49. }
  50. t.Errorf("Command not found: %s", commandStr)
  51. }
  52. func (l *TestEventLogger) HandleEvent(_ *lucifer3.EventBus, event lucifer3.Event) {
  53. if ev, ok := event.(syncEvent); ok {
  54. if atomic.CompareAndSwapUint64(&l.syncN, ev.id, 0) {
  55. close(l.syncCh)
  56. }
  57. }
  58. l.entries = append(l.entries, event)
  59. }
  60. func (l *TestEventLogger) HandleCommand(_ *lucifer3.EventBus, command lucifer3.Command) {
  61. l.entries = append(l.entries, command)
  62. }
  63. func evStr(ev any) string {
  64. if ev, ok := ev.(lucifer3.Event); ok {
  65. return ev.EventDescription()
  66. } else if ev, ok := ev.(lucifer3.Command); ok {
  67. return ev.CommandDescription()
  68. }
  69. panic("Unknown type")
  70. }