11package kotlinx.coroutines.sync
22
3- import kotlinx.coroutines.TestBase
4- import kotlinx.coroutines.cancelAndJoin
5- import kotlinx.coroutines.launch
6- import kotlinx.coroutines.yield
3+ import kotlinx.coroutines.*
74import kotlin.test.Test
85import kotlin.test.assertEquals
96import kotlin.test.assertFalse
@@ -140,4 +137,35 @@ class SemaphoreTest : TestBase() {
140137 job1.cancel()
141138 finish(6 )
142139 }
140+
141+ @Test
142+ fun testAcquiredPermits () = runTest {
143+ val semaphore = Semaphore (5 , acquiredPermits = 4 )
144+ assertEquals(semaphore.availablePermits, 1 )
145+ semaphore.acquire()
146+ assertEquals(semaphore.availablePermits, 0 )
147+ assertFalse(semaphore.tryAcquire())
148+ semaphore.release()
149+ assertEquals(semaphore.availablePermits, 1 )
150+ assertTrue(semaphore.tryAcquire())
151+ }
152+
153+ @Test
154+ fun testReleaseAcquiredPermits () = runTest {
155+ val semaphore = Semaphore (5 , acquiredPermits = 4 )
156+ assertEquals(semaphore.availablePermits, 1 )
157+ repeat(4 ) { semaphore.release() }
158+ assertEquals(5 , semaphore.availablePermits)
159+ assertFailsWith<IllegalStateException > { semaphore.release() }
160+ repeat(5 ) { assertTrue(semaphore.tryAcquire()) }
161+ assertFalse(semaphore.tryAcquire())
162+ }
163+
164+ @Test
165+ fun testIllegalArguments () {
166+ assertFailsWith<IllegalArgumentException > { Semaphore (- 1 , 0 ) }
167+ assertFailsWith<IllegalArgumentException > { Semaphore (0 , 0 ) }
168+ assertFailsWith<IllegalArgumentException > { Semaphore (1 , - 1 ) }
169+ assertFailsWith<IllegalArgumentException > { Semaphore (1 , 2 ) }
170+ }
143171}
0 commit comments