queue_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package queue
  2. import "testing"
  3. func TestQueueLength(t *testing.T) {
  4. q := New()
  5. if q.Length() != 0 {
  6. t.Error("empty queue length not 0")
  7. }
  8. for i := 0; i < 1000; i++ {
  9. q.Add(i)
  10. if q.Length() != i+1 {
  11. t.Error("adding: queue with", i, "elements has length", q.Length())
  12. }
  13. }
  14. for i := 0; i < 1000; i++ {
  15. q.Remove()
  16. if q.Length() != 1000-i-1 {
  17. t.Error("removing: queue with", 1000-i-i, "elements has length", q.Length())
  18. }
  19. }
  20. }
  21. func TestQueueGet(t *testing.T) {
  22. q := New()
  23. for i := 0; i < 1000; i++ {
  24. q.Add(i)
  25. for j := 0; j < q.Length(); j++ {
  26. if q.Get(j).(int) != j {
  27. t.Errorf("index %d doesn't contain %d", j, j)
  28. }
  29. }
  30. }
  31. }
  32. func TestQueueGetOutOfRangePanics(t *testing.T) {
  33. q := New()
  34. q.Add(1)
  35. q.Add(2)
  36. q.Add(3)
  37. func() {
  38. defer func() {
  39. if r := recover(); r == nil {
  40. t.Errorf("should panic when negative index")
  41. } else {
  42. t.Logf("got panic as expected: %v", r)
  43. }
  44. }()
  45. func() {
  46. q.Get(-1)
  47. }()
  48. }()
  49. func() {
  50. defer func() {
  51. if r := recover(); r == nil {
  52. t.Errorf("should panic when index greater than length")
  53. } else {
  54. t.Logf("got panic as expected: %v", r)
  55. }
  56. }()
  57. func() {
  58. q.Get(4)
  59. }()
  60. }()
  61. }
  62. // General warning: Go's benchmark utility (go test -bench .) increases the number of
  63. // iterations until the benchmarks take a reasonable amount of time to run; memory usage
  64. // is *NOT* considered. On my machine, these benchmarks hit around ~1GB before they've had
  65. // enough, but if you have less than that available and start swapping, then all bets are off.
  66. func BenchmarkQueueSerial(b *testing.B) {
  67. q := New()
  68. for i := 0; i < b.N; i++ {
  69. q.Add(nil)
  70. }
  71. for i := 0; i < b.N; i++ {
  72. q.Remove()
  73. }
  74. }
  75. func BenchmarkQueueTickTock(b *testing.B) {
  76. q := New()
  77. for i := 0; i < b.N; i++ {
  78. q.Add(nil)
  79. q.Remove()
  80. }
  81. }