1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License 15 */ 16 17 package android.accessibility.cts.common; 18 19 import androidx.test.rule.ActivityTestRule; 20 21 import org.junit.rules.ExternalResource; 22 import org.junit.rules.RuleChain; 23 import org.junit.rules.TestWatcher; 24 import org.junit.runner.Description; 25 26 /** 27 * Custom {@code TestRule} that dump accessibility related data upon test failures. 28 * 29 * <p>Note: when using other {@code TestRule}s, make sure to use a {@link RuleChain} to ensure it 30 * is applied outside of other rules that can fail a test (otherwise this rule may not know that the 31 * test failed). If using with {@link ExternalResource}-like {@code TestRule}s, {@link 32 * ActivityTestRule} or {@link InstrumentedAccessibilityService}, this rule should chaining as a 33 * inner rule to resources-like rules so that it will dump data before resources are cleaned up. 34 * 35 * <p>To capture the output of this rule, add the following to AndroidTest.xml: 36 * <pre> 37 * <!-- Collect output of AccessibilityDumpOnFailureRule. --> 38 * <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector"> 39 * <option name="directory-keys" value="/sdcard/<test.package.name>" /> 40 * <option name="collect-on-run-ended-only" value="true" /> 41 * </metrics_collector> 42 * </pre> 43 * <p>And disable external storage isolation: 44 * <pre> 45 * <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" /> 46 * <application ... android:requestLegacyExternalStorage="true" ... > 47 * </pre> 48 */ 49 public class AccessibilityDumpOnFailureRule extends TestWatcher { 50 dump(int flag)51 public void dump(int flag) { 52 AccessibilityDumper.getInstance().dump(flag); 53 } 54 55 @Override starting(Description description)56 protected void starting(Description description) { 57 AccessibilityDumper.getInstance().setName(getTestNameFrom(description)); 58 } 59 60 @Override failed(Throwable t, Description description)61 protected void failed(Throwable t, Description description) { 62 AccessibilityDumper.getInstance().dump(); 63 } 64 getTestNameFrom(Description description)65 private String getTestNameFrom(Description description) { 66 return description.getTestClass().getSimpleName() 67 + "_" + description.getMethodName(); 68 } 69 } 70