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.

96 lines
2.1 KiB

  1. package buffered_queue
  2. import "testing"
  3. func TestJobQueue(t *testing.T) {
  4. type Job[T any] struct {
  5. ID int
  6. Action string
  7. Data T
  8. }
  9. queue := NewBufferedQueue[Job[string]](2, false) // Chunk size of 5
  10. queue.Enqueue(Job[string]{ID: 1, Action: "task1", Data: "hello"})
  11. queue.Enqueue(Job[string]{ID: 2, Action: "task2", Data: "world"})
  12. if queue.Size() != 2 {
  13. t.Errorf("Expected queue size of 2, got %d", queue.Size())
  14. }
  15. queue.Enqueue(Job[string]{ID: 3, Action: "task3", Data: "3!"})
  16. queue.Enqueue(Job[string]{ID: 4, Action: "task4", Data: "4!"})
  17. queue.Enqueue(Job[string]{ID: 5, Action: "task5", Data: "5!"})
  18. if queue.Size() != 5 {
  19. t.Errorf("Expected queue size of 5, got %d", queue.Size())
  20. }
  21. println("enqueued 5 items")
  22. println("dequeue", 1)
  23. job, ok := queue.Dequeue()
  24. if !ok {
  25. t.Errorf("Expected dequeue to return true")
  26. }
  27. if job.ID != 1 {
  28. t.Errorf("Expected job ID of 1, got %d", job.ID)
  29. }
  30. println("dequeue", 2)
  31. job, ok = queue.Dequeue()
  32. if !ok {
  33. t.Errorf("Expected dequeue to return true")
  34. }
  35. println("enqueue", 6)
  36. queue.Enqueue(Job[string]{ID: 6, Action: "task6", Data: "6!"})
  37. println("enqueue", 7)
  38. queue.Enqueue(Job[string]{ID: 7, Action: "task7", Data: "7!"})
  39. for i := 0; i < 5; i++ {
  40. println("dequeue ...")
  41. job, ok = queue.Dequeue()
  42. if !ok {
  43. t.Errorf("Expected dequeue to return true")
  44. }
  45. println("dequeued", job.ID)
  46. }
  47. if queue.Size() != 0 {
  48. t.Errorf("Expected queue size of 0, got %d", queue.Size())
  49. }
  50. for i := 0; i < 5; i++ {
  51. println("enqueue", i+8)
  52. queue.Enqueue(Job[string]{ID: i + 8, Action: "task", Data: "data"})
  53. }
  54. for i := 0; i < 5; i++ {
  55. job, ok = queue.Dequeue()
  56. if !ok {
  57. t.Errorf("Expected dequeue to return true")
  58. }
  59. if job.ID != i+8 {
  60. t.Errorf("Expected job ID of %d, got %d", i, job.ID)
  61. }
  62. println("dequeued", job.ID)
  63. }
  64. }
  65. func BenchmarkBufferedQueue(b *testing.B) {
  66. type Job[T any] struct {
  67. ID int
  68. Action string
  69. Data T
  70. }
  71. queue := NewBufferedQueue[Job[string]](1024, true)
  72. for i := 0; i < b.N; i++ {
  73. queue.Enqueue(Job[string]{ID: i, Action: "task", Data: "data"})
  74. }
  75. for i := 0; i < b.N; i++ {
  76. _, _ = queue.Dequeue()
  77. }
  78. }