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