/waiter/test/waiter/util/semaphore_test.clj

https://github.com/twosigma/waiter · Clojure · 47 lines · 30 code · 2 blank · 15 comment · 9 complexity · c7c26a281bbf6e2cf2da6af632cb3ba7 MD5 · raw file

  1. ;;
  2. ;; Copyright (c) Two Sigma Open Source, LLC
  3. ;;
  4. ;; Licensed under the Apache License, Version 2.0 (the "License");
  5. ;; you may not use this file except in compliance with the License.
  6. ;; You may obtain a copy of the License at
  7. ;;
  8. ;; http://www.apache.org/licenses/LICENSE-2.0
  9. ;;
  10. ;; Unless required by applicable law or agreed to in writing, software
  11. ;; distributed under the License is distributed on an "AS IS" BASIS,
  12. ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. ;; See the License for the specific language governing permissions and
  14. ;; limitations under the License.
  15. ;;
  16. (ns waiter.util.semaphore-test
  17. (:require [clojure.test :refer :all]
  18. [waiter.util.semaphore :refer :all])
  19. (:import (waiter.util.semaphore NonBlockingSemaphore)))
  20. (deftest test-counting-semaphore-creation
  21. (is (thrown? AssertionError (create-semaphore -1)))
  22. (is (thrown? AssertionError (create-semaphore 0)))
  23. (is (instance? NonBlockingSemaphore (create-semaphore 1)))
  24. (is (instance? NonBlockingSemaphore (create-semaphore 10))))
  25. (deftest test-counting-semaphore-operations
  26. (let [max-permits 4
  27. semaphore (create-semaphore max-permits)]
  28. (is (= max-permits (total-permits semaphore)))
  29. (is (= max-permits (available-permits semaphore)))
  30. (dotimes [n max-permits]
  31. (is (try-acquire! semaphore))
  32. (is (= (- max-permits n 1) (available-permits semaphore))))
  33. (dotimes [_ 10]
  34. (is (not (try-acquire! semaphore))))
  35. (is (= (- max-permits 1) (release! semaphore)))
  36. (is (= 1 (available-permits semaphore)))
  37. (is (try-acquire! semaphore))
  38. (is (zero? (available-permits semaphore)))
  39. (dotimes [n max-permits]
  40. (is (= (- max-permits n 1) (release! semaphore)))
  41. (is (= (inc n) (available-permits semaphore))))
  42. (is (thrown? IllegalStateException (release! semaphore)))
  43. (is (thrown? IllegalStateException (release! semaphore)))
  44. (is (try-acquire! semaphore))
  45. (is (= (dec max-permits) (available-permits semaphore)))))