1
1
package kotlinx.coroutines.sync
2
2
3
- import kotlinx.coroutines.TestBase
4
- import kotlinx.coroutines.cancelAndJoin
5
- import kotlinx.coroutines.launch
6
- import kotlinx.coroutines.yield
3
+ import kotlinx.coroutines.*
7
4
import kotlin.test.Test
8
5
import kotlin.test.assertEquals
9
6
import kotlin.test.assertFalse
@@ -140,4 +137,35 @@ class SemaphoreTest : TestBase() {
140
137
job1.cancel()
141
138
finish(6 )
142
139
}
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
+ }
143
171
}
0 commit comments