diff options
author | Jeffrey Huang <jeffreyhuang@google.com> | 2024-03-21 14:20:11 -0700 |
---|---|---|
committer | Jeffrey Huang <jeffreyhuang@google.com> | 2024-03-21 14:40:52 -0700 |
commit | c0d20b1b01b80ea19153cc66b3c3351e6d1692d3 (patch) | |
tree | 4e08d301081ef0e77192e15b447e59bc8717b31c | |
parent | 77b1a1d738840ff9e4ad36ef25de5ab4481fa5a7 (diff) | |
download | StatsD-c0d20b1b01b80ea19153cc66b3c3351e6d1692d3.tar.gz |
Reformat cts test files
Refactor ordinal() to getNumber()
Delete DeviceAtomTestCase, BaseTestCase, and AtomTestCase
Refactor ValidationTestUtil to be static class
Bug: 188731220
Test: m -j
Change-Id: Ie06151dd96a42075e57c69e2139f8010c715d2c4
15 files changed, 403 insertions, 2247 deletions
diff --git a/tests/src/android/cts/statsd/alarm/AlarmTests.java b/tests/src/android/cts/statsd/alarm/AlarmTests.java index 1ac5ec2e..0f49e9a2 100644 --- a/tests/src/android/cts/statsd/alarm/AlarmTests.java +++ b/tests/src/android/cts/statsd/alarm/AlarmTests.java @@ -87,20 +87,24 @@ public class AlarmTests extends DeviceTestCase implements IBuildReceiver { String markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); RunUtil.getDefault().sleep(9_000); - if (INCIDENTD_TESTS_ENABLED) assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); + if (INCIDENTD_TESTS_ENABLED) { + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); + } } private final StatsdConfig.Builder getBaseConfig() throws Exception { return ConfigUtils.createConfigBuilder(MetricsUtils.DEVICE_SIDE_TEST_PACKAGE) - .addAlarm(Alarm.newBuilder().setId(ALARM_ID).setOffsetMillis(2).setPeriodMillis( - 5_000) // every 5 seconds. + .addAlarm(Alarm.newBuilder() + .setId(ALARM_ID) + .setOffsetMillis(2) + .setPeriodMillis(5_000) // every 5 seconds. ) .addSubscription(Subscription.newBuilder() .setId(SUBSCRIPTION_ID_INCIDENTD) .setRuleType(Subscription.RuleType.ALARM) .setRuleId(ALARM_ID) - .setIncidentdDetails( - IncidentdDetails.newBuilder().addSection(INCIDENTD_SECTION))); + .setIncidentdDetails(IncidentdDetails.newBuilder() + .addSection(INCIDENTD_SECTION))); } } diff --git a/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java b/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java index ac3c4676..74fe1b55 100644 --- a/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java +++ b/tests/src/android/cts/statsd/alert/AnomalyDetectionTests.java @@ -166,39 +166,36 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei String markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); // count(label=6) -> 1 (not an anomaly, since not "greater than 2") AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 6); + AppBreadcrumbReported.State.START.getNumber(), 6); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); } // count(label=6) -> 2 (not an anomaly, since not "greater than 2") AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 6); + AppBreadcrumbReported.State.START.getNumber(), 6); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); } // count(label=12) -> 1 (not an anomaly, since not "greater than 2") AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 12); + AppBreadcrumbReported.State.START.getNumber(), 12); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_LONG); assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); } AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 6); // count(label=6) -> 3 (anomaly, since "greater than 2"!) RunUtil.getDefault().sleep(WAIT_AFTER_BREADCRUMB_MS); @@ -206,8 +203,7 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei assertWithMessage("Expected anomaly").that(data).hasSize(1); assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); } } @@ -237,23 +233,23 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei // Test that alarm doesn't fire early. String markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(6_000); // Recorded duration at end: 6s assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); RunUtil.getDefault().sleep(4_000); // Recorded duration at end: 6s assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); // Test that alarm does fire when it is supposed to (after 4s, plus up to 5s alarm delay). AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(9_000); // Recorded duration at end: 13s AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 2); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 2); List<EventMetricData> data = ReportUtils.getEventMetricDataList(getDevice()); assertWithMessage("Expected anomaly").that(data).hasSize(1); assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID); @@ -261,9 +257,9 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei // Now test that the refractory period is obeyed. markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(3_000); // Recorded duration at end: 13s // NB: the previous getEventMetricDataList also removes the report, so size is back to 0. assertWithMessage("Premature anomaly").that( @@ -271,24 +267,23 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei // Test that detection works again after refractory period finishes. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); RunUtil.getDefault().sleep(8_000); // Recorded duration at end: 9s AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(15_000); // Recorded duration at end: 15s // We can do an incidentd test now that all the timing issues are done. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 2); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 2); data = ReportUtils.getEventMetricDataList(getDevice()); assertWithMessage("Expected anomaly").that(data).hasSize(1); assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); } AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); } // Tests that anomaly detection for duration works even when the alarm fires too late. @@ -313,10 +308,10 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei ConfigUtils.uploadConfig(getDevice(), config); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(5_000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); RunUtil.getDefault().sleep(2_000); assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); @@ -326,11 +321,11 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei // It is likely that the alarm will only fire after this period is already over, but the // anomaly should nonetheless be detected when the event stops. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(1_200); // Anomaly should be detected here if the alarm didn't fire yet. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); RunUtil.getDefault().sleep(200); List<EventMetricData> data = ReportUtils.getEventMetricDataList(getDevice()); if (data.size() == 2) { @@ -360,18 +355,17 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei String markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 6); // value = 6, which is NOT > trigger RunUtil.getDefault().sleep(WAIT_AFTER_BREADCRUMB_MS); assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); } AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 14); // value = 14 > trigger RunUtil.getDefault().sleep(WAIT_AFTER_BREADCRUMB_MS); @@ -379,8 +373,7 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei assertWithMessage("Expected anomaly").that(data).hasSize(1); assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); } } @@ -417,7 +410,7 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei String markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 6); // value = 6, which is NOT > trigger RunUtil.getDefault().sleep(WAIT_AFTER_BREADCRUMB_MS); assertWithMessage("Premature anomaly").that( @@ -425,7 +418,7 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei if (PERFETTO_TESTS_ENABLED) assertThat(isSystemTracingEnabled()).isFalse(); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 14); // value = 14 > trigger RunUtil.getDefault().sleep(WAIT_AFTER_BREADCRUMB_MS); @@ -468,20 +461,19 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei String markTime = MetricsUtils.getCurrentLogcatDate(getDevice()); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 6); // gauge = 6, which is NOT > trigger RunUtil.getDefault().sleep( Math.max(WAIT_AFTER_BREADCRUMB_MS, 1_100)); // Must be >1s to push next bucket. assertWithMessage("Premature anomaly").that( ReportUtils.getEventMetricDataList(getDevice())).isEmpty(); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isFalse(); } // We waited for >1s above, so we are now in the next bucket (which is essential). AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), + AppBreadcrumbReported.State.START.getNumber(), 14); // gauge = 14 > trigger RunUtil.getDefault().sleep(WAIT_AFTER_BREADCRUMB_MS); @@ -489,8 +481,7 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei assertWithMessage("Expected anomaly").that(data).hasSize(1); assertThat(data.get(0).getAtom().getAnomalyDetected().getAlertId()).isEqualTo(ALERT_ID); if (INCIDENTD_TESTS_ENABLED) { - assertThat( - MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); + assertThat(MetricsUtils.didIncidentdFireSince(getDevice(), markTime)).isTrue(); } } @@ -537,67 +528,54 @@ public class AnomalyDetectionTests extends DeviceTestCase implements IBuildRecei long triggerIfSumGt) throws Exception { return ConfigUtils.createConfigBuilder(MetricsUtils.DEVICE_SIDE_TEST_PACKAGE) // Items of relevance for detecting the anomaly: - .addAtomMatcher( - StatsdConfigProto.AtomMatcher.newBuilder() - .setId(APP_BREADCRUMB_REPORTED_MATCH_START_ID) - .setSimpleAtomMatcher( - StatsdConfigProto.SimpleAtomMatcher.newBuilder() - .setAtomId( - Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - // Event only when the uid is this app's uid. - .addFieldValueMatcher(ConfigUtils.createFvm( - AppBreadcrumbReported.UID_FIELD_NUMBER) - .setEqInt(SHELL_UID)) - .addFieldValueMatcher( - ConfigUtils.createFvm( - AppBreadcrumbReported.STATE_FIELD_NUMBER) - .setEqInt( - AppBreadcrumbReported.State.START.ordinal())))) - .addAtomMatcher( - StatsdConfigProto.AtomMatcher.newBuilder() - .setId(APP_BREADCRUMB_REPORTED_MATCH_STOP_ID) - .setSimpleAtomMatcher( - StatsdConfigProto.SimpleAtomMatcher.newBuilder() - .setAtomId( - Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - // Event only when the uid is this app's uid. - .addFieldValueMatcher(ConfigUtils.createFvm( - AppBreadcrumbReported.UID_FIELD_NUMBER) - .setEqInt(SHELL_UID)) - .addFieldValueMatcher( - ConfigUtils.createFvm( - AppBreadcrumbReported.STATE_FIELD_NUMBER) - .setEqInt( - AppBreadcrumbReported.State.STOP.ordinal())))) + .addAtomMatcher(StatsdConfigProto.AtomMatcher.newBuilder() + .setId(APP_BREADCRUMB_REPORTED_MATCH_START_ID) + .setSimpleAtomMatcher(StatsdConfigProto.SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) // Event + // only when the uid is this app's uid. + .addFieldValueMatcher(ConfigUtils + .createFvm(AppBreadcrumbReported.UID_FIELD_NUMBER) + .setEqInt(SHELL_UID)) + .addFieldValueMatcher(ConfigUtils + .createFvm(AppBreadcrumbReported.STATE_FIELD_NUMBER) + .setEqInt(AppBreadcrumbReported.State.START.getNumber())))) + .addAtomMatcher(StatsdConfigProto.AtomMatcher.newBuilder() + .setId(APP_BREADCRUMB_REPORTED_MATCH_STOP_ID) + .setSimpleAtomMatcher(StatsdConfigProto.SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) + // Event only when the uid is this app's uid. + .addFieldValueMatcher(ConfigUtils + .createFvm(AppBreadcrumbReported.UID_FIELD_NUMBER) + .setEqInt(SHELL_UID)) + .addFieldValueMatcher(ConfigUtils + .createFvm(AppBreadcrumbReported.STATE_FIELD_NUMBER) + .setEqInt(AppBreadcrumbReported.State.STOP.getNumber())))) .addAlert(Alert.newBuilder() .setId(ALERT_ID) .setMetricId(METRIC_ID) // The metric itself must yet be added by the test. .setNumBuckets(numBuckets) .setRefractoryPeriodSecs(refractorySecs) .setTriggerIfSumGt(triggerIfSumGt)) - .addSubscription( - Subscription.newBuilder() - .setId(SUBSCRIPTION_ID_INCIDENTD) - .setRuleType(Subscription.RuleType.ALERT) - .setRuleId(ALERT_ID) - .setIncidentdDetails(IncidentdDetails.newBuilder().addSection( - INCIDENTD_SECTION))) + .addSubscription(Subscription.newBuilder() + .setId(SUBSCRIPTION_ID_INCIDENTD) + .setRuleType(Subscription.RuleType.ALERT) + .setRuleId(ALERT_ID) + .setIncidentdDetails(IncidentdDetails.newBuilder().addSection( + INCIDENTD_SECTION))) // We want to trigger anomalies on METRIC_ID, but don't want the actual data. .addNoReportMetric(METRIC_ID) // Items of relevance to reporting the anomaly (we do want this data): - .addAtomMatcher( - StatsdConfigProto.AtomMatcher.newBuilder() - .setId(ANOMALY_DETECT_MATCH_ID) - .setSimpleAtomMatcher( - StatsdConfigProto.SimpleAtomMatcher.newBuilder() - .setAtomId(Atom.ANOMALY_DETECTED_FIELD_NUMBER) - .addFieldValueMatcher(ConfigUtils.createFvm( - AnomalyDetected.CONFIG_UID_FIELD_NUMBER) - .setEqInt(SHELL_UID)) - .addFieldValueMatcher(ConfigUtils.createFvm( - AnomalyDetected.CONFIG_ID_FIELD_NUMBER) - .setEqInt(ConfigUtils.CONFIG_ID)))) + .addAtomMatcher(StatsdConfigProto.AtomMatcher.newBuilder() + .setId(ANOMALY_DETECT_MATCH_ID) + .setSimpleAtomMatcher(StatsdConfigProto.SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.ANOMALY_DETECTED_FIELD_NUMBER) + .addFieldValueMatcher(ConfigUtils + .createFvm(AnomalyDetected.CONFIG_UID_FIELD_NUMBER) + .setEqInt(SHELL_UID)) + .addFieldValueMatcher(ConfigUtils + .createFvm(AnomalyDetected.CONFIG_ID_FIELD_NUMBER) + .setEqInt(ConfigUtils.CONFIG_ID)))) .addEventMetric(StatsdConfigProto.EventMetric.newBuilder() .setId(ANOMALY_EVENT_ID) .setWhat(ANOMALY_DETECT_MATCH_ID)); diff --git a/tests/src/android/cts/statsd/atom/AtomTestCase.java b/tests/src/android/cts/statsd/atom/AtomTestCase.java deleted file mode 100644 index b0825a78..00000000 --- a/tests/src/android/cts/statsd/atom/AtomTestCase.java +++ /dev/null @@ -1,1265 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.cts.statsd.atom; - -import static android.cts.statsd.atom.DeviceAtomTestCase.DEVICE_SIDE_TEST_APK; -import static android.cts.statsd.atom.DeviceAtomTestCase.DEVICE_SIDE_TEST_PACKAGE; -import static com.google.common.truth.Truth.assertThat; -import static com.google.common.truth.Truth.assertWithMessage; - -import android.os.BatteryStatsProto; -import android.os.StatsDataDumpProto; -import android.service.battery.BatteryServiceDumpProto; -import android.service.batterystats.BatteryStatsServiceDumpProto; -import android.service.procstats.ProcessStatsServiceDumpProto; - -import com.android.annotations.Nullable; -import com.android.internal.os.StatsdConfigProto.AtomMatcher; -import com.android.internal.os.StatsdConfigProto.EventMetric; -import com.android.internal.os.StatsdConfigProto.FieldFilter; -import com.android.internal.os.StatsdConfigProto.FieldMatcher; -import com.android.internal.os.StatsdConfigProto.FieldValueMatcher; -import com.android.internal.os.StatsdConfigProto.GaugeMetric; -import com.android.internal.os.StatsdConfigProto.Predicate; -import com.android.internal.os.StatsdConfigProto.SimpleAtomMatcher; -import com.android.internal.os.StatsdConfigProto.SimplePredicate; -import com.android.internal.os.StatsdConfigProto.StatsdConfig; -import com.android.internal.os.StatsdConfigProto.TimeUnit; -import com.android.os.AtomsProto.AppBreadcrumbReported; -import com.android.os.AtomsProto.Atom; -import com.android.os.AtomsProto.ProcessStatsPackageProto; -import com.android.os.AtomsProto.ProcessStatsProto; -import com.android.os.AtomsProto.ProcessStatsStateProto; -import com.android.os.StatsLog; -import com.android.os.StatsLog.ConfigMetricsReport; -import com.android.os.StatsLog.ConfigMetricsReportList; -import com.android.os.StatsLog.CountMetricData; -import com.android.os.StatsLog.DurationMetricData; -import com.android.os.StatsLog.EventMetricData; -import com.android.os.StatsLog.GaugeBucketInfo; -import com.android.os.StatsLog.GaugeMetricData; -import com.android.os.StatsLog.StatsLogReport; -import com.android.os.StatsLog.StatsLogReport.GaugeMetricDataWrapper; -import com.android.os.StatsLog.ValueMetricData; -import com.android.tradefed.device.DeviceNotAvailableException; -import com.android.tradefed.log.LogUtil; -import com.android.tradefed.util.CommandResult; -import com.android.tradefed.util.CommandStatus; -import com.android.tradefed.util.Pair; - -import com.google.common.collect.Range; -import com.google.common.io.Files; -import com.google.protobuf.ByteString; -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Random; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import perfetto.protos.PerfettoConfig.DataSourceConfig; -import perfetto.protos.PerfettoConfig.FtraceConfig; -import perfetto.protos.PerfettoConfig.TraceConfig; - -/** - * Base class for testing Statsd atoms. - * Validates reporting of statsd logging based on different events - */ -public class AtomTestCase extends BaseTestCase { - - /** - * Run tests that are optional; they are not valid CTS tests per se, since not all devices can - * be expected to pass them, but can be run, if desired, to ensure they work when appropriate. - */ - public static final boolean OPTIONAL_TESTS_ENABLED = false; - - public static final String UPDATE_CONFIG_CMD = "cmd stats config update"; - public static final String DUMP_REPORT_CMD = "cmd stats dump-report"; - public static final String DUMP_BATTERY_CMD = "dumpsys battery"; - public static final String DUMP_BATTERYSTATS_CMD = "dumpsys batterystats"; - public static final String DUMPSYS_STATS_CMD = "dumpsys stats"; - public static final String DUMP_PROCSTATS_CMD = "dumpsys procstats"; - public static final String REMOVE_CONFIG_CMD = "cmd stats config remove"; - /** ID of the config, which evaluates to -1572883457. */ - public static final long CONFIG_ID = "cts_config".hashCode(); - - public static final String FEATURE_AUDIO_OUTPUT = "android.hardware.audio.output"; - public static final String FEATURE_AUTOMOTIVE = "android.hardware.type.automotive"; - public static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth"; - public static final String FEATURE_BLUETOOTH_LE = "android.hardware.bluetooth_le"; - public static final String FEATURE_CAMERA = "android.hardware.camera"; - public static final String FEATURE_CAMERA_FLASH = "android.hardware.camera.flash"; - public static final String FEATURE_CAMERA_FRONT = "android.hardware.camera.front"; - public static final String FEATURE_LEANBACK_ONLY = "android.software.leanback_only"; - public static final String FEATURE_LOCATION_GPS = "android.hardware.location.gps"; - public static final String FEATURE_PC = "android.hardware.type.pc"; - public static final String FEATURE_PICTURE_IN_PICTURE = "android.software.picture_in_picture"; - public static final String FEATURE_TELEPHONY = "android.hardware.telephony"; - public static final String FEATURE_WATCH = "android.hardware.type.watch"; - public static final String FEATURE_WIFI = "android.hardware.wifi"; - public static final String FEATURE_INCREMENTAL_DELIVERY = - "android.software.incremental_delivery"; - - public static final int SHELL_UID = 2000; - - // Telephony phone types - public static final int PHONE_TYPE_GSM = 1; - public static final int PHONE_TYPE_CDMA = 2; - public static final int PHONE_TYPE_CDMA_LTE = 6; - - protected static final int WAIT_TIME_SHORT = 500; - protected static final int WAIT_TIME_LONG = 2_000; - - protected static final long SCREEN_STATE_CHANGE_TIMEOUT = 4000; - protected static final long SCREEN_STATE_POLLING_INTERVAL = 500; - - protected static final long NS_PER_SEC = (long) 1E+9; - - @Override - protected void setUp() throws Exception { - super.setUp(); - - // Uninstall to clear the history in case it's still on the device. - removeConfig(CONFIG_ID); - getReportList(); // Clears data. - } - - @Override - protected void tearDown() throws Exception { - removeConfig(CONFIG_ID); - getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE); - super.tearDown(); - } - - /** - * Determines whether logcat indicates that incidentd fired since the given device date. - */ - protected boolean didIncidentdFireSince(String date) throws Exception { - final String INCIDENTD_TAG = "incidentd"; - final String INCIDENTD_STARTED_STRING = "reportIncident"; - // TODO: Do something more robust than this in case of delayed logging. - Thread.sleep(1000); - String log = getLogcatSince(date, String.format( - "-s %s -e %s", INCIDENTD_TAG, INCIDENTD_STARTED_STRING)); - return log.contains(INCIDENTD_STARTED_STRING); - } - - protected boolean checkDeviceFor(String methodName) throws Exception { - try { - installPackage(DEVICE_SIDE_TEST_APK, true); - runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".Checkers", methodName); - // Test passes, meaning that the answer is true. - LogUtil.CLog.d(methodName + "() indicates true."); - return true; - } catch (AssertionError e) { - // Method is designed to fail if the answer is false. - LogUtil.CLog.d(methodName + "() indicates false."); - return false; - } - } - - /** - * Returns a protobuf-encoded perfetto config that enables the kernel - * ftrace tracer with sched_switch for 10 seconds. - */ - protected ByteString getPerfettoConfig() { - TraceConfig.Builder builder = TraceConfig.newBuilder(); - - TraceConfig.BufferConfig buffer = TraceConfig.BufferConfig - .newBuilder() - .setSizeKb(128) - .build(); - builder.addBuffers(buffer); - - FtraceConfig ftraceConfig = FtraceConfig.newBuilder() - .addFtraceEvents("sched/sched_switch") - .build(); - DataSourceConfig dataSourceConfig = DataSourceConfig.newBuilder() - .setName("linux.ftrace") - .setTargetBuffer(0) - .setFtraceConfig(ftraceConfig) - .build(); - TraceConfig.DataSource dataSource = TraceConfig.DataSource - .newBuilder() - .setConfig(dataSourceConfig) - .build(); - builder.addDataSources(dataSource); - - builder.setDurationMs(10000); - builder.setAllowUserBuildTracing(true); - - TraceConfig.IncidentReportConfig incident = TraceConfig.IncidentReportConfig - .newBuilder() - .setSkipIncidentd(true) - .build(); - builder.setIncidentReportConfig(incident); - - // To avoid being hit with guardrails firing in multiple test runs back - // to back, we set a unique session key for each config. - Random random = new Random(); - StringBuilder sessionNameBuilder = new StringBuilder("statsd-cts-"); - sessionNameBuilder.append(random.nextInt() & Integer.MAX_VALUE); - builder.setUniqueSessionName(sessionNameBuilder.toString()); - - return builder.build().toByteString(); - } - - /** - * Resets the state of the Perfetto guardrails. This avoids that the test fails if it's - * run too close of for too many times and hits the upload limit. - */ - protected void resetPerfettoGuardrails() throws Exception { - final String cmd = "perfetto --reset-guardrails"; - CommandResult cr = getDevice().executeShellV2Command(cmd); - if (cr.getStatus() != CommandStatus.SUCCESS) - throw new Exception(String.format("Error while executing %s: %s %s", cmd, cr.getStdout(), cr.getStderr())); - } - - private String probe(String path) throws Exception { - return getDevice().executeShellCommand("if [ -e " + path + " ] ; then" - + " cat " + path + " ; else echo -1 ; fi"); - } - - protected void enableSystemTracing() throws Exception { - getDevice().executeShellCommand("setprop persist.traced.enable 1"); - } - - protected void disableSystemTracing() throws Exception { - getDevice().executeShellCommand("setprop persist.traced.enable 0"); - } - - /** - * Determines whether perfetto enabled the kernel ftrace tracer. - */ - protected boolean isSystemTracingEnabled() throws Exception { - final String traceFsPath = "/sys/kernel/tracing/tracing_on"; - String tracing_on = probe(traceFsPath); - if (tracing_on.startsWith("0")) return false; - if (tracing_on.startsWith("1")) return true; - - // fallback to debugfs - LogUtil.CLog.d("Unexpected state for %s = %s. Falling back to debugfs", traceFsPath, - tracing_on); - - final String debugFsPath = "/sys/kernel/debug/tracing/tracing_on"; - tracing_on = probe(debugFsPath); - if (tracing_on.startsWith("0")) return false; - if (tracing_on.startsWith("1")) return true; - throw new Exception(String.format("Unexpected state for %s = %s", traceFsPath, tracing_on)); - } - - protected static StatsdConfig.Builder createConfigBuilder() { - return StatsdConfig.newBuilder() - .setId(CONFIG_ID) - .addAllowedLogSource("AID_SYSTEM") - .addAllowedLogSource("AID_BLUETOOTH") - // TODO(b/134091167): Fix bluetooth source name issue in Auto platform. - .addAllowedLogSource("com.android.bluetooth") - .addAllowedLogSource("AID_LMKD") - .addAllowedLogSource("AID_RADIO") - .addAllowedLogSource("AID_ROOT") - .addAllowedLogSource("AID_STATSD") - .addAllowedLogSource("com.android.systemui") - .addAllowedLogSource(DeviceAtomTestCase.DEVICE_SIDE_TEST_PACKAGE) - .addDefaultPullPackages("AID_RADIO") - .addDefaultPullPackages("AID_SYSTEM") - .addWhitelistedAtomIds(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER); - } - - protected void createAndUploadConfig(int atomTag) throws Exception { - StatsdConfig.Builder conf = createConfigBuilder(); - addAtomEvent(conf, atomTag); - uploadConfig(conf); - } - - protected void uploadConfig(StatsdConfig.Builder config) throws Exception { - uploadConfig(config.build()); - } - - protected void uploadConfig(StatsdConfig config) throws Exception { - LogUtil.CLog.d("Uploading the following config:\n" + config.toString()); - File configFile = File.createTempFile("statsdconfig", ".config"); - try { - Files.write(config.toByteArray(), configFile); - String remotePath = "/data/local/tmp/" + configFile.getName(); - getDevice().pushFile(configFile, remotePath); - getDevice().executeShellCommand(String.join(" ", "cat", remotePath, "|", - UPDATE_CONFIG_CMD, String.valueOf(SHELL_UID), String.valueOf(CONFIG_ID))); - getDevice().executeShellCommand("rm " + remotePath); - } finally { - configFile.delete(); - } - } - - protected void removeConfig(long configId) throws Exception { - getDevice().executeShellCommand( - String.join(" ", REMOVE_CONFIG_CMD, - String.valueOf(SHELL_UID), String.valueOf(configId))); - } - - /** Gets the statsd report and sorts it. Note that this also deletes that report from statsd. */ - protected List<EventMetricData> getEventMetricDataList() throws Exception { - ConfigMetricsReportList reportList = getReportList(); - return getEventMetricDataList(reportList); - } - - /** - * Gets a List of sorted ConfigMetricsReports from ConfigMetricsReportList. - */ - protected List<ConfigMetricsReport> getSortedConfigMetricsReports( - ConfigMetricsReportList configMetricsReportList) { - return configMetricsReportList.getReportsList().stream() - .sorted(Comparator.comparing(ConfigMetricsReport::getCurrentReportWallClockNanos)) - .collect(Collectors.toList()); - } - - /** - * Extracts and sorts the EventMetricData from the given ConfigMetricsReportList (which must - * contain a single report). - */ - protected List<EventMetricData> getEventMetricDataList(ConfigMetricsReportList reportList) - throws Exception { - assertThat(reportList.getReportsCount()).isEqualTo(1); - ConfigMetricsReport report = reportList.getReports(0); - - List<EventMetricData> data = new ArrayList<>(); - for (StatsLogReport metric : report.getMetricsList()) { - for (EventMetricData metricData : - metric.getEventMetrics().getDataList()) { - if (metricData.hasAtom()) { - data.add(metricData); - } else { - data.addAll(backfillAggregatedAtomsInEventMetric(metricData)); - } - } - } - data.sort(Comparator.comparing(EventMetricData::getElapsedTimestampNanos)); - - LogUtil.CLog.d("Get EventMetricDataList as following:\n"); - for (EventMetricData d : data) { - LogUtil.CLog.d("Atom at " + d.getElapsedTimestampNanos() + ":\n" + d.getAtom().toString()); - } - return data; - } - - protected List<Atom> getGaugeMetricDataList() throws Exception { - return getGaugeMetricDataList(/*checkTimestampTruncated=*/false); - } - - protected List<Atom> getGaugeMetricDataList(boolean checkTimestampTruncated) throws Exception { - ConfigMetricsReportList reportList = getReportList(); - assertThat(reportList.getReportsCount()).isEqualTo(1); - - // only config - ConfigMetricsReport report = reportList.getReports(0); - assertThat(report.getMetricsCount()).isEqualTo(1); - - List<Atom> data = new ArrayList<>(); - for (GaugeMetricData gaugeMetricData : - report.getMetrics(0).getGaugeMetrics().getDataList()) { - assertThat(gaugeMetricData.getBucketInfoCount()).isEqualTo(1); - GaugeBucketInfo bucketInfo = gaugeMetricData.getBucketInfo(0); - if (bucketInfo.getAtomCount() != 0) { - for (Atom atom : bucketInfo.getAtomList()) { - data.add(atom); - } - } else { - backFillGaugeBucketAtoms(bucketInfo.getAggregatedAtomInfoList()); - } - if (checkTimestampTruncated) { - for (long timestampNs : bucketInfo.getElapsedTimestampNanosList()) { - assertTimestampIsTruncated(timestampNs); - } - } - } - - LogUtil.CLog.d("Get GaugeMetricDataList as following:\n"); - for (Atom d : data) { - LogUtil.CLog.d("Atom:\n" + d.toString()); - } - return data; - } - - private List<Atom> backFillGaugeBucketAtoms( - List<StatsLog.AggregatedAtomInfo> atomInfoList) { - List<Pair<Atom, Long>> atomTimestamp = new ArrayList<>(); - for (StatsLog.AggregatedAtomInfo atomInfo : atomInfoList) { - for (long timestampNs : atomInfo.getElapsedTimestampNanosList()) { - atomTimestamp.add(Pair.create(atomInfo.getAtom(), timestampNs)); - } - } - atomTimestamp.sort(Comparator.comparing(o -> o.second)); - return atomTimestamp.stream().map(p -> p.first).collect(Collectors.toList()); - } - - protected GaugeMetricDataWrapper backfillGaugeMetricData(GaugeMetricDataWrapper dataWrapper) { - GaugeMetricDataWrapper.Builder dataWrapperBuilder = dataWrapper.toBuilder(); - List<GaugeMetricData> backfilledMetricData = new ArrayList<>(); - for (GaugeMetricData gaugeMetricData : dataWrapperBuilder.getDataList()) { - GaugeMetricData.Builder gaugeMetricDataBuilder = gaugeMetricData.toBuilder(); - List<GaugeBucketInfo> backfilledBuckets = new ArrayList<>(); - for (GaugeBucketInfo bucketInfo : gaugeMetricData.getBucketInfoList()) { - backfilledBuckets.add(backfillGaugeBucket(bucketInfo.toBuilder())); - } - gaugeMetricDataBuilder.clearBucketInfo(); - gaugeMetricDataBuilder.addAllBucketInfo(backfilledBuckets); - backfilledMetricData.add(gaugeMetricDataBuilder.build()); - } - dataWrapperBuilder.clearData(); - dataWrapperBuilder.addAllData(backfilledMetricData); - return dataWrapperBuilder.build(); - } - - private GaugeBucketInfo backfillGaugeBucket(GaugeBucketInfo.Builder bucketInfoBuilder) { - if (bucketInfoBuilder.getAtomCount() != 0) { - return bucketInfoBuilder.build(); - } - List<Pair<Atom, Long>> atomTimestampData = new ArrayList<>(); - for (StatsLog.AggregatedAtomInfo atomInfo : bucketInfoBuilder.getAggregatedAtomInfoList()) { - for (long timestampNs : atomInfo.getElapsedTimestampNanosList()) { - atomTimestampData.add(Pair.create(atomInfo.getAtom(), timestampNs)); - } - } - atomTimestampData.sort(Comparator.comparing(o -> o.second)); - bucketInfoBuilder.clearAggregatedAtomInfo(); - for (Pair<Atom, Long> atomTimestamp : atomTimestampData) { - bucketInfoBuilder.addAtom(atomTimestamp.first); - bucketInfoBuilder.addElapsedTimestampNanos(atomTimestamp.second); - } - return bucketInfoBuilder.build(); - } - - /** - * Gets the statsd report and extract duration metric data. - * Note that this also deletes that report from statsd. - */ - protected List<DurationMetricData> getDurationMetricDataList() throws Exception { - ConfigMetricsReportList reportList = getReportList(); - assertThat(reportList.getReportsCount()).isEqualTo(1); - ConfigMetricsReport report = reportList.getReports(0); - - List<DurationMetricData> data = new ArrayList<>(); - for (StatsLogReport metric : report.getMetricsList()) { - data.addAll(metric.getDurationMetrics().getDataList()); - } - - LogUtil.CLog.d("Got DurationMetricDataList as following:\n"); - for (DurationMetricData d : data) { - LogUtil.CLog.d("Duration " + d); - } - return data; - } - - /** - * Gets the statsd report and extract count metric data. - * Note that this also deletes that report from statsd. - */ - protected List<CountMetricData> getCountMetricDataList() throws Exception { - ConfigMetricsReportList reportList = getReportList(); - assertThat(reportList.getReportsCount()).isEqualTo(1); - ConfigMetricsReport report = reportList.getReports(0); - - List<CountMetricData> data = new ArrayList<>(); - for (StatsLogReport metric : report.getMetricsList()) { - data.addAll(metric.getCountMetrics().getDataList()); - } - - LogUtil.CLog.d("Got CountMetricDataList as following:\n"); - for (CountMetricData d : data) { - LogUtil.CLog.d("Count " + d); - } - return data; - } - - /** - * Gets the statsd report and extract value metric data. - * Note that this also deletes that report from statsd. - */ - protected List<ValueMetricData> getValueMetricDataList() throws Exception { - ConfigMetricsReportList reportList = getReportList(); - assertThat(reportList.getReportsCount()).isEqualTo(1); - ConfigMetricsReport report = reportList.getReports(0); - - List<ValueMetricData> data = new ArrayList<>(); - for (StatsLogReport metric : report.getMetricsList()) { - data.addAll(metric.getValueMetrics().getDataList()); - } - - LogUtil.CLog.d("Got ValueMetricDataList as following:\n"); - for (ValueMetricData d : data) { - LogUtil.CLog.d("Value " + d); - } - return data; - } - - protected StatsLogReport getStatsLogReport() throws Exception { - ConfigMetricsReport report = getConfigMetricsReport(); - assertThat(report.hasUidMap()).isTrue(); - assertThat(report.getMetricsCount()).isEqualTo(1); - return report.getMetrics(0); - } - - protected ConfigMetricsReport getConfigMetricsReport() throws Exception { - ConfigMetricsReportList reportList = getReportList(); - assertThat(reportList.getReportsCount()).isEqualTo(1); - return reportList.getReports(0); - } - - /** Gets the statsd report. Note that this also deletes that report from statsd. */ - protected ConfigMetricsReportList getReportList() throws Exception { - try { - ConfigMetricsReportList reportList = getDump(ConfigMetricsReportList.parser(), - String.join(" ", DUMP_REPORT_CMD, String.valueOf(SHELL_UID), - String.valueOf(CONFIG_ID), "--include_current_bucket", "--proto")); - return reportList; - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to fetch and parse the statsd output report. " - + "Perhaps there is not a valid statsd config for the requested " - + "uid=" + getHostUid() + ", id=" + CONFIG_ID + "."); - throw (e); - } - } - - protected BatteryStatsProto getBatteryStatsProto() throws Exception { - try { - BatteryStatsProto batteryStatsProto = getDump(BatteryStatsServiceDumpProto.parser(), - String.join(" ", DUMP_BATTERYSTATS_CMD, - "--proto")).getBatterystats(); - LogUtil.CLog.d("Got batterystats:\n " + batteryStatsProto.toString()); - return batteryStatsProto; - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to dump batterystats proto"); - throw (e); - } - } - - /** Gets reports from the statsd data incident section from the stats dumpsys. */ - protected List<ConfigMetricsReportList> getReportsFromStatsDataDumpProto() throws Exception { - try { - StatsDataDumpProto statsProto = getDump(StatsDataDumpProto.parser(), - String.join(" ", DUMPSYS_STATS_CMD, "--proto")); - // statsProto holds repeated bytes, which we must parse into ConfigMetricsReportLists. - List<ConfigMetricsReportList> reports - = new ArrayList<>(statsProto.getConfigMetricsReportListCount()); - for (ByteString reportListBytes : statsProto.getConfigMetricsReportListList()) { - reports.add(ConfigMetricsReportList.parseFrom(reportListBytes)); - } - LogUtil.CLog.d("Got dumpsys stats output:\n " + reports.toString()); - return reports; - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to dumpsys stats proto"); - throw (e); - } - } - - protected List<ProcessStatsProto> getProcStatsProto() throws Exception { - try { - - List<ProcessStatsProto> processStatsProtoList = - new ArrayList<ProcessStatsProto>(); - android.service.procstats.ProcessStatsSectionProto sectionProto = getDump( - ProcessStatsServiceDumpProto.parser(), - String.join(" ", DUMP_PROCSTATS_CMD, - "--proto")).getProcstatsNow(); - for (android.service.procstats.ProcessStatsProto stats : - sectionProto.getProcessStatsList()) { - ProcessStatsProto procStats = ProcessStatsProto.parser().parseFrom( - stats.toByteArray()); - processStatsProtoList.add(procStats); - } - LogUtil.CLog.d("Got procstats:\n "); - for (ProcessStatsProto processStatsProto : processStatsProtoList) { - LogUtil.CLog.d(processStatsProto.toString()); - } - return processStatsProtoList; - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to dump procstats proto"); - throw (e); - } - } - - /* - * Get all procstats package data in proto - */ - protected List<ProcessStatsPackageProto> getAllProcStatsProto() throws Exception { - try { - android.service.procstats.ProcessStatsSectionProto sectionProto = getDump( - ProcessStatsServiceDumpProto.parser(), - String.join(" ", DUMP_PROCSTATS_CMD, - "--proto")).getProcstatsOver24Hrs(); - List<ProcessStatsPackageProto> processStatsProtoList = - new ArrayList<ProcessStatsPackageProto>(); - for (android.service.procstats.ProcessStatsPackageProto pkgStast : - sectionProto.getPackageStatsList()) { - ProcessStatsPackageProto pkgAtom = - ProcessStatsPackageProto.parser().parseFrom(pkgStast.toByteArray()); - processStatsProtoList.add(pkgAtom); - } - LogUtil.CLog.d("Got procstats:\n "); - for (ProcessStatsPackageProto processStatsProto : processStatsProtoList) { - LogUtil.CLog.d(processStatsProto.toString()); - } - return processStatsProtoList; - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to dump procstats proto"); - throw (e); - } - } - - /* - * Get all processes' procstats statsd data in proto - */ - protected List<android.service.procstats.ProcessStatsProto> getAllProcStatsProtoForStatsd() - throws Exception { - try { - android.service.procstats.ProcessStatsSectionProto sectionProto = getDump( - android.service.procstats.ProcessStatsSectionProto.parser(), - String.join(" ", DUMP_PROCSTATS_CMD, - "--statsd")); - List<android.service.procstats.ProcessStatsProto> processStatsProtoList - = sectionProto.getProcessStatsList(); - LogUtil.CLog.d("Got procstats:\n "); - for (android.service.procstats.ProcessStatsProto processStatsProto - : processStatsProtoList) { - LogUtil.CLog.d(processStatsProto.toString()); - } - return processStatsProtoList; - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to dump procstats proto"); - throw (e); - } - } - - protected boolean hasBattery() throws Exception { - try { - BatteryServiceDumpProto batteryProto = getDump(BatteryServiceDumpProto.parser(), - String.join(" ", DUMP_BATTERY_CMD, "--proto")); - LogUtil.CLog.d("Got battery service dump:\n " + batteryProto.toString()); - return batteryProto.getIsPresent(); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - LogUtil.CLog.e("Failed to dump batteryservice proto"); - throw (e); - } - } - - /** Creates a FieldValueMatcher.Builder corresponding to the given field. */ - protected static FieldValueMatcher.Builder createFvm(int field) { - return FieldValueMatcher.newBuilder().setField(field); - } - - protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag) throws Exception { - addAtomEvent(conf, atomTag, new ArrayList<FieldValueMatcher.Builder>()); - } - - /** - * Adds an event to the config for an atom that matches the given key. - * - * @param conf configuration - * @param atomTag atom tag (from atoms.proto) - * @param fvm FieldValueMatcher.Builder for the relevant key - */ - protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag, - FieldValueMatcher.Builder fvm) - throws Exception { - addAtomEvent(conf, atomTag, Arrays.asList(fvm)); - } - - /** - * Adds an event to the config for an atom that matches the given keys. - * - * @param conf configuration - * @param atomId atom tag (from atoms.proto) - * @param fvms list of FieldValueMatcher.Builders to attach to the atom. May be null. - */ - protected void addAtomEvent(StatsdConfig.Builder conf, int atomId, - List<FieldValueMatcher.Builder> fvms) throws Exception { - - final String atomName = "Atom" + System.nanoTime(); - final String eventName = "Event" + System.nanoTime(); - - SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder().setAtomId(atomId); - if (fvms != null) { - for (FieldValueMatcher.Builder fvm : fvms) { - sam.addFieldValueMatcher(fvm); - } - } - conf.addAtomMatcher(AtomMatcher.newBuilder() - .setId(atomName.hashCode()) - .setSimpleAtomMatcher(sam)); - conf.addEventMetric(EventMetric.newBuilder() - .setId(eventName.hashCode()) - .setWhat(atomName.hashCode())); - } - - /** - * Adds an atom to a gauge metric of a config - * - * @param conf configuration - * @param atomId atom id (from atoms.proto) - * @param gaugeMetric the gauge metric to add - */ - protected void addGaugeAtom(StatsdConfig.Builder conf, int atomId, - GaugeMetric.Builder gaugeMetric) throws Exception { - final String atomName = "Atom" + System.nanoTime(); - final String gaugeName = "Gauge" + System.nanoTime(); - final String predicateName = "APP_BREADCRUMB"; - SimpleAtomMatcher.Builder sam = SimpleAtomMatcher.newBuilder().setAtomId(atomId); - conf.addAtomMatcher(AtomMatcher.newBuilder() - .setId(atomName.hashCode()) - .setSimpleAtomMatcher(sam)); - final String predicateTrueName = "APP_BREADCRUMB_1"; - final String predicateFalseName = "APP_BREADCRUMB_2"; - conf.addAtomMatcher(AtomMatcher.newBuilder() - .setId(predicateTrueName.hashCode()) - .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() - .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addFieldValueMatcher(FieldValueMatcher.newBuilder() - .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER) - .setEqInt(1) - ) - ) - ) - // Used to trigger predicate - .addAtomMatcher(AtomMatcher.newBuilder() - .setId(predicateFalseName.hashCode()) - .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() - .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addFieldValueMatcher(FieldValueMatcher.newBuilder() - .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER) - .setEqInt(2) - ) - ) - ); - conf.addPredicate(Predicate.newBuilder() - .setId(predicateName.hashCode()) - .setSimplePredicate(SimplePredicate.newBuilder() - .setStart(predicateTrueName.hashCode()) - .setStop(predicateFalseName.hashCode()) - .setCountNesting(false) - ) - ); - gaugeMetric - .setId(gaugeName.hashCode()) - .setWhat(atomName.hashCode()) - .setCondition(predicateName.hashCode()); - conf.addGaugeMetric(gaugeMetric.build()); - } - - /** - * Adds an atom to a gauge metric of a config - * - * @param conf configuration - * @param atomId atom id (from atoms.proto) - * @param dimension dimension is needed for most pulled atoms - */ - protected void addGaugeAtomWithDimensions(StatsdConfig.Builder conf, int atomId, - @Nullable FieldMatcher.Builder dimension) throws Exception { - GaugeMetric.Builder gaugeMetric = GaugeMetric.newBuilder() - .setGaugeFieldsFilter(FieldFilter.newBuilder().setIncludeAll(true).build()) - .setSamplingType(GaugeMetric.SamplingType.CONDITION_CHANGE_TO_TRUE) - .setMaxNumGaugeAtomsPerBucket(10000) - .setBucket(TimeUnit.CTS); - if (dimension != null) { - gaugeMetric.setDimensionsInWhat(dimension.build()); - } - addGaugeAtom(conf, atomId, gaugeMetric); - } - - /** - * Asserts that each set of states in stateSets occurs at least once in data. - * Asserts that the states in data occur in the same order as the sets in stateSets. - * - * @param stateSets A list of set of states, where each set represents an equivalent - * state of the device for the purpose of CTS. - * @param data list of EventMetricData from statsd, produced by - * getReportMetricListData() - * @param wait expected duration (in ms) between state changes; asserts that the - * actual wait - * time was wait/2 <= actual_wait <= 5*wait. Use 0 to ignore this - * assertion. - * @param getStateFromAtom expression that takes in an Atom and returns the state it contains - */ - public void assertStatesOccurred(List<Set<Integer>> stateSets, List<EventMetricData> data, - int wait, Function<Atom, Integer> getStateFromAtom) { - // Sometimes, there are more events than there are states. - // Eg: When the screen turns off, it may go into OFF and then DOZE immediately. - assertWithMessage("Too few states found").that(data.size()).isAtLeast(stateSets.size()); - int stateSetIndex = 0; // Tracks which state set we expect the data to be in. - for (int dataIndex = 0; dataIndex < data.size(); dataIndex++) { - Atom atom = data.get(dataIndex).getAtom(); - int state = getStateFromAtom.apply(atom); - // If state is in the current state set, we do not assert anything. - // If it is not, we expect to have transitioned to the next state set. - if (stateSets.get(stateSetIndex).contains(state)) { - // No need to assert anything. Just log it. - LogUtil.CLog.i("The following atom at dataIndex=" + dataIndex + " is " - + "in stateSetIndex " + stateSetIndex + ":\n" - + data.get(dataIndex).getAtom().toString()); - } else { - stateSetIndex += 1; - LogUtil.CLog.i("Assert that the following atom at dataIndex=" + dataIndex + " is" - + " in stateSetIndex " + stateSetIndex + ":\n" - + data.get(dataIndex).getAtom().toString()); - assertWithMessage("Missed first state").that(dataIndex).isNotEqualTo(0); - assertWithMessage("Too many states").that(stateSetIndex) - .isLessThan(stateSets.size()); - assertWithMessage(String.format("Is in wrong state (%d)", state)) - .that(stateSets.get(stateSetIndex)).contains(state); - if (wait > 0) { - assertTimeDiffBetween(data.get(dataIndex - 1), data.get(dataIndex), - wait / 2, wait * 5); - } - } - } - assertWithMessage("Too few states").that(stateSetIndex).isEqualTo(stateSets.size() - 1); - } - - /** - * Removes all elements from data prior to the first occurrence of an element of state. After - * this method is called, the first element of data (if non-empty) is guaranteed to be an - * element in state. - * - * @param getStateFromAtom expression that takes in an Atom and returns the state it contains - */ - public void popUntilFind(List<EventMetricData> data, Set<Integer> state, - Function<Atom, Integer> getStateFromAtom) { - int firstStateIdx; - for (firstStateIdx = 0; firstStateIdx < data.size(); firstStateIdx++) { - Atom atom = data.get(firstStateIdx).getAtom(); - if (state.contains(getStateFromAtom.apply(atom))) { - break; - } - } - if (firstStateIdx == 0) { - // First first element already is in state, so there's nothing to do. - return; - } - data.subList(0, firstStateIdx).clear(); - } - - /** - * Removes all elements from data after to the last occurrence of an element of state. After - * this method is called, the last element of data (if non-empty) is guaranteed to be an - * element in state. - * - * @param getStateFromAtom expression that takes in an Atom and returns the state it contains - */ - public void popUntilFindFromEnd(List<EventMetricData> data, Set<Integer> state, - Function<Atom, Integer> getStateFromAtom) { - int lastStateIdx; - for (lastStateIdx = data.size() - 1; lastStateIdx >= 0; lastStateIdx--) { - Atom atom = data.get(lastStateIdx).getAtom(); - if (state.contains(getStateFromAtom.apply(atom))) { - break; - } - } - if (lastStateIdx == data.size()-1) { - // Last element already is in state, so there's nothing to do. - return; - } - data.subList(lastStateIdx+1, data.size()).clear(); - } - - /** Returns the UID of the host, which should always either be SHELL (2000). */ - protected int getHostUid() throws DeviceNotAvailableException { - return SHELL_UID; - } - - protected String getProperty(String prop) throws Exception { - return getDevice().executeShellCommand("getprop " + prop).replace("\n", ""); - } - - protected void turnScreenOn() throws Exception { - getDevice().executeShellCommand("input keyevent KEYCODE_WAKEUP"); - getDevice().executeShellCommand("wm dismiss-keyguard"); - } - - protected void turnScreenOff() throws Exception { - getDevice().executeShellCommand("input keyevent KEYCODE_SLEEP"); - } - - protected void setChargingState(int state) throws Exception { - getDevice().executeShellCommand("cmd battery set status " + state); - } - - protected void unplugDevice() throws Exception { - // On batteryless devices on Android P or above, the 'unplug' command - // alone does not simulate the really unplugged state. - // - // This is because charging state is left as "unknown". Unless a valid - // state like 3 = BatteryManager.BATTERY_STATUS_DISCHARGING is set, - // framework does not consider the device as running on battery. - setChargingState(3); - - getDevice().executeShellCommand("cmd battery unplug"); - } - - protected void plugInAc() throws Exception { - getDevice().executeShellCommand("cmd battery set ac 1"); - } - - protected void plugInUsb() throws Exception { - getDevice().executeShellCommand("cmd battery set usb 1"); - } - - protected void plugInWireless() throws Exception { - getDevice().executeShellCommand("cmd battery set wireless 1"); - } - - protected void enableLooperStats() throws Exception { - getDevice().executeShellCommand("cmd looper_stats enable"); - } - - protected void resetLooperStats() throws Exception { - getDevice().executeShellCommand("cmd looper_stats reset"); - } - - protected void disableLooperStats() throws Exception { - getDevice().executeShellCommand("cmd looper_stats disable"); - } - - protected void enableBinderStats() throws Exception { - getDevice().executeShellCommand("dumpsys binder_calls_stats --enable"); - } - - protected void resetBinderStats() throws Exception { - getDevice().executeShellCommand("dumpsys binder_calls_stats --reset"); - } - - protected void disableBinderStats() throws Exception { - getDevice().executeShellCommand("dumpsys binder_calls_stats --disable"); - } - - protected void binderStatsNoSampling() throws Exception { - getDevice().executeShellCommand("dumpsys binder_calls_stats --no-sampling"); - } - - protected void setUpLooperStats() throws Exception { - getDevice().executeShellCommand("cmd looper_stats enable"); - getDevice().executeShellCommand("cmd looper_stats sampling_interval 1"); - getDevice().executeShellCommand("cmd looper_stats reset"); - } - - protected void cleanUpLooperStats() throws Exception { - getDevice().executeShellCommand("cmd looper_stats disable"); - } - - public void setAppBreadcrumbPredicate() throws Exception { - doAppBreadcrumbReportedStart(1); - } - - public void clearAppBreadcrumbPredicate() throws Exception { - doAppBreadcrumbReportedStart(2); - } - - public void doAppBreadcrumbReportedStart(int label) throws Exception { - doAppBreadcrumbReported(label, AppBreadcrumbReported.State.START.ordinal()); - } - - public void doAppBreadcrumbReportedStop(int label) throws Exception { - doAppBreadcrumbReported(label, AppBreadcrumbReported.State.STOP.ordinal()); - } - - public void doAppBreadcrumbReported(int label) throws Exception { - doAppBreadcrumbReported(label, AppBreadcrumbReported.State.UNSPECIFIED.ordinal()); - } - - public void doAppBreadcrumbReported(int label, int state) throws Exception { - getDevice().executeShellCommand(String.format( - "cmd stats log-app-breadcrumb %d %d %d", SHELL_UID, label, state)); - } - - protected void setBatteryLevel(int level) throws Exception { - getDevice().executeShellCommand("cmd battery set level " + level); - } - - protected void resetBatteryStatus() throws Exception { - getDevice().executeShellCommand("cmd battery reset"); - } - - protected int getScreenBrightness() throws Exception { - return Integer.parseInt( - getDevice().executeShellCommand("settings get system screen_brightness").trim()); - } - - protected void setScreenBrightness(int brightness) throws Exception { - getDevice().executeShellCommand("settings put system screen_brightness " + brightness); - } - - // Gets whether "Always on Display" setting is enabled. - // In rare cases, this is different from whether the device can enter SCREEN_STATE_DOZE. - protected String getAodState() throws Exception { - return getDevice().executeShellCommand("settings get secure doze_always_on"); - } - - protected void setAodState(String state) throws Exception { - getDevice().executeShellCommand("settings put secure doze_always_on " + state); - } - - protected boolean isScreenBrightnessModeManual() throws Exception { - String mode = getDevice().executeShellCommand("settings get system screen_brightness_mode"); - return Integer.parseInt(mode.trim()) == 0; - } - - protected void setScreenBrightnessMode(boolean manual) throws Exception { - getDevice().executeShellCommand( - "settings put system screen_brightness_mode " + (manual ? 0 : 1)); - } - - protected void enterDozeModeLight() throws Exception { - getDevice().executeShellCommand("dumpsys deviceidle force-idle light"); - } - - protected void enterDozeModeDeep() throws Exception { - getDevice().executeShellCommand("dumpsys deviceidle force-idle deep"); - } - - protected void leaveDozeMode() throws Exception { - getDevice().executeShellCommand("dumpsys deviceidle unforce"); - getDevice().executeShellCommand("dumpsys deviceidle disable"); - getDevice().executeShellCommand("dumpsys deviceidle enable"); - } - - protected void turnBatterySaverOn() throws Exception { - unplugDevice(); - getDevice().executeShellCommand("settings put global low_power 1"); - } - - protected void turnBatterySaverOff() throws Exception { - getDevice().executeShellCommand("settings put global low_power 0"); - getDevice().executeShellCommand("cmd battery reset"); - } - - protected void turnBatteryStatsAutoResetOn() throws Exception { - getDevice().executeShellCommand("dumpsys batterystats enable no-auto-reset"); - } - - protected void turnBatteryStatsAutoResetOff() throws Exception { - getDevice().executeShellCommand("dumpsys batterystats enable no-auto-reset"); - } - - protected void flushBatteryStatsHandlers() throws Exception { - // Dumping batterystats will flush everything in the batterystats handler threads. - getDevice().executeShellCommand(DUMP_BATTERYSTATS_CMD); - } - - protected void rebootDevice() throws Exception { - getDevice().rebootUntilOnline(); - } - - /** - * Asserts that the two events are within the specified range of each other. - * - * @param d0 the event that should occur first - * @param d1 the event that should occur second - * @param minDiffMs d0 should precede d1 by at least this amount - * @param maxDiffMs d0 should precede d1 by at most this amount - */ - public static void assertTimeDiffBetween(EventMetricData d0, EventMetricData d1, - int minDiffMs, int maxDiffMs) { - long diffMs = (d1.getElapsedTimestampNanos() - d0.getElapsedTimestampNanos()) / 1_000_000; - assertWithMessage("Illegal time difference") - .that(diffMs).isIn(Range.closed((long) minDiffMs, (long) maxDiffMs)); - } - - protected String getCurrentLogcatDate() throws Exception { - // TODO: Do something more robust than this for getting logcat markers. - long timestampMs = getDevice().getDeviceDate(); - return new SimpleDateFormat("MM-dd HH:mm:ss.SSS") - .format(new Date(timestampMs)); - } - - protected String getLogcatSince(String date, String logcatParams) throws Exception { - return getDevice().executeShellCommand(String.format( - "logcat -v threadtime -t '%s' -d %s", date, logcatParams)); - } - - // TODO: Remove this and migrate all usages to createConfigBuilder() - protected StatsdConfig.Builder getPulledConfig() { - return createConfigBuilder(); - } - /** - * Determines if the device has the given feature. - * Prints a warning if its value differs from requiredAnswer. - */ - protected boolean hasFeature(String featureName, boolean requiredAnswer) throws Exception { - final String features = getDevice().executeShellCommand("pm list features"); - StringTokenizer featureToken = new StringTokenizer(features, "\n"); - boolean hasIt = false; - - while (featureToken.hasMoreTokens()) { - if (("feature:" + featureName).equals(featureToken.nextToken())) { - hasIt = true; - break; - } - } - - if (hasIt != requiredAnswer) { - LogUtil.CLog.w("Device does " + (requiredAnswer ? "not " : "") + "have feature " - + featureName); - } - return hasIt == requiredAnswer; - } - - /** - * Determines if the device has |file|. - */ - protected boolean doesFileExist(String file) throws Exception { - return getDevice().doesFileExist(file); - } - - protected void turnOnAirplaneMode() throws Exception { - getDevice().executeShellCommand("cmd connectivity airplane-mode enable"); - } - - protected void turnOffAirplaneMode() throws Exception { - getDevice().executeShellCommand("cmd connectivity airplane-mode disable"); - } - - /** - * Returns a list of fields and values for {@code className} from {@link TelephonyDebugService} - * output. - * - * <p>Telephony dumpsys output does not support proto at the moment. This method provides - * limited support for parsing its output. Specifically, it does not support arrays or - * multi-line values. - */ - private List<Map<String, String>> getTelephonyDumpEntries(String className) throws Exception { - // Matches any line with indentation, except for lines with only spaces - Pattern indentPattern = Pattern.compile("^(\\s*)[^ ].*$"); - // Matches pattern for class, e.g. " Phone:" - Pattern classNamePattern = Pattern.compile("^(\\s*)" + Pattern.quote(className) + ":.*$"); - // Matches pattern for key-value pairs, e.g. " mPhoneId=1" - Pattern keyValuePattern = Pattern.compile("^(\\s*)([a-zA-Z]+[a-zA-Z0-9_]*)\\=(.+)$"); - String response = - getDevice().executeShellCommand("dumpsys activity service TelephonyDebugService"); - Queue<String> responseLines = new LinkedList<>(Arrays.asList(response.split("[\\r\\n]+"))); - - List<Map<String, String>> results = new ArrayList<>(); - while (responseLines.peek() != null) { - Matcher matcher = classNamePattern.matcher(responseLines.poll()); - if (matcher.matches()) { - final int classIndentLevel = matcher.group(1).length(); - final Map<String, String> instanceEntries = new HashMap<>(); - while (responseLines.peek() != null) { - // Skip blank lines - matcher = indentPattern.matcher(responseLines.peek()); - if (responseLines.peek().length() == 0 || !matcher.matches()) { - responseLines.poll(); - continue; - } - // Finish (without consuming the line) if already parsed past this instance - final int indentLevel = matcher.group(1).length(); - if (indentLevel <= classIndentLevel) { - break; - } - // Parse key-value pair if it belongs to the instance directly - matcher = keyValuePattern.matcher(responseLines.poll()); - if (indentLevel == classIndentLevel + 1 && matcher.matches()) { - instanceEntries.put(matcher.group(2), matcher.group(3)); - } - } - results.add(instanceEntries); - } - } - return results; - } - - protected int getActiveSimSlotCount() throws Exception { - List<Map<String, String>> slots = getTelephonyDumpEntries("UiccSlot"); - long count = slots.stream().filter(slot -> "true".equals(slot.get("mActive"))).count(); - return Math.toIntExact(count); - } - - /** - * Returns the upper bound of active SIM profile count. - * - * <p>The value is an upper bound as eSIMs without profiles are also counted in. - */ - protected int getActiveSimCountUpperBound() throws Exception { - List<Map<String, String>> slots = getTelephonyDumpEntries("UiccSlot"); - long count = slots.stream().filter(slot -> - "true".equals(slot.get("mActive")) - && "CARDSTATE_PRESENT".equals(slot.get("mCardState"))).count(); - return Math.toIntExact(count); - } - - /** - * Returns the upper bound of active eSIM profile count. - * - * <p>The value is an upper bound as eSIMs without profiles are also counted in. - */ - protected int getActiveEsimCountUpperBound() throws Exception { - List<Map<String, String>> slots = getTelephonyDumpEntries("UiccSlot"); - long count = slots.stream().filter(slot -> - "true".equals(slot.get("mActive")) - && "CARDSTATE_PRESENT".equals(slot.get("mCardState")) - && "true".equals(slot.get("mIsEuicc"))).count(); - return Math.toIntExact(count); - } - - protected boolean hasGsmPhone() throws Exception { - // Not using log entries or ServiceState in the dump since they may or may not be present, - // which can make the test flaky - return getTelephonyDumpEntries("Phone").stream() - .anyMatch(phone -> - String.format("%d", PHONE_TYPE_GSM).equals(phone.get("getPhoneType()"))); - } - - protected boolean hasCdmaPhone() throws Exception { - // Not using log entries or ServiceState in the dump due to the same reason as hasGsmPhone() - return getTelephonyDumpEntries("Phone").stream() - .anyMatch(phone -> - String.format("%d", PHONE_TYPE_CDMA).equals(phone.get("getPhoneType()")) - || String.format("%d", PHONE_TYPE_CDMA_LTE) - .equals(phone.get("getPhoneType()"))); - } - - // Checks that a timestamp has been truncated to be a multiple of 5 min - protected void assertTimestampIsTruncated(long timestampNs) { - long fiveMinutesInNs = NS_PER_SEC * 5 * 60; - assertWithMessage("Timestamp is not truncated") - .that(timestampNs % fiveMinutesInNs).isEqualTo(0); - } - - protected List<EventMetricData> backfillAggregatedAtomsInEventMetric( - EventMetricData metricData) { - if (!metricData.hasAggregatedAtomInfo()) { - return Collections.singletonList(metricData); - } - List<EventMetricData> data = new ArrayList<>(); - StatsLog.AggregatedAtomInfo atomInfo = metricData.getAggregatedAtomInfo(); - for (long timestamp : atomInfo.getElapsedTimestampNanosList()) { - data.add(EventMetricData.newBuilder() - .setAtom(atomInfo.getAtom()) - .setElapsedTimestampNanos(timestamp) - .build()); - } - return data; - } -} diff --git a/tests/src/android/cts/statsd/atom/BaseTestCase.java b/tests/src/android/cts/statsd/atom/BaseTestCase.java deleted file mode 100644 index 0c9921ed..00000000 --- a/tests/src/android/cts/statsd/atom/BaseTestCase.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.cts.statsd.atom; - -import static com.google.common.truth.Truth.assertThat; -import static com.google.common.truth.Truth.assertWithMessage; - -import android.cts.statsd.validation.ValidationTestUtil; - -import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper; -import com.android.ddmlib.testrunner.RemoteAndroidTestRunner; -import com.android.ddmlib.testrunner.TestResult.TestStatus; -import com.android.tradefed.build.IBuildInfo; -import com.android.tradefed.device.CollectingByteOutputReceiver; -import com.android.tradefed.device.DeviceNotAvailableException; -import com.android.tradefed.log.LogUtil.CLog; -import com.android.tradefed.result.CollectingTestListener; -import com.android.tradefed.result.TestDescription; -import com.android.tradefed.result.TestResult; -import com.android.tradefed.result.TestRunResult; -import com.android.tradefed.testtype.DeviceTestCase; -import com.android.tradefed.testtype.IBuildReceiver; - -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.MessageLite; -import com.google.protobuf.Parser; - -import java.io.FileNotFoundException; -import java.util.Map; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -// Largely copied from incident's ProtoDumpTestCase -public class BaseTestCase extends DeviceTestCase implements IBuildReceiver { - - protected IBuildInfo mCtsBuild; - - private static final String TEST_RUNNER = "androidx.test.runner.AndroidJUnitRunner"; - - @Override - protected void setUp() throws Exception { - super.setUp(); - assertThat(mCtsBuild).isNotNull(); - } - - @Override - public void setBuild(IBuildInfo buildInfo) { - mCtsBuild = buildInfo; - } - - public IBuildInfo getBuild() { - return mCtsBuild; - } - - /** - * Create and return {@link ValidationTestUtil} and give it the current build. - */ - public ValidationTestUtil createValidationUtil() { - ValidationTestUtil util = new ValidationTestUtil(); - util.setBuild(getBuild()); - return util; - } - - /** - * Call onto the device with an adb shell command and get the results of - * that as a proto of the given type. - * - * @param parser A protobuf parser object. e.g. MyProto.parser() - * @param command The adb shell command to run. e.g. "dumpsys fingerprint --proto" - * - * @throws DeviceNotAvailableException If there was a problem communicating with - * the test device. - * @throws InvalidProtocolBufferException If there was an error parsing - * the proto. Note that a 0 length buffer is not necessarily an error. - */ - public <T extends MessageLite> T getDump(Parser<T> parser, String command) - throws DeviceNotAvailableException, InvalidProtocolBufferException { - final CollectingByteOutputReceiver receiver = new CollectingByteOutputReceiver(); - getDevice().executeShellCommand(command, receiver); - if (false) { - CLog.d("Command output while parsing " + parser.getClass().getCanonicalName() - + " for command: " + command + "\n" - + BufferDebug.debugString(receiver.getOutput(), -1)); - } - try { - return parser.parseFrom(receiver.getOutput()); - } catch (Exception ex) { - CLog.d("Error parsing " + parser.getClass().getCanonicalName() + " for command: " - + command - + BufferDebug.debugString(receiver.getOutput(), 16384)); - throw ex; - } - } - - /** - * Install a device side test package. - * - * @param appFileName Apk file name, such as "CtsNetStatsApp.apk". - * @param grantPermissions whether to give runtime permissions. - */ - protected void installPackage(String appFileName, boolean grantPermissions) - throws FileNotFoundException, DeviceNotAvailableException { - CLog.d("Installing app " + appFileName); - CompatibilityBuildHelper buildHelper = new CompatibilityBuildHelper(mCtsBuild); - final String result = getDevice().installPackage( - buildHelper.getTestFile(appFileName), true, grantPermissions); - assertWithMessage(String.format("Failed to install %s: %s", appFileName, result)) - .that(result).isNull(); - } - - protected CompatibilityBuildHelper getBuildHelper() { - return new CompatibilityBuildHelper(mCtsBuild); - } - - /** - * Run a device side test. - * - * @param pkgName Test package name, such as "com.android.server.cts.netstats". - * @param testClassName Test class name; either a fully qualified name, or "." + a class name. - * @param testMethodName Test method name. - * @return {@link TestRunResult} of this invocation. - * @throws DeviceNotAvailableException - */ - @Nonnull - protected TestRunResult runDeviceTests(@Nonnull String pkgName, - @Nullable String testClassName, @Nullable String testMethodName) - throws DeviceNotAvailableException { - if (testClassName != null && testClassName.startsWith(".")) { - testClassName = pkgName + testClassName; - } - - RemoteAndroidTestRunner testRunner = new RemoteAndroidTestRunner( - pkgName, TEST_RUNNER, getDevice().getIDevice()); - if (testClassName != null && testMethodName != null) { - testRunner.setMethodName(testClassName, testMethodName); - } else if (testClassName != null) { - testRunner.setClassName(testClassName); - } - - CollectingTestListener listener = new CollectingTestListener(); - assertThat(getDevice().runInstrumentationTests(testRunner, listener)).isTrue(); - - final TestRunResult result = listener.getCurrentRunResults(); - if (result.isRunFailure()) { - throw new Error("Failed to successfully run device tests for " - + result.getName() + ": " + result.getRunFailureMessage()); - } - if (result.getNumTests() == 0) { - throw new Error("No tests were run on the device"); - } - - if (result.hasFailedTests()) { - // build a meaningful error message - StringBuilder errorBuilder = new StringBuilder("On-device tests failed:\n"); - for (Map.Entry<TestDescription, TestResult> resultEntry : - result.getTestResults().entrySet()) { - if (!resultEntry.getValue().getStatus().equals(TestStatus.PASSED)) { - errorBuilder.append(resultEntry.getKey().toString()); - errorBuilder.append(":\n"); - errorBuilder.append(resultEntry.getValue().getStackTrace()); - } - } - throw new AssertionError(errorBuilder.toString()); - } - - return result; - } -} diff --git a/tests/src/android/cts/statsd/atom/DeviceAtomTestCase.java b/tests/src/android/cts/statsd/atom/DeviceAtomTestCase.java deleted file mode 100644 index d641ebc1..00000000 --- a/tests/src/android/cts/statsd/atom/DeviceAtomTestCase.java +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Copyright (C) 2017 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package android.cts.statsd.atom; - -import static com.google.common.truth.Truth.assertThat; -import static com.google.common.truth.Truth.assertWithMessage; - -import com.android.internal.os.StatsdConfigProto.FieldValueMatcher; -import com.android.internal.os.StatsdConfigProto.MessageMatcher; -import com.android.internal.os.StatsdConfigProto.Position; -import com.android.internal.os.StatsdConfigProto.StatsdConfig; -import com.android.os.StatsLog.EventMetricData; -import com.android.tradefed.log.LogUtil; - -import java.util.Arrays; -import java.util.List; - -/** - * Base class for testing Statsd atoms that report a uid. Tests are performed via a device-side app. - */ -public class DeviceAtomTestCase extends AtomTestCase { - - public static final String DEVICE_SIDE_TEST_APK = "CtsStatsdApp.apk"; - public static final String DEVICE_SIDE_TEST_PACKAGE = - "com.android.server.cts.device.statsd"; - public static final long DEVICE_SIDE_TEST_PACKAGE_VERSION = 10; - public static final String DEVICE_SIDE_TEST_FOREGROUND_SERVICE_NAME = - "com.android.server.cts.device.statsd.StatsdCtsForegroundService"; - private static final String DEVICE_SIDE_BG_SERVICE_COMPONENT = - "com.android.server.cts.device.statsd/.StatsdCtsBackgroundService"; - public static final long DEVICE_SIDE_TEST_PKG_HASH = - Long.parseUnsignedLong("15694052924544098582"); - - // Constants from device side tests (not directly accessible here). - public static final String KEY_ACTION = "action"; - public static final String ACTION_LMK = "action.lmk"; - - public static final String CONFIG_NAME = "cts_config"; - - @Override - protected void setUp() throws Exception { - super.setUp(); - getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE); - installTestApp(); - Thread.sleep(1000); - } - - @Override - protected void tearDown() throws Exception { - getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE); - super.tearDown(); - } - - /** - * Performs a device-side test by calling a method on the app and returns its stats events. - * @param methodName the name of the method in the app's AtomTests to perform - * @param atom atom tag (from atoms.proto) - * @param key atom's field corresponding to state - * @param stateOn 'on' value - * @param stateOff 'off' value - * @param minTimeDiffMs max allowed time between start and stop - * @param maxTimeDiffMs min allowed time between start and stop - * @param demandExactlyTwo whether there must be precisely two events logged (1 start, 1 stop) - * @return list of events with the app's uid matching the configuration defined by the params. - */ - protected List<EventMetricData> doDeviceMethodOnOff( - String methodName, int atom, int key, int stateOn, int stateOff, - int minTimeDiffMs, int maxTimeDiffMs, boolean demandExactlyTwo) throws Exception { - StatsdConfig.Builder conf = createConfigBuilder(); - addAtomEvent(conf, atom, createFvm(key).setEqInt(stateOn)); - addAtomEvent(conf, atom, createFvm(key).setEqInt(stateOff)); - List<EventMetricData> data = doDeviceMethod(methodName, conf); - - if (demandExactlyTwo) { - assertThat(data).hasSize(2); - } else { - assertThat(data.size()).isAtLeast(2); - } - assertTimeDiffBetween(data.get(0), data.get(1), minTimeDiffMs, maxTimeDiffMs); - return data; - } - - /** - * - * @param methodName the name of the method in the app's AtomTests to perform - * @param cfg statsd configuration - * @return list of events with the app's uid matching the configuration. - */ - protected List<EventMetricData> doDeviceMethod(String methodName, StatsdConfig.Builder cfg) - throws Exception { - removeConfig(CONFIG_ID); - getReportList(); // Clears previous data on disk. - uploadConfig(cfg); - int appUid = getUid(); - LogUtil.CLog.d("\nPerforming device-side test of " + methodName + " for uid " + appUid); - runDeviceTests(DEVICE_SIDE_TEST_PACKAGE, ".AtomTests", methodName); - - return getEventMetricDataList(); - } - - protected void createAndUploadConfig(int atomTag, boolean useAttribution) throws Exception { - StatsdConfig.Builder conf = createConfigBuilder(); - addAtomEvent(conf, atomTag, useAttribution); - uploadConfig(conf); - } - - /** - * Adds an event to the config for an atom that matches the given key AND has the app's uid. - * @param conf configuration - * @param atomTag atom tag (from atoms.proto) - * @param fvm FieldValueMatcher.Builder for the relevant key - */ - @Override - protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag, FieldValueMatcher.Builder fvm) - throws Exception { - - final int UID_KEY = 1; - FieldValueMatcher.Builder fvmUid = createAttributionFvm(UID_KEY); - addAtomEvent(conf, atomTag, Arrays.asList(fvm, fvmUid)); - } - - /** - * Adds an event to the config for an atom that matches the app's uid. - * @param conf configuration - * @param atomTag atom tag (from atoms.proto) - * @param useAttribution If true, the atom has a uid within an attribution node. Else, the atom - * has a uid but not in an attribution node. - */ - protected void addAtomEvent(StatsdConfig.Builder conf, int atomTag, - boolean useAttribution) throws Exception { - final int UID_KEY = 1; - FieldValueMatcher.Builder fvmUid; - if (useAttribution) { - fvmUid = createAttributionFvm(UID_KEY); - } else { - fvmUid = createFvm(UID_KEY).setEqString(DEVICE_SIDE_TEST_PACKAGE); - } - addAtomEvent(conf, atomTag, Arrays.asList(fvmUid)); - } - - /** - * Creates a FieldValueMatcher for atoms that use AttributionNode - */ - protected FieldValueMatcher.Builder createAttributionFvm(int field) { - final int ATTRIBUTION_NODE_UID_KEY = 1; - return createFvm(field).setPosition(Position.ANY) - .setMatchesTuple(MessageMatcher.newBuilder() - .addFieldValueMatcher(createFvm(ATTRIBUTION_NODE_UID_KEY) - .setEqString(DEVICE_SIDE_TEST_PACKAGE))); - } - - /** - * Gets the uid of the test app. - */ - protected int getUid() throws Exception { - int currentUser = getDevice().getCurrentUser(); - final String packages = getDevice().executeShellCommand("cmd package list packages -U" - + " --user " + currentUser + " " + DEVICE_SIDE_TEST_PACKAGE); - - // Split package list by lines - // Sample packages response: - // package:com.android.server.cts.device.statsd.host uid:1010033 - // package:com.android.server.cts.device.statsd uid:1010034 - final String[] lines = packages.split("[\\r\\n]+"); - for (final String line : lines) { - if (line.startsWith("package:" + DEVICE_SIDE_TEST_PACKAGE + " ")) { - final int uidIndex = line.lastIndexOf(":") + 1; - final int uid = Integer.parseInt(line.substring(uidIndex).trim()); - assertThat(uid).isGreaterThan(10_000); - return uid; - } - } - throw new Error( - String.format("Could not find installed package: %s", DEVICE_SIDE_TEST_PACKAGE)); - } - - /** - * Installs the test apk. - */ - protected void installTestApp() throws Exception { - installPackage(DEVICE_SIDE_TEST_APK, true); - LogUtil.CLog.i("Installing device-side test app with uid " + getUid()); - allowBackgroundServices(); - } - - /** - * Uninstalls the test apk. - */ - protected void uninstallPackage() throws Exception{ - getDevice().uninstallPackage(DEVICE_SIDE_TEST_PACKAGE); - } - - /** - * Required to successfully start a background service from adb in Android O. - */ - protected void allowBackgroundServices() throws Exception { - getDevice().executeShellCommand(String.format( - "cmd deviceidle tempwhitelist %s", DEVICE_SIDE_TEST_PACKAGE)); - } - - /** - * Runs a (background) service to perform the given action. - * @param actionValue the action code constants indicating the desired action to perform. - */ - protected void executeBackgroundService(String actionValue) throws Exception { - allowBackgroundServices(); - getDevice().executeShellCommand(String.format( - "am startservice -n '%s' -e %s %s", - DEVICE_SIDE_BG_SERVICE_COMPONENT, - KEY_ACTION, actionValue)); - } - - - /** Make the test app standby-active so it can run syncs and jobs immediately. */ - protected void allowImmediateSyncs() throws Exception { - getDevice().executeShellCommand("am set-standby-bucket " - + DEVICE_SIDE_TEST_PACKAGE + " active"); - } - - /** - * Runs the specified activity. - */ - protected void runActivity(String activity, String actionKey, String actionValue) - throws Exception { - runActivity(activity, actionKey, actionValue, WAIT_TIME_LONG); - } - - /** - * Runs the specified activity. - */ - protected void runActivity(String activity, String actionKey, String actionValue, - long waitTime) throws Exception { - try (AutoCloseable a = withActivity(activity, actionKey, actionValue)) { - Thread.sleep(waitTime); - } - } - - /** - * Starts the specified activity and returns an {@link AutoCloseable} that stops the activity - * when closed. - * - * <p>Example usage: - * <pre> - * try (AutoClosable a = withActivity("activity", "action", "action-value")) { - * doStuff(); - * } - * </pre> - */ - protected AutoCloseable withActivity(String activity, String actionKey, String actionValue) - throws Exception { - String intentString = null; - if (actionKey != null && actionValue != null) { - intentString = actionKey + " " + actionValue; - } - if (intentString == null) { - getDevice().executeShellCommand( - "am start -n " + DEVICE_SIDE_TEST_PACKAGE + "/." + activity); - } else { - getDevice().executeShellCommand( - "am start -n " + DEVICE_SIDE_TEST_PACKAGE + "/." + activity + " -e " + - intentString); - } - return () -> { - getDevice().executeShellCommand( - "am force-stop " + DEVICE_SIDE_TEST_PACKAGE); - Thread.sleep(WAIT_TIME_SHORT); - }; - } - - protected void resetBatteryStats() throws Exception { - getDevice().executeShellCommand("dumpsys batterystats --reset"); - } - - protected void clearProcStats() throws Exception { - getDevice().executeShellCommand("dumpsys procstats --clear"); - } - - protected void startProcStatsTesting() throws Exception { - getDevice().executeShellCommand("dumpsys procstats --start-testing"); - } - - protected void stopProcStatsTesting() throws Exception { - getDevice().executeShellCommand("dumpsys procstats --stop-testing"); - } - - protected void commitProcStatsToDisk() throws Exception { - getDevice().executeShellCommand("dumpsys procstats --commit"); - } - - protected void rebootDeviceAndWaitUntilReady() throws Exception { - rebootDevice(); - // Wait for 5 mins. - assertWithMessage("Device failed to boot") - .that(getDevice().waitForBootComplete(300_000)).isTrue(); - assertWithMessage("Stats service failed to start") - .that(waitForStatsServiceStart(60_000)).isTrue(); - Thread.sleep(2_000); - } - - protected boolean waitForStatsServiceStart(final long waitTime) throws Exception { - LogUtil.CLog.i("Waiting %d ms for stats service to start", waitTime); - int counter = 1; - long startTime = System.currentTimeMillis(); - while ((System.currentTimeMillis() - startTime) < waitTime) { - if ("running".equals(getProperty("init.svc.statsd"))) { - return true; - } - Thread.sleep(Math.min(200 * counter, 2_000)); - counter++; - } - LogUtil.CLog.w("Stats service did not start after %d ms", waitTime); - return false; - } - - boolean getNetworkStatsCombinedSubTypeEnabled() throws Exception { - final String output = getDevice().executeShellCommand( - "settings get global netstats_combine_subtype_enabled").trim(); - return output.equals("1"); - } - - void setNetworkStatsCombinedSubTypeEnabled(boolean enable) throws Exception { - getDevice().executeShellCommand("settings put global netstats_combine_subtype_enabled " - + (enable ? "1" : "0")); - } -} diff --git a/tests/src/android/cts/statsd/metadata/MetadataTests.java b/tests/src/android/cts/statsd/metadata/MetadataTests.java index d3764d3c..1f498f94 100644 --- a/tests/src/android/cts/statsd/metadata/MetadataTests.java +++ b/tests/src/android/cts/statsd/metadata/MetadataTests.java @@ -56,7 +56,7 @@ public class MetadataTests extends MetadataTestCase { long startTime = System.currentTimeMillis(); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.START.ordinal(), /* irrelevant val */ + AtomsProto.AppBreadcrumbReported.State.START.getNumber(), /* irrelevant val */ 6); // Event, within < TTL_TIME_SEC secs. RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); StatsdStatsReport report = getStatsdStatsReport(); // Has only been 1 second @@ -79,7 +79,7 @@ public class MetadataTests extends MetadataTestCase { RunUtil.getDefault().sleep(10); } AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.START.ordinal(), /* irrelevant val */ + AtomsProto.AppBreadcrumbReported.State.START.getNumber(), /* irrelevant val */ 6); // Event, after TTL_TIME_SEC secs. RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); report = getStatsdStatsReport(); @@ -162,7 +162,7 @@ public class MetadataTests extends MetadataTestCase { // loss info will not be propagated, which is intention by design. // Log atoms into socket successfully to trigger libstatsocket dumpAtomsLossStats() AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.START.ordinal(), /* irrelevant val */ + AtomsProto.AppBreadcrumbReported.State.START.getNumber(), /* irrelevant val */ 6); // Event, after TTL_TIME_SEC secs. // Delay to allow libstatssocket loss info to be propagated to statsdstats diff --git a/tests/src/android/cts/statsd/metric/CountMetricsTests.java b/tests/src/android/cts/statsd/metric/CountMetricsTests.java index d4cfb98d..00249533 100644 --- a/tests/src/android/cts/statsd/metric/CountMetricsTests.java +++ b/tests/src/android/cts/statsd/metric/CountMetricsTests.java @@ -83,14 +83,14 @@ public class CountMetricsTests extends DeviceTestCase implements IBuildReceiver .setId(MetricsUtils.COUNT_METRIC_ID) .setBucket(StatsdConfigProto.TimeUnit.ONE_MINUTE) .setWhat(matcherId)) - .addAtomMatcher(MetricsUtils.simpleAtomMatcher(matcherId)); + .addAtomMatcher(MetricsUtils.simpleAtomMatcher(matcherId)); ConfigUtils.uploadConfig(getDevice(), builder); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 0); + AppBreadcrumbReported.State.START.getNumber(), 0); RunUtil.getDefault().sleep(100); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 0); + AppBreadcrumbReported.State.STOP.getNumber(), 0); RunUtil.getDefault().sleep(2000); // Wait for the metrics to propagate to statsd. StatsLogReport metricReport = ReportUtils.getStatsLogReport(getDevice(), @@ -143,19 +143,19 @@ public class CountMetricsTests extends DeviceTestCase implements IBuildReceiver ConfigUtils.uploadConfig(getDevice(), builder); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 0); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 0); + AppBreadcrumbReported.State.START.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 0); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 0); + AppBreadcrumbReported.State.STOP.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 0); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 0); RunUtil.getDefault().sleep(2000); // Wait for the metrics to propagate to statsd. StatsLogReport metricReport = ReportUtils.getStatsLogReport(getDevice(), @@ -226,32 +226,32 @@ public class CountMetricsTests extends DeviceTestCase implements IBuildReceiver // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Set the condition to true. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), startMatcherLabel); + AppBreadcrumbReported.State.START.getNumber(), startMatcherLabel); RunUtil.getDefault().sleep(10); // Log an event that should be counted. Bucket 1 Count 1. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Log an event that should be counted. Bucket 1 Count 2. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Set the condition to false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), endMatcherLabel); + AppBreadcrumbReported.State.STOP.getNumber(), endMatcherLabel); RunUtil.getDefault().sleep(10); // Log an event that should not be counted because condition is false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -259,27 +259,27 @@ public class CountMetricsTests extends DeviceTestCase implements IBuildReceiver // Log an event that should not be counted. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Condition to true again. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), startMatcherLabel); + AppBreadcrumbReported.State.START.getNumber(), startMatcherLabel); RunUtil.getDefault().sleep(10); // Event should not be counted, metric is still not active. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Log an event that should be counted. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -287,7 +287,7 @@ public class CountMetricsTests extends DeviceTestCase implements IBuildReceiver // Log an event that should not be counted. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), whatMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), whatMatcherLabel); RunUtil.getDefault().sleep(10); // Wait for the metrics to propagate to statsd. @@ -310,29 +310,25 @@ public class CountMetricsTests extends DeviceTestCase implements IBuildReceiver public void testPartialBucketCountMetric() throws Exception { int matcherId = 1; StatsdConfigProto.StatsdConfig.Builder builder = ConfigUtils.createConfigBuilder( - MetricsUtils.DEVICE_SIDE_TEST_PACKAGE); - builder - .addCountMetric( - StatsdConfigProto.CountMetric.newBuilder() - .setId(MetricsUtils.COUNT_METRIC_ID) - .setBucket( - StatsdConfigProto.TimeUnit.ONE_DAY) // Ensures partial - // bucket. - .setWhat(matcherId) - .setSplitBucketForAppUpgrade(true)) + MetricsUtils.DEVICE_SIDE_TEST_PACKAGE) + .addCountMetric(StatsdConfigProto.CountMetric.newBuilder() + .setId(MetricsUtils.COUNT_METRIC_ID) + .setBucket(StatsdConfigProto.TimeUnit.ONE_DAY) // Ensures partial bucket. + .setWhat(matcherId) + .setSplitBucketForAppUpgrade(true)) .addAtomMatcher(MetricsUtils.simpleAtomMatcher(matcherId)); ConfigUtils.uploadConfig(getDevice(), builder); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 0); + AppBreadcrumbReported.State.START.getNumber(), 0); builder.getCountMetricBuilder(0).setBucket(StatsdConfigProto.TimeUnit.CTS); ConfigUtils.uploadConfig(getDevice(), builder); // The count metric had a partial bucket. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 0); + AppBreadcrumbReported.State.START.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 0); + AppBreadcrumbReported.State.START.getNumber(), 0); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_LONG); // Finish the current bucket. ConfigMetricsReportList reports = ReportUtils.getReportList(getDevice(), diff --git a/tests/src/android/cts/statsd/metric/DurationMetricsTests.java b/tests/src/android/cts/statsd/metric/DurationMetricsTests.java index 00ff927c..a40dbf19 100644 --- a/tests/src/android/cts/statsd/metric/DurationMetricsTests.java +++ b/tests/src/android/cts/statsd/metric/DurationMetricsTests.java @@ -88,22 +88,21 @@ public class DurationMetricsTests extends DeviceTestCase { builder.addPredicate(predicate); // Add DurationMetric. - builder.addDurationMetric( - StatsdConfigProto.DurationMetric.newBuilder() - .setId(MetricsUtils.DURATION_METRIC_ID) - .setWhat(predicate.getId()) - .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) - .setBucket(StatsdConfigProto.TimeUnit.CTS)); + builder.addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() + .setId(MetricsUtils.DURATION_METRIC_ID) + .setWhat(predicate.getId()) + .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) + .setBucket(StatsdConfigProto.TimeUnit.CTS)); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); // Create AppBreadcrumbReported Start/Stop events. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), label); + AppBreadcrumbReported.State.START.getNumber(), label); RunUtil.getDefault().sleep(2000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), label); + AppBreadcrumbReported.State.STOP.getNumber(), label); // Wait for the metrics to propagate to statsd. RunUtil.getDefault().sleep(2000); @@ -160,67 +159,64 @@ public class DurationMetricsTests extends DeviceTestCase { .setSimplePredicate(conditionSimplePredicate) .build(); - builder - .addPredicate(predicate) - .addPredicate(conditionPredicate); + builder.addPredicate(predicate).addPredicate(conditionPredicate); // Add DurationMetric. - builder - .addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() - .setId(MetricsUtils.DURATION_METRIC_ID) - .setWhat(predicate.getId()) - .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) - .setBucket(StatsdConfigProto.TimeUnit.CTS) - .setCondition(conditionPredicate.getId()) - ); + builder.addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() + .setId(MetricsUtils.DURATION_METRIC_ID) + .setWhat(predicate.getId()) + .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) + .setBucket(StatsdConfigProto.TimeUnit.CTS) + .setCondition(conditionPredicate.getId()) + ); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); // Start uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Set the condition to true. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Start counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Set the condition to false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), conditionLabel); + AppBreadcrumbReported.State.STOP.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Start uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); @@ -272,13 +268,11 @@ public class DurationMetricsTests extends DeviceTestCase { builder.addPredicate(predicate); // Add DurationMetric. - builder - .addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() + builder.addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() .setId(MetricsUtils.DURATION_METRIC_ID) .setWhat(predicate.getId()) .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) - .setBucket(StatsdConfigProto.TimeUnit.CTS) - ) + .setBucket(StatsdConfigProto.TimeUnit.CTS)) .addMetricActivation(StatsdConfigProto.MetricActivation.newBuilder() .setMetricId(MetricsUtils.DURATION_METRIC_ID) .addEventActivation(StatsdConfigProto.EventActivation.newBuilder() @@ -292,31 +286,31 @@ public class DurationMetricsTests extends DeviceTestCase { // Start uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Start counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); @@ -385,14 +379,12 @@ public class DurationMetricsTests extends DeviceTestCase { builder.addPredicate(conditionPredicate); // Add DurationMetric. - builder - .addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() + builder.addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() .setId(MetricsUtils.DURATION_METRIC_ID) .setWhat(predicate.getId()) .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) .setBucket(StatsdConfigProto.TimeUnit.CTS) - .setCondition(conditionPredicate.getId()) - ) + .setCondition(conditionPredicate.getId())) .addMetricActivation(StatsdConfigProto.MetricActivation.newBuilder() .setMetricId(MetricsUtils.DURATION_METRIC_ID) .addEventActivation(StatsdConfigProto.EventActivation.newBuilder() @@ -406,41 +398,41 @@ public class DurationMetricsTests extends DeviceTestCase { // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Set the condition to true. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Start counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Set the condition to false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), conditionLabel); + AppBreadcrumbReported.State.STOP.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Start uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -450,48 +442,48 @@ public class DurationMetricsTests extends DeviceTestCase { // Start uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Set condition to true again. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Start uncounted duration AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Start counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop counted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -499,14 +491,14 @@ public class DurationMetricsTests extends DeviceTestCase { // Start uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), durationLabel); + AppBreadcrumbReported.State.START.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); RunUtil.getDefault().sleep(2_000); // Stop uncounted duration. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), durationLabel); + AppBreadcrumbReported.State.STOP.getNumber(), durationLabel); RunUtil.getDefault().sleep(10); // Wait for the metrics to propagate to statsd. @@ -561,46 +553,44 @@ public class DurationMetricsTests extends DeviceTestCase { dimensionsBuilder .addChild(FieldMatcher.newBuilder().setField( AppBreadcrumbReported.LABEL_FIELD_NUMBER)); - Predicate predicateB = - Predicate.newBuilder() - .setId(MetricsUtils.StringToId("Predicate_B")) - .setSimplePredicate(SimplePredicate.newBuilder() - .setStart(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) - .setStop(APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID) - .setDimensions(dimensionsBuilder.build()) - .build()) - .build(); + Predicate predicateB = Predicate.newBuilder() + .setId(MetricsUtils.StringToId("Predicate_B")) + .setSimplePredicate(SimplePredicate.newBuilder() + .setStart(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) + .setStop(APP_BREADCRUMB_REPORTED_B_MATCH_STOP_ID) + .setDimensions(dimensionsBuilder.build()) + .build()) + .build(); builder.addPredicate(predicateB); // Add DurationMetric. - builder.addDurationMetric( - StatsdConfigProto.DurationMetric.newBuilder() - .setId(MetricsUtils.DURATION_METRIC_ID) - .setWhat(predicateB.getId()) - .setCondition(predicateA.getId()) - .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) - .setBucket(StatsdConfigProto.TimeUnit.CTS) - .setDimensionsInWhat( - FieldMatcher.newBuilder() - .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addChild(FieldMatcher.newBuilder().setField( - AppBreadcrumbReported.LABEL_FIELD_NUMBER)))); + builder.addDurationMetric(StatsdConfigProto.DurationMetric.newBuilder() + .setId(MetricsUtils.DURATION_METRIC_ID) + .setWhat(predicateB.getId()) + .setCondition(predicateA.getId()) + .setAggregationType(StatsdConfigProto.DurationMetric.AggregationType.SUM) + .setBucket(StatsdConfigProto.TimeUnit.CTS) + .setDimensionsInWhat( + FieldMatcher.newBuilder() + .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) + .addChild(FieldMatcher.newBuilder().setField( + AppBreadcrumbReported.LABEL_FIELD_NUMBER)))); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); // Trigger events. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(2000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 2); + AppBreadcrumbReported.State.START.getNumber(), 2); RunUtil.getDefault().sleep(2000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); RunUtil.getDefault().sleep(2000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 2); + AppBreadcrumbReported.State.STOP.getNumber(), 2); // Wait for the metrics to propagate to statsd. RunUtil.getDefault().sleep(2000); diff --git a/tests/src/android/cts/statsd/metric/GaugeMetricsTests.java b/tests/src/android/cts/statsd/metric/GaugeMetricsTests.java index ed27a5ca..db0a39f7 100644 --- a/tests/src/android/cts/statsd/metric/GaugeMetricsTests.java +++ b/tests/src/android/cts/statsd/metric/GaugeMetricsTests.java @@ -99,59 +99,58 @@ public class GaugeMetricsTests extends DeviceTestCase { builder.addPredicate(predicate); // Add GaugeMetric. - FieldMatcher fieldMatcher = - FieldMatcher.newBuilder().setField( - APP_BREADCRUMB_REPORTED_B_MATCH_START_ID).build(); - builder.addGaugeMetric( - StatsdConfigProto.GaugeMetric.newBuilder() - .setId(MetricsUtils.GAUGE_METRIC_ID) - .setWhat(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) - .setCondition(predicate.getId()) - .setGaugeFieldsFilter( - FieldFilter.newBuilder().setIncludeAll(false).setFields( - fieldMatcher).build()) - .setDimensionsInWhat( - FieldMatcher.newBuilder() - .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) - .addChild(FieldMatcher.newBuilder() - .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) - .build()) - .build()) - .setBucket(StatsdConfigProto.TimeUnit.CTS) - .build()); + FieldMatcher fieldMatcher = FieldMatcher.newBuilder() + .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) + .build(); + builder.addGaugeMetric(StatsdConfigProto.GaugeMetric.newBuilder() + .setId(MetricsUtils.GAUGE_METRIC_ID) + .setWhat(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) + .setCondition(predicate.getId()) + .setGaugeFieldsFilter(FieldFilter.newBuilder() + .setIncludeAll(false) + .setFields(fieldMatcher) + .build()) + .setDimensionsInWhat(FieldMatcher.newBuilder() + .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) + .addChild(FieldMatcher.newBuilder() + .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) + .build()) + .build()) + .setBucket(StatsdConfigProto.TimeUnit.CTS) + .build()); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); // Create AppBreadcrumbReported Start/Stop events. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 0); + AppBreadcrumbReported.State.START.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 2); + AppBreadcrumbReported.State.START.getNumber(), 2); RunUtil.getDefault().sleep(2000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 2); + AppBreadcrumbReported.State.STOP.getNumber(), 2); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 0); + AppBreadcrumbReported.State.STOP.getNumber(), 0); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 2); + AppBreadcrumbReported.State.START.getNumber(), 2); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(2000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 2); + AppBreadcrumbReported.State.STOP.getNumber(), 2); RunUtil.getDefault().sleep(10); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); // Wait for the metrics to propagate to statsd. RunUtil.getDefault().sleep(2000); @@ -194,16 +193,13 @@ public class GaugeMetricsTests extends DeviceTestCase { int activationAtomMatcherLabel = 1; int systemUptimeMatcherId = 2; - AtomMatcher activationAtomMatcher = - MetricsUtils.appBreadcrumbMatcherWithLabel( - activationAtomMatcherId, activationAtomMatcherLabel); - AtomMatcher systemUptimeMatcher = - AtomMatcher.newBuilder() - .setId(systemUptimeMatcherId) - .setSimpleAtomMatcher( - SimpleAtomMatcher.newBuilder().setAtomId( - Atom.SYSTEM_UPTIME_FIELD_NUMBER)) - .build(); + AtomMatcher activationAtomMatcher = MetricsUtils.appBreadcrumbMatcherWithLabel( + activationAtomMatcherId, activationAtomMatcherLabel); + AtomMatcher systemUptimeMatcher = AtomMatcher.newBuilder() + .setId(systemUptimeMatcherId) + .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.SYSTEM_UPTIME_FIELD_NUMBER)) + .build(); StatsdConfigProto.StatsdConfig.Builder builder = ConfigUtils.createConfigBuilder( MetricsUtils.DEVICE_SIDE_TEST_PACKAGE); @@ -211,14 +207,13 @@ public class GaugeMetricsTests extends DeviceTestCase { builder.addAtomMatcher(systemUptimeMatcher); // Add GaugeMetric. - builder.addGaugeMetric( - StatsdConfigProto.GaugeMetric.newBuilder() - .setId(MetricsUtils.GAUGE_METRIC_ID) - .setWhat(systemUptimeMatcherId) - .setGaugeFieldsFilter( - FieldFilter.newBuilder().setIncludeAll(true).build()) - .setBucket(StatsdConfigProto.TimeUnit.CTS) - .build()); + builder.addGaugeMetric(StatsdConfigProto.GaugeMetric.newBuilder() + .setId(MetricsUtils.GAUGE_METRIC_ID) + .setWhat(systemUptimeMatcherId) + .setGaugeFieldsFilter( + FieldFilter.newBuilder().setIncludeAll(true).build()) + .setBucket(StatsdConfigProto.TimeUnit.CTS) + .build()); // Add activation. builder.addMetricActivation(MetricActivation.newBuilder() @@ -253,18 +248,16 @@ public class GaugeMetricsTests extends DeviceTestCase { APP_BREADCRUMB_REPORTED_A_MATCH_START_ID, conditionLabel); AtomMatcher conditionStopAtomMatcher = MetricsUtils.stopAtomMatcherWithLabel( APP_BREADCRUMB_REPORTED_A_MATCH_STOP_ID, conditionLabel); - AtomMatcher activationMatcher = - MetricsUtils.startAtomMatcherWithLabel( - activationMatcherId, activationMatcherLabel); - AtomMatcher whatMatcher = - MetricsUtils.unspecifiedAtomMatcher(whatMatcherId); - - StatsdConfig.Builder builder = ConfigUtils.createConfigBuilder( - MetricsUtils.DEVICE_SIDE_TEST_PACKAGE) - .addAtomMatcher(conditionStartAtomMatcher) - .addAtomMatcher(conditionStopAtomMatcher) - .addAtomMatcher(whatMatcher) - .addAtomMatcher(activationMatcher); + AtomMatcher activationMatcher = MetricsUtils.startAtomMatcherWithLabel( + activationMatcherId, activationMatcherLabel); + AtomMatcher whatMatcher = MetricsUtils.unspecifiedAtomMatcher(whatMatcherId); + + StatsdConfig.Builder builder = + ConfigUtils.createConfigBuilder(MetricsUtils.DEVICE_SIDE_TEST_PACKAGE) + .addAtomMatcher(conditionStartAtomMatcher) + .addAtomMatcher(conditionStopAtomMatcher) + .addAtomMatcher(whatMatcher) + .addAtomMatcher(activationMatcher); // Add Predicates. SimplePredicate simplePredicate = SimplePredicate.newBuilder() @@ -278,59 +271,53 @@ public class GaugeMetricsTests extends DeviceTestCase { builder.addPredicate(predicate); // Add GaugeMetric. - builder - .addGaugeMetric(GaugeMetric.newBuilder() + builder.addGaugeMetric(GaugeMetric.newBuilder() .setId(MetricsUtils.GAUGE_METRIC_ID) .setWhat(whatMatcher.getId()) .setBucket(TimeUnit.CTS) .setCondition(predicate.getId()) - .setGaugeFieldsFilter( - FieldFilter.newBuilder().setIncludeAll(false).setFields( - FieldMatcher.newBuilder() - .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) - ) - ) - .setDimensionsInWhat(FieldMatcher.newBuilder().setField(whatMatcherId)) - ) + .setGaugeFieldsFilter(FieldFilter.newBuilder() + .setIncludeAll(false) + .setFields(FieldMatcher.newBuilder() + .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID))) + .setDimensionsInWhat(FieldMatcher.newBuilder().setField(whatMatcherId))) .addMetricActivation(MetricActivation.newBuilder() .setMetricId(MetricsUtils.GAUGE_METRIC_ID) .addEventActivation(EventActivation.newBuilder() .setAtomMatcherId(activationMatcherId) .setActivationType(ActivationType.ACTIVATE_IMMEDIATELY) - .setTtlSeconds(ttlSec) - ) - ); + .setTtlSeconds(ttlSec))); ConfigUtils.uploadConfig(getDevice(), builder); // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.START.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Set the condition to true. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // This value is collected. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 10); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 10); RunUtil.getDefault().sleep(10); // Ignored; value already collected. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 20); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 20); RunUtil.getDefault().sleep(10); // Set the condition to false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), conditionLabel); + AppBreadcrumbReported.State.STOP.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Value not updated because condition is false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 30); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 30); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -338,27 +325,27 @@ public class GaugeMetricsTests extends DeviceTestCase { // Value not collected. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 40); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 40); RunUtil.getDefault().sleep(10); // Condition to true again. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Value not collected. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 50); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 50); RunUtil.getDefault().sleep(10); // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.START.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Value collected. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 60); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 60); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -366,7 +353,7 @@ public class GaugeMetricsTests extends DeviceTestCase { // Value not collected. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 70); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 70); RunUtil.getDefault().sleep(10); // Wait for the metrics to propagate to statsd. diff --git a/tests/src/android/cts/statsd/metric/MetricActivationTests.java b/tests/src/android/cts/statsd/metric/MetricActivationTests.java index 58276c4e..7cee7eea 100644 --- a/tests/src/android/cts/statsd/metric/MetricActivationTests.java +++ b/tests/src/android/cts/statsd/metric/MetricActivationTests.java @@ -80,18 +80,18 @@ public class MetricActivationTests extends DeviceTestCase { } private StatsdConfig.Builder createConfig(final int act1TtlSecs, final int act2TtlSecs) { - AtomMatcher metric1Matcher = MetricsUtils.simpleAtomMatcher(metric1MatcherId, - metric1MatcherId); - AtomMatcher metric2Matcher = MetricsUtils.simpleAtomMatcher(metric2MatcherId, - metric2MatcherId); - AtomMatcher metric3Matcher = MetricsUtils.simpleAtomMatcher(metric3MatcherId, - metric3MatcherId); + AtomMatcher metric1Matcher = + MetricsUtils.simpleAtomMatcher(metric1MatcherId, metric1MatcherId); + AtomMatcher metric2Matcher = + MetricsUtils.simpleAtomMatcher(metric2MatcherId, metric2MatcherId); + AtomMatcher metric3Matcher = + MetricsUtils.simpleAtomMatcher(metric3MatcherId, metric3MatcherId); AtomMatcher act1Matcher = MetricsUtils.simpleAtomMatcher(act1MatcherId, act1MatcherId); - AtomMatcher act1CancelMatcher = MetricsUtils.simpleAtomMatcher(act1CancelMatcherId, - act1CancelMatcherId); + AtomMatcher act1CancelMatcher = + MetricsUtils.simpleAtomMatcher(act1CancelMatcherId, act1CancelMatcherId); AtomMatcher act2Matcher = MetricsUtils.simpleAtomMatcher(act2MatcherId, act2MatcherId); - AtomMatcher act2CancelMatcher = MetricsUtils.simpleAtomMatcher(act2CancelMatcherId, - act2CancelMatcherId); + AtomMatcher act2CancelMatcher = + MetricsUtils.simpleAtomMatcher(act2CancelMatcherId, act2CancelMatcherId); EventMetric metric1 = EventMetric.newBuilder().setId(metric1Id).setWhat(metric1MatcherId).build(); @@ -176,62 +176,62 @@ public class MetricActivationTests extends DeviceTestCase { // Ignored, metric not active. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Trigger cancel for already inactive event activation 1. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1CancelMatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1CancelMatcherId); RunUtil.getDefault().sleep(10L); // Trigger event activation 1. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // First logged event. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Second logged event. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Cancel event activation 1. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1CancelMatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1CancelMatcherId); RunUtil.getDefault().sleep(10L); // Ignored, metric not active. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Trigger event activation 1. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // Trigger event activation 2. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act2MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act2MatcherId); RunUtil.getDefault().sleep(10L); // Third logged event. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Cancel event activation 2. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act2CancelMatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act2CancelMatcherId); RunUtil.getDefault().sleep(10L); // Fourth logged event. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Expire event activation 1 @@ -239,22 +239,22 @@ public class MetricActivationTests extends DeviceTestCase { // Ignored, metric 1 not active. Activation 1 expired and Activation 2 was cancelled. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // Trigger event activation 2. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act2MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act2MatcherId); RunUtil.getDefault().sleep(10L); // Metric 1 log ignored, Activation 1 expired and Activation 2 needs reboot to activate. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); // First logged event for Metric 3. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric3MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric3MatcherId); RunUtil.getDefault().sleep(10L); ConfigMetricsReportList reportList = ReportUtils.getReportList(getDevice(), @@ -295,7 +295,7 @@ public class MetricActivationTests extends DeviceTestCase { // Metric 2 Activation 1: 0 seconds (will activate after boot) // Metric 2 Activation 2: 0 seconds AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // First logged event for Metric 1. @@ -334,7 +334,7 @@ public class MetricActivationTests extends DeviceTestCase { // Metric 2 Activation 1: 0 seconds // Metric 2 Activation 2: 400 seconds AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act2MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act2MatcherId); RunUtil.getDefault().sleep(10L); // Metric 1 event ignored, will activate after boot. @@ -349,7 +349,7 @@ public class MetricActivationTests extends DeviceTestCase { // Metric 2 Activation 1: 0 seconds (will activate after boot) // Metric 2 Activation 2: 400 seconds AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // Third logged event for Metric 1. @@ -451,7 +451,7 @@ public class MetricActivationTests extends DeviceTestCase { // Metric 2 Activation 1: 0 seconds (will activate after boot) // Metric 2 Activation 2: 0 seconds AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // First logged event for Metric 1. @@ -478,7 +478,7 @@ public class MetricActivationTests extends DeviceTestCase { // Metric 2 Activation 1: 0 seconds (will activate after boot) // Metric 2 Activation 2: 0 seconds AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // Third logged event for Metric 1. @@ -505,7 +505,7 @@ public class MetricActivationTests extends DeviceTestCase { // Metric 2 Activation 1: 200 seconds // Metric 2 Activation 2: 0 seconds AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), act1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), act1MatcherId); RunUtil.getDefault().sleep(10L); // Fifth logged event for Metric 1. @@ -569,15 +569,15 @@ public class MetricActivationTests extends DeviceTestCase { private void logAllMetrics() throws Exception { AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric1MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric1MatcherId); RunUtil.getDefault().sleep(10L); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric2MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric2MatcherId); RunUtil.getDefault().sleep(10L); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), metric3MatcherId); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), metric3MatcherId); RunUtil.getDefault().sleep(10L); } diff --git a/tests/src/android/cts/statsd/metric/MetricsUtils.java b/tests/src/android/cts/statsd/metric/MetricsUtils.java index 3fdd6850..010df49f 100644 --- a/tests/src/android/cts/statsd/metric/MetricsUtils.java +++ b/tests/src/android/cts/statsd/metric/MetricsUtils.java @@ -55,20 +55,19 @@ public class MetricsUtils { public static AtomMatcher.Builder getAtomMatcher(int atomId) { AtomMatcher.Builder builder = AtomMatcher.newBuilder(); builder.setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() - .setAtomId(atomId)); + .setAtomId(atomId)); return builder; } public static AtomMatcher startAtomMatcher(int id) { - return AtomMatcher.newBuilder() - .setId(id) - .setSimpleAtomMatcher( - SimpleAtomMatcher.newBuilder() - .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addFieldValueMatcher(FieldValueMatcher.newBuilder() - .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) - .setEqInt(AppBreadcrumbReported.State.START.ordinal()))) - .build(); + return AtomMatcher.newBuilder() + .setId(id) + .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) + .addFieldValueMatcher(FieldValueMatcher.newBuilder() + .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) + .setEqInt(AppBreadcrumbReported.State.START.getNumber()))) + .build(); } public static AtomMatcher startAtomMatcherWithLabel(int id, int label) { @@ -76,15 +75,14 @@ public class MetricsUtils { } public static AtomMatcher stopAtomMatcher(int id) { - return AtomMatcher.newBuilder() - .setId(id) - .setSimpleAtomMatcher( - SimpleAtomMatcher.newBuilder() - .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addFieldValueMatcher(FieldValueMatcher.newBuilder() - .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) - .setEqInt(AppBreadcrumbReported.State.STOP.ordinal()))) - .build(); + return AtomMatcher.newBuilder() + .setId(id) + .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) + .addFieldValueMatcher(FieldValueMatcher.newBuilder() + .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) + .setEqInt(AppBreadcrumbReported.State.STOP.getNumber()))) + .build(); } public static AtomMatcher stopAtomMatcherWithLabel(int id, int label) { @@ -98,16 +96,16 @@ public class MetricsUtils { .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) .addFieldValueMatcher(FieldValueMatcher.newBuilder() .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) - .setEqInt(AppBreadcrumbReported.State.UNSPECIFIED.ordinal()))) + .setEqInt(AppBreadcrumbReported.State.UNSPECIFIED.getNumber()))) .build(); } public static AtomMatcher simpleAtomMatcher(int id) { - return AtomMatcher.newBuilder() - .setId(id) - .setSimpleAtomMatcher( - SimpleAtomMatcher.newBuilder().setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)) - .build(); + return AtomMatcher.newBuilder() + .setId(id) + .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER)) + .build(); } public static AtomMatcher appBreadcrumbMatcherWithLabel(int id, int label) { @@ -130,7 +128,7 @@ public class MetricsUtils { .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) .addFieldValueMatcher(FieldValueMatcher.newBuilder() .setField(AppBreadcrumbReported.STATE_FIELD_NUMBER) - .setEqInt(state.ordinal())) + .setEqInt(state.getNumber())) .addFieldValueMatcher(FieldValueMatcher.newBuilder() .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER) .setEqInt(label))) @@ -138,16 +136,16 @@ public class MetricsUtils { } public static AtomMatcher simpleAtomMatcher(int id, int label) { - return AtomMatcher.newBuilder() - .setId(id) - .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() - .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addFieldValueMatcher(FieldValueMatcher.newBuilder() - .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER) - .setEqInt(label) - ) - ) - .build(); + return AtomMatcher.newBuilder() + .setId(id) + .setSimpleAtomMatcher(SimpleAtomMatcher.newBuilder() + .setAtomId(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) + .addFieldValueMatcher(FieldValueMatcher.newBuilder() + .setField(AppBreadcrumbReported.LABEL_FIELD_NUMBER) + .setEqInt(label) + ) + ) + .build(); } public static EventActivation.Builder createEventActivation(int ttlSecs, int matcherId, @@ -159,7 +157,7 @@ public class MetricsUtils { } public static long StringToId(String str) { - return str.hashCode(); + return str.hashCode(); } public static String getCurrentLogcatDate(ITestDevice device) throws Exception { @@ -178,7 +176,7 @@ public class MetricsUtils { if (bucketNum != null && bucketInfo.hasField(bucketNum)) { found = true; } else if (startMillis != null && bucketInfo.hasField(startMillis) && - endMillis != null && bucketInfo.hasField(endMillis)) { + endMillis != null && bucketInfo.hasField(endMillis)) { found = true; } assertWithMessage( diff --git a/tests/src/android/cts/statsd/metric/ValueMetricsTests.java b/tests/src/android/cts/statsd/metric/ValueMetricsTests.java index db1a99e5..6cd6873a 100644 --- a/tests/src/android/cts/statsd/metric/ValueMetricsTests.java +++ b/tests/src/android/cts/statsd/metric/ValueMetricsTests.java @@ -83,33 +83,32 @@ public class ValueMetricsTests extends DeviceTestCase { builder.addAtomMatcher(atomMatcher); // Add ValueMetric. - builder.addValueMetric( - ValueMetric.newBuilder() - .setId(MetricsUtils.VALUE_METRIC_ID) - .setWhat(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) - .setBucket(TimeUnit.CTS) - .setValueField(FieldMatcher.newBuilder() - .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) - .addChild(FieldMatcher.newBuilder().setField( - AppBreadcrumbReported.LABEL_FIELD_NUMBER))) - .setDimensionsInWhat(FieldMatcher.newBuilder() - .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) - .build()) - .build()); + builder.addValueMetric(ValueMetric.newBuilder() + .setId(MetricsUtils.VALUE_METRIC_ID) + .setWhat(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) + .setBucket(TimeUnit.CTS) + .setValueField(FieldMatcher.newBuilder() + .setField(Atom.APP_BREADCRUMB_REPORTED_FIELD_NUMBER) + .addChild(FieldMatcher.newBuilder().setField( + AppBreadcrumbReported.LABEL_FIELD_NUMBER))) + .setDimensionsInWhat(FieldMatcher.newBuilder() + .setField(APP_BREADCRUMB_REPORTED_B_MATCH_START_ID) + .build()) + .build()); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); // Create AppBreadcrumbReported Start/Stop events. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(1000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 3); + AppBreadcrumbReported.State.START.getNumber(), 3); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 3); + AppBreadcrumbReported.State.STOP.getNumber(), 3); // Wait for the metrics to propagate to statsd. RunUtil.getDefault().sleep(1000); @@ -168,28 +167,27 @@ public class ValueMetricsTests extends DeviceTestCase { .setSimpleAtomMatcher(sam)); // Add ValueMetric. - builder.addValueMetric( - ValueMetric.newBuilder() - .setId(MetricsUtils.VALUE_METRIC_ID) - .setWhat(atomName.hashCode()) - .setBucket(TimeUnit.ONE_MINUTE) - .setValueField(FieldMatcher.newBuilder() - .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER) - .addChild(FieldMatcher.newBuilder().setField( - SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER))) - .setCondition(predicateName.hashCode()) - .build()); + builder.addValueMetric(ValueMetric.newBuilder() + .setId(MetricsUtils.VALUE_METRIC_ID) + .setWhat(atomName.hashCode()) + .setBucket(TimeUnit.ONE_MINUTE) + .setValueField(FieldMatcher.newBuilder() + .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER) + .addChild(FieldMatcher.newBuilder().setField( + SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER))) + .setCondition(predicateName.hashCode()) + .build()); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); // Create AppBreadcrumbReported Start/Stop events. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); // Wait for 2 min and 1 sec to capture at least 2 buckets RunUtil.getDefault().sleep(2 * 60_000 + 10_000); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); // Wait for the metrics to propagate to statsd. RunUtil.getDefault().sleep(1_000); @@ -250,17 +248,16 @@ public class ValueMetricsTests extends DeviceTestCase { .setSimpleAtomMatcher(sam)); // Add ValueMetric. - builder.addValueMetric( - ValueMetric.newBuilder() - .setId(MetricsUtils.VALUE_METRIC_ID) - .setWhat(atomName.hashCode()) - .setBucket(TimeUnit.ONE_MINUTE) - .setValueField(FieldMatcher.newBuilder() - .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER) - .addChild(FieldMatcher.newBuilder().setField( - SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER))) - .setCondition(predicateName.hashCode()) - .build()); + builder.addValueMetric(ValueMetric.newBuilder() + .setId(MetricsUtils.VALUE_METRIC_ID) + .setWhat(atomName.hashCode()) + .setBucket(TimeUnit.ONE_MINUTE) + .setValueField(FieldMatcher.newBuilder() + .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER) + .addChild(FieldMatcher.newBuilder().setField( + SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER))) + .setCondition(predicateName.hashCode()) + .build()); // Upload config. ConfigUtils.uploadConfig(getDevice(), builder); @@ -270,10 +267,10 @@ public class ValueMetricsTests extends DeviceTestCase { // Create AppBreadcrumbReported Start/Stop events. for (int i = 0; i < NUM_EVENTS; i++) { AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), 1); + AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(GAP_INTERVAL); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), 1); + AppBreadcrumbReported.State.STOP.getNumber(), 1); RunUtil.getDefault().sleep(GAP_INTERVAL); } @@ -323,16 +320,15 @@ public class ValueMetricsTests extends DeviceTestCase { .setSimpleAtomMatcher(sam)); // Add ValueMetric. - builder.addValueMetric( - ValueMetric.newBuilder() - .setId(MetricsUtils.VALUE_METRIC_ID) - .setWhat(atomName.hashCode()) - .setBucket(TimeUnit.ONE_MINUTE) - .setValueField(FieldMatcher.newBuilder() - .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER) - .addChild(FieldMatcher.newBuilder().setField( - SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER))) - .build()); + builder.addValueMetric(ValueMetric.newBuilder() + .setId(MetricsUtils.VALUE_METRIC_ID) + .setWhat(atomName.hashCode()) + .setBucket(TimeUnit.ONE_MINUTE) + .setValueField(FieldMatcher.newBuilder() + .setField(Atom.SYSTEM_ELAPSED_REALTIME_FIELD_NUMBER) + .addChild(FieldMatcher.newBuilder().setField( + SystemElapsedRealtime.TIME_MILLIS_FIELD_NUMBER))) + .build()); // Add activation. builder.addMetricActivation(MetricActivation.newBuilder() .setMetricId(MetricsUtils.VALUE_METRIC_ID) @@ -397,8 +393,7 @@ public class ValueMetricsTests extends DeviceTestCase { builder.addPredicate(predicate); // Add ValueMetric. - builder - .addValueMetric(ValueMetric.newBuilder() + builder.addValueMetric(ValueMetric.newBuilder() .setId(MetricsUtils.VALUE_METRIC_ID) .setWhat(whatMatcher.getId()) .setBucket(TimeUnit.ONE_MINUTE) @@ -423,32 +418,32 @@ public class ValueMetricsTests extends DeviceTestCase { // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.START.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Set the condition to true. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Skipped due to unknown condition at start of bucket. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 10); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 10); RunUtil.getDefault().sleep(10); // Skipped due to unknown condition at start of bucket. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 200); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 200); RunUtil.getDefault().sleep(10); // Set the condition to false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.STOP.ordinal(), conditionLabel); + AppBreadcrumbReported.State.STOP.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Log an event that should not be counted because condition is false. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 3_000); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 3_000); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -456,27 +451,27 @@ public class ValueMetricsTests extends DeviceTestCase { // Log an event that should not be counted. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 40_000); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 40_000); RunUtil.getDefault().sleep(10); // Condition to true again. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), conditionLabel); + AppBreadcrumbReported.State.START.getNumber(), conditionLabel); RunUtil.getDefault().sleep(10); // Event should not be counted, metric is still not active. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 500_000); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 500_000); RunUtil.getDefault().sleep(10); // Activate the metric. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.START.ordinal(), activationMatcherLabel); + AppBreadcrumbReported.State.START.getNumber(), activationMatcherLabel); RunUtil.getDefault().sleep(10); // Log an event that should be counted. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 6_000_000); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 6_000_000); RunUtil.getDefault().sleep(10); // Let the metric deactivate. @@ -484,7 +479,7 @@ public class ValueMetricsTests extends DeviceTestCase { // Log an event that should not be counted. AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 70_000_000); + AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 70_000_000); RunUtil.getDefault().sleep(10); // Wait for the metrics to propagate to statsd. diff --git a/tests/src/android/cts/statsd/subscriber/ShellSubscriberTest.java b/tests/src/android/cts/statsd/subscriber/ShellSubscriberTest.java index 7f622120..a79b2b0d 100644 --- a/tests/src/android/cts/statsd/subscriber/ShellSubscriberTest.java +++ b/tests/src/android/cts/statsd/subscriber/ShellSubscriberTest.java @@ -149,7 +149,7 @@ public class ShellSubscriberTest extends DeviceTestCase { // Pushed event. arbitrary label = 1 AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 1); + AtomsProto.AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 1); // Make sure the last 19 threads die before moving to the next step. // First subscription is still active due to its longer timeout that is used keep @@ -188,7 +188,7 @@ public class ShellSubscriberTest extends DeviceTestCase { // Pushed event. arbitrary label = 1 AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 1); + AtomsProto.AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 1); // Make sure all the threads die before moving to the next step for (int i = 0; i <= maxSubs; i++) { @@ -275,7 +275,7 @@ public class ShellSubscriberTest extends DeviceTestCase { // Pushed event. arbitrary label = 1 AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.UNSPECIFIED.ordinal(), 1); + AtomsProto.AppBreadcrumbReported.State.UNSPECIFIED.getNumber(), 1); // Wait for thread to die before returning shellThread.join(); // Remove config from device if not already deleted diff --git a/tests/src/android/cts/statsd/validation/ProcStatsValidationTests.java b/tests/src/android/cts/statsd/validation/ProcStatsValidationTests.java index 9d6f1ada..6b61497d 100644 --- a/tests/src/android/cts/statsd/validation/ProcStatsValidationTests.java +++ b/tests/src/android/cts/statsd/validation/ProcStatsValidationTests.java @@ -90,12 +90,12 @@ public class ProcStatsValidationTests extends ProcStateTestCase { RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); final String fileName = "PROCSTATSQ_PULL.pbtxt"; - StatsdConfig config = createValidationUtil().getConfig(fileName); + StatsdConfig config = ValidationTestUtil.getConfig(fileName, mCtsBuild); LogUtil.CLog.d("Updating the following config:\n" + config.toString()); ConfigUtils.uploadConfig(getDevice(), config.toBuilder()); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT); AtomTestUtils.sendAppBreadcrumbReportedAtom(getDevice(), - AtomsProto.AppBreadcrumbReported.State.START.ordinal(), 1); + AtomsProto.AppBreadcrumbReported.State.START.getNumber(), 1); RunUtil.getDefault().sleep(AtomTestUtils.WAIT_TIME_SHORT + 5_000); List<Atom> statsdData = ReportUtils.getGaugeMetricAtoms(getDevice()); @@ -282,15 +282,6 @@ public class ProcStatsValidationTests extends ProcStateTestCase { getDevice().executeShellCommand("dumpsys procstats --commit"); } - /** - * Create and return {@link ValidationTestUtil} and give it the current build. - */ - public ValidationTestUtil createValidationUtil() { - ValidationTestUtil util = new ValidationTestUtil(); - util.setBuild(mCtsBuild); - return util; - } - /* * Get all processes' procstats statsd data in proto */ diff --git a/tests/src/android/cts/statsd/validation/ValidationTestUtil.java b/tests/src/android/cts/statsd/validation/ValidationTestUtil.java index d3e5bad5..cb3a41eb 100644 --- a/tests/src/android/cts/statsd/validation/ValidationTestUtil.java +++ b/tests/src/android/cts/statsd/validation/ValidationTestUtil.java @@ -15,11 +15,10 @@ */ package android.cts.statsd.validation; -import android.cts.statsd.atom.BaseTestCase; - +import com.android.compatibility.common.tradefed.build.CompatibilityBuildHelper; import com.android.internal.os.StatsdConfigProto.StatsdConfig; +import com.android.tradefed.build.IBuildInfo; import com.android.tradefed.log.LogUtil; -import com.android.tradefed.log.LogUtil.CLog; import com.android.tradefed.util.FileUtil; import com.google.protobuf.TextFormat; @@ -28,14 +27,14 @@ import com.google.protobuf.TextFormat.ParseException; import java.io.File; import java.io.IOException; -public class ValidationTestUtil extends BaseTestCase { +public class ValidationTestUtil { private static final String TAG = "Statsd.ValidationTestUtil"; - public StatsdConfig getConfig(String fileName) throws IOException { + public static StatsdConfig getConfig(String fileName, IBuildInfo ctsBuild) throws IOException { try { // TODO: Ideally, we should use real metrics that are also pushed to the fleet. - File configFile = getBuildHelper().getTestFile(fileName); + File configFile = getBuildHelper(ctsBuild).getTestFile(fileName); String configStr = FileUtil.readStringFromFile(configFile); StatsdConfig.Builder builder = StatsdConfig.newBuilder(); TextFormat.merge(configStr, builder); @@ -47,4 +46,8 @@ public class ValidationTestUtil extends BaseTestCase { } return null; } + + private static CompatibilityBuildHelper getBuildHelper(IBuildInfo ctsBuild) { + return new CompatibilityBuildHelper(ctsBuild); + } } |