1 /* 2 * Copyright (C) 2021 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 static org.junit.Assert.assertThrows; 20 21 import android.test.AndroidTestCase; 22 23 import org.junit.Test; 24 25 import java.util.concurrent.atomic.AtomicBoolean; 26 import java.util.concurrent.atomic.AtomicInteger; 27 28 29 /** 30 * Tests for {@link SystemServiceManager}. 31 */ 32 public class SystemServiceManagerTest extends AndroidTestCase { 33 34 private static final String TAG = "SystemServiceManagerTest"; 35 36 private final SystemServiceManager mSystemServiceManager = 37 new SystemServiceManager(getContext()); 38 39 @Test testSealStartedServices()40 public void testSealStartedServices() throws Exception { 41 // must be effectively final, since it's changed from inner class below 42 AtomicBoolean serviceStarted = new AtomicBoolean(false); 43 SystemService service1 = new SystemService(getContext()) { 44 @Override 45 public void onStart() { 46 serviceStarted.set(true); 47 } 48 }; 49 SystemService service2 = new SystemService(getContext()) { 50 @Override 51 public void onStart() { 52 throw new IllegalStateException("Second service must not be called"); 53 } 54 }; 55 56 // started services have their #onStart methods called 57 mSystemServiceManager.startService(service1); 58 assertTrue(serviceStarted.get()); 59 60 // however, after locking started services, it is not possible to start a new service 61 mSystemServiceManager.sealStartedServices(); 62 assertThrows(UnsupportedOperationException.class, 63 () -> mSystemServiceManager.startService(service2)); 64 } 65 66 @Test testDuplicateServices()67 public void testDuplicateServices() throws Exception { 68 AtomicInteger counter = new AtomicInteger(0); 69 SystemService service = new SystemService(getContext()) { 70 @Override 71 public void onStart() { 72 counter.incrementAndGet(); 73 } 74 }; 75 76 mSystemServiceManager.startService(service); 77 assertEquals(1, counter.get()); 78 79 // manager does not start the same service twice 80 mSystemServiceManager.startService(service); 81 assertEquals(1, counter.get()); 82 } 83 84 @Test onUserCompletedEventShouldNotThrowExceptionWithStoppedOrUnknownUser()85 public void onUserCompletedEventShouldNotThrowExceptionWithStoppedOrUnknownUser() { 86 mSystemServiceManager.onUserCompletedEvent(99, 87 SystemService.UserCompletedEventType.EVENT_TYPE_USER_STARTING); 88 } 89 90 } 91