semaphore_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. // Copyright (C) 2018 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package semaphore
  7. import "testing"
  8. func TestZeroByteSemaphore(t *testing.T) {
  9. t.Parallel()
  10. // A semaphore with zero capacity is just a no-op.
  11. s := New(0)
  12. // None of these should block or panic
  13. s.Take(123)
  14. s.Take(456)
  15. s.Give(1 << 30)
  16. }
  17. func TestByteSemaphoreCapChangeUp(t *testing.T) {
  18. t.Parallel()
  19. // Waiting takes should unblock when the capacity increases
  20. s := New(100)
  21. s.Take(75)
  22. if s.available != 25 {
  23. t.Error("bad state after take")
  24. }
  25. gotit := make(chan struct{})
  26. go func() {
  27. s.Take(75)
  28. close(gotit)
  29. }()
  30. s.SetCapacity(155)
  31. <-gotit
  32. if s.available != 5 {
  33. t.Error("bad state after both takes")
  34. }
  35. }
  36. func TestByteSemaphoreCapChangeDown1(t *testing.T) {
  37. t.Parallel()
  38. // Things should make sense when capacity is adjusted down
  39. s := New(100)
  40. s.Take(75)
  41. if s.available != 25 {
  42. t.Error("bad state after take")
  43. }
  44. s.SetCapacity(90)
  45. if s.available != 15 {
  46. t.Error("bad state after adjust")
  47. }
  48. s.Give(75)
  49. if s.available != 90 {
  50. t.Error("bad state after give")
  51. }
  52. }
  53. func TestByteSemaphoreCapChangeDown2(t *testing.T) {
  54. t.Parallel()
  55. // Things should make sense when capacity is adjusted down, different case
  56. s := New(100)
  57. s.Take(75)
  58. if s.available != 25 {
  59. t.Error("bad state after take")
  60. }
  61. s.SetCapacity(10)
  62. if s.available != 0 {
  63. t.Error("bad state after adjust")
  64. }
  65. s.Give(75)
  66. if s.available != 10 {
  67. t.Error("bad state after give")
  68. }
  69. }
  70. func TestByteSemaphoreGiveMore(t *testing.T) {
  71. t.Parallel()
  72. // We shouldn't end up with more available than we have capacity...
  73. s := New(100)
  74. s.Take(150)
  75. if s.available != 0 {
  76. t.Errorf("bad state after large take")
  77. }
  78. s.Give(150)
  79. if s.available != 100 {
  80. t.Errorf("bad state after large take + give")
  81. }
  82. s.Take(150)
  83. s.SetCapacity(125)
  84. // available was zero before, we're increasing capacity by 25
  85. if s.available != 25 {
  86. t.Errorf("bad state after setcap")
  87. }
  88. s.Give(150)
  89. if s.available != 125 {
  90. t.Errorf("bad state after large take + give with adjustment")
  91. }
  92. }