tests/InputMethodStressTest/src/com/android/inputmethod/stresstest/ScreenCaptureRule.java
raw symbols SCIP| 1 | /* |
| 2 | * Copyright (C) 2022 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package com.android.inputmethod.stresstest; |
| 18 | |
| 19 | import com.android.compatibility.common.util.SystemUtil; |
| 20 | |
| 21 | import org.junit.rules.TestWatcher; |
| 22 | import org.junit.runner.Description; |
| 23 | |
| 24 | import java.text.SimpleDateFormat; |
| 25 | import java.util.Date; |
| 26 | |
| 27 | /** |
| 28 | * Takes a screenshot when the test fails. |
| 29 | * |
| 30 | * <p>Use {@link com.android.tradefed.device.metric.FilePullerLogCollector} to collect screenshots |
| 31 | * taken. |
| 32 | * For example, in AndroidTest.xml: |
| 33 | * <code> |
| 34 | * <metrics_collector class="com.android.tradefed.device.metric.FilePullerLogCollector"> |
| 35 | * <option name="directory-keys" value="/sdcard/MyTest/" /> |
| 36 | * <option name="collect-on-run-ended-only" value="true" /> |
| 37 | * </metrics_collector> |
| 38 | * </code> |
| 39 | * in MyTest.java: |
| 40 | * <code> |
| 41 | * @Rule |
| 42 | * public ScreenCaptureRule mScreenCaptureRule = new ScreenCaptureRule("/sdcard/MyTest"); |
| 43 | * </code> |
| 44 | */ |
| 45 | public class ScreenCaptureRule extends TestWatcher { |
| 46 | |
| 47 | private static final String TAG = "ScreenCaptureRule"; |
| 48 | |
| 49 | private final String mOutDir; |
| 50 | |
| 51 | public ScreenCaptureRule(String outDir) { |
| 52 | mOutDir = outDir; |
| 53 | } |
| 54 | |
| 55 | @Override |
| 56 | protected void failed(Throwable e, Description description) { |
| 57 | super.failed(e, description); |
| 58 | String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date()); |
| 59 | String fileName = "screenshot-" + time + ".png"; |
| 60 | capture(fileName); |
| 61 | } |
| 62 | |
| 63 | /** Take a screenshot. */ |
| 64 | public void capture(String fileName) { |
| 65 | SystemUtil.runCommandAndPrintOnLogcat(TAG, String.format("mkdir -p %s", mOutDir)); |
| 66 | SystemUtil.runCommandAndPrintOnLogcat(TAG, |
| 67 | String.format("screencap %s/%s", mOutDir, fileName)); |
| 68 | } |
| 69 | } |