syncs_test.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package syncs
  5. import (
  6. "context"
  7. "testing"
  8. )
  9. func TestWaitGroupChan(t *testing.T) {
  10. wg := NewWaitGroupChan()
  11. wantNotDone := func() {
  12. t.Helper()
  13. select {
  14. case <-wg.DoneChan():
  15. t.Fatal("done too early")
  16. default:
  17. }
  18. }
  19. wantDone := func() {
  20. t.Helper()
  21. select {
  22. case <-wg.DoneChan():
  23. default:
  24. t.Fatal("expected to be done")
  25. }
  26. }
  27. wg.Add(2)
  28. wantNotDone()
  29. wg.Decr()
  30. wantNotDone()
  31. wg.Decr()
  32. wantDone()
  33. wantDone()
  34. }
  35. func TestClosedChan(t *testing.T) {
  36. ch := ClosedChan()
  37. for i := 0; i < 2; i++ {
  38. select {
  39. case <-ch:
  40. default:
  41. t.Fatal("not closed")
  42. }
  43. }
  44. }
  45. func TestSemaphore(t *testing.T) {
  46. s := NewSemaphore(2)
  47. s.Acquire()
  48. if !s.TryAcquire() {
  49. t.Fatal("want true")
  50. }
  51. if s.TryAcquire() {
  52. t.Fatal("want false")
  53. }
  54. ctx, cancel := context.WithCancel(context.Background())
  55. cancel()
  56. if s.AcquireContext(ctx) {
  57. t.Fatal("want false")
  58. }
  59. s.Release()
  60. if !s.AcquireContext(context.Background()) {
  61. t.Fatal("want true")
  62. }
  63. s.Release()
  64. s.Release()
  65. }