counter_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package log
  2. import (
  3. "sync"
  4. "testing"
  5. )
  6. func TestCounter_Ops(t *testing.T) {
  7. ctr := newCounter()
  8. var num int
  9. // Should return 0 if never seen
  10. num = ctr.count("something")
  11. if num != 0 {
  12. t.Fatalf("counter: count: expected %d; found %d", 0, num)
  13. }
  14. // Should return 1 if seen once
  15. num = ctr.increment("something")
  16. if num != 1 {
  17. t.Fatalf("counter: count: expected %d; found %d", 1, num)
  18. }
  19. // Should still return 1 if seen only once
  20. num = ctr.count("something")
  21. if num != 1 {
  22. t.Fatalf("counter: count: expected %d; found %d", 1, num)
  23. }
  24. // Should return 1 if seen once
  25. for i := 2; i <= 234; i++ {
  26. num = ctr.increment("something")
  27. if num != i {
  28. t.Fatalf("counter: count: expected %d; found %d", i, num)
  29. }
  30. }
  31. ctr.delete("something")
  32. num = ctr.count("something")
  33. if num != 0 {
  34. t.Fatalf("counter: count: expected %d; found %d", 0, num)
  35. }
  36. }
  37. func TestCounter_Threadsafety(t *testing.T) {
  38. var wg sync.WaitGroup
  39. // Run 1000 goroutines, logging 10000 times each as fast as they can
  40. for i := 1; i <= 1000; i++ {
  41. wg.Add(1)
  42. go func() {
  43. for j := 1; j <= 10000; j++ {
  44. DedupedInfof(10, "this log seen %d times", j)
  45. }
  46. wg.Done()
  47. }()
  48. }
  49. wg.Wait()
  50. }
  51. func TestDeduping(t *testing.T) {
  52. // Should log 10 times, then stop
  53. for i := 1; i <= 234; i++ {
  54. DedupedInfof(10, "this log seen %d times", i)
  55. }
  56. }