1 /* 2 * Copyright (C) 2022 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.power.stats; 18 19 import static androidx.test.InstrumentationRegistry.getContext; 20 21 import static org.junit.Assert.fail; 22 23 import android.os.BatteryConsumer; 24 import android.os.BatteryStatsManager; 25 import android.os.BatteryUsageStats; 26 import android.os.BatteryUsageStatsQuery; 27 import android.os.UidBatteryConsumer; 28 29 import org.junit.Test; 30 31 /** 32 * Test BatteryStatsManager and CellularBatteryStats to ensure that valid data is being reported 33 * and that invalid data is not reported. 34 */ 35 public class BatteryStatsManagerTest { 36 37 @Test testBatteryUsageStatsDataConsistency()38 public void testBatteryUsageStatsDataConsistency() { 39 BatteryStatsManager bsm = getContext().getSystemService(BatteryStatsManager.class); 40 BatteryUsageStats stats = bsm.getBatteryUsageStats( 41 new BatteryUsageStatsQuery.Builder().setMaxStatsAgeMs( 42 0).includeProcessStateData().build()); 43 final int[] components = 44 {BatteryConsumer.POWER_COMPONENT_CPU, 45 BatteryConsumer.POWER_COMPONENT_MOBILE_RADIO, 46 BatteryConsumer.POWER_COMPONENT_WIFI, 47 BatteryConsumer.POWER_COMPONENT_BLUETOOTH}; 48 final int[] states = 49 {BatteryConsumer.PROCESS_STATE_FOREGROUND, 50 BatteryConsumer.PROCESS_STATE_BACKGROUND, 51 BatteryConsumer.PROCESS_STATE_FOREGROUND_SERVICE, 52 BatteryConsumer.PROCESS_STATE_CACHED}; 53 for (UidBatteryConsumer ubc : stats.getUidBatteryConsumers()) { 54 for (int component : components) { 55 double consumedPower = ubc.getConsumedPower(ubc.getKey(component)); 56 double sumStates = 0; 57 for (int state : states) { 58 sumStates += ubc.getConsumedPower(ubc.getKey(component, state)); 59 } 60 if (sumStates > consumedPower + 0.1) { 61 fail("Sum of states exceeds total. UID = " + ubc.getUid() + " " 62 + BatteryConsumer.powerComponentIdToString(component) 63 + " total = " + consumedPower + " states = " + sumStates); 64 } 65 } 66 } 67 } 68 } 69