ring_test.go 997 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package collection
  2. import (
  3. "sync"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestNewRing(t *testing.T) {
  8. assert.Panics(t, func() {
  9. NewRing(0)
  10. })
  11. }
  12. func TestRingLess(t *testing.T) {
  13. ring := NewRing(5)
  14. for i := 0; i < 3; i++ {
  15. ring.Add(i)
  16. }
  17. elements := ring.Take()
  18. assert.ElementsMatch(t, []interface{}{0, 1, 2}, elements)
  19. }
  20. func TestRingMore(t *testing.T) {
  21. ring := NewRing(5)
  22. for i := 0; i < 11; i++ {
  23. ring.Add(i)
  24. }
  25. elements := ring.Take()
  26. assert.ElementsMatch(t, []interface{}{6, 7, 8, 9, 10}, elements)
  27. }
  28. func TestRingAdd(t *testing.T) {
  29. ring := NewRing(5051)
  30. wg := sync.WaitGroup{}
  31. for i := 1; i <= 100; i++ {
  32. wg.Add(1)
  33. go func(i int) {
  34. defer wg.Done()
  35. for j := 1; j <= i; j++ {
  36. ring.Add(i)
  37. }
  38. }(i)
  39. }
  40. wg.Wait()
  41. assert.Equal(t, 5050, len(ring.Take()))
  42. }
  43. func BenchmarkRingAdd(b *testing.B) {
  44. ring := NewRing(500)
  45. b.RunParallel(func(pb *testing.PB) {
  46. for pb.Next() {
  47. for i := 0; i < b.N; i++ {
  48. ring.Add(i)
  49. }
  50. }
  51. })
  52. }