1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 
17 package com.android.server
18 
19 import androidx.test.filters.SmallTest
20 import androidx.test.runner.AndroidJUnit4
21 import com.android.server.NetIdManager.MIN_NET_ID
22 import com.android.testutils.assertThrows
23 import com.android.testutils.ExceptionUtils.ThrowingRunnable
24 import org.junit.Test
25 import org.junit.runner.RunWith
26 import kotlin.test.assertEquals
27 
28 @RunWith(AndroidJUnit4::class)
29 @SmallTest
30 class NetIdManagerTest {
31     @Test
testReserveReleaseNetIdnull32     fun testReserveReleaseNetId() {
33         val manager = NetIdManager(MIN_NET_ID + 4)
34         assertEquals(MIN_NET_ID, manager.reserveNetId())
35         assertEquals(MIN_NET_ID + 1, manager.reserveNetId())
36         assertEquals(MIN_NET_ID + 2, manager.reserveNetId())
37         assertEquals(MIN_NET_ID + 3, manager.reserveNetId())
38 
39         manager.releaseNetId(MIN_NET_ID + 1)
40         manager.releaseNetId(MIN_NET_ID + 3)
41         // IDs only loop once there is no higher ID available
42         assertEquals(MIN_NET_ID + 4, manager.reserveNetId())
43         assertEquals(MIN_NET_ID + 1, manager.reserveNetId())
44         assertEquals(MIN_NET_ID + 3, manager.reserveNetId())
45         assertThrows(IllegalStateException::class.java, ThrowingRunnable { manager.reserveNetId() })
46         manager.releaseNetId(MIN_NET_ID + 5)
47         // Still no ID available: MIN_NET_ID + 5 was not reserved
48         assertThrows(IllegalStateException::class.java, ThrowingRunnable { manager.reserveNetId() })
49         manager.releaseNetId(MIN_NET_ID + 2)
50         // Throwing an exception still leaves the manager in a working state
51         assertEquals(MIN_NET_ID + 2, manager.reserveNetId())
52     }
53 }