bytesemaphore_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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 model
  7. import "testing"
  8. func TestZeroByteSempahore(t *testing.T) {
  9. // A semaphore with zero capacity is just a no-op.
  10. s := newByteSemaphore(0)
  11. // None of these should block or panic
  12. s.take(123)
  13. s.take(456)
  14. s.give(1 << 30)
  15. }
  16. func TestByteSempahoreCapChangeUp(t *testing.T) {
  17. // Waiting takes should unblock when the capacity increases
  18. s := newByteSemaphore(100)
  19. s.take(75)
  20. if s.available != 25 {
  21. t.Error("bad state after take")
  22. }
  23. gotit := make(chan struct{})
  24. go func() {
  25. s.take(75)
  26. close(gotit)
  27. }()
  28. s.setCapacity(155)
  29. <-gotit
  30. if s.available != 5 {
  31. t.Error("bad state after both takes")
  32. }
  33. }
  34. func TestByteSempahoreCapChangeDown1(t *testing.T) {
  35. // Things should make sense when capacity is adjusted down
  36. s := newByteSemaphore(100)
  37. s.take(75)
  38. if s.available != 25 {
  39. t.Error("bad state after take")
  40. }
  41. s.setCapacity(90)
  42. if s.available != 15 {
  43. t.Error("bad state after adjust")
  44. }
  45. s.give(75)
  46. if s.available != 90 {
  47. t.Error("bad state after give")
  48. }
  49. }
  50. func TestByteSempahoreCapChangeDown2(t *testing.T) {
  51. // Things should make sense when capacity is adjusted down, different case
  52. s := newByteSemaphore(100)
  53. s.take(75)
  54. if s.available != 25 {
  55. t.Error("bad state after take")
  56. }
  57. s.setCapacity(10)
  58. if s.available != 0 {
  59. t.Error("bad state after adjust")
  60. }
  61. s.give(75)
  62. if s.available != 10 {
  63. t.Error("bad state after give")
  64. }
  65. }
  66. func TestByteSempahoreGiveMore(t *testing.T) {
  67. // We shouldn't end up with more available than we have capacity...
  68. s := newByteSemaphore(100)
  69. s.take(150)
  70. if s.available != 0 {
  71. t.Errorf("bad state after large take")
  72. }
  73. s.give(150)
  74. if s.available != 100 {
  75. t.Errorf("bad state after large take + give")
  76. }
  77. s.take(150)
  78. s.setCapacity(125)
  79. // available was zero before, we're increasing capacity by 25
  80. if s.available != 25 {
  81. t.Errorf("bad state after setcap")
  82. }
  83. s.give(150)
  84. if s.available != 125 {
  85. t.Errorf("bad state after large take + give with adjustment")
  86. }
  87. }