OLD | NEW |
(Empty) | |
| 1 // Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package org.chromium.base.test; |
| 6 |
| 7 import android.support.test.InstrumentationRegistry; |
| 8 import android.support.test.uiautomator.UiDevice; |
| 9 |
| 10 import org.junit.runners.model.Statement; |
| 11 |
| 12 import org.chromium.base.Log; |
| 13 |
| 14 import java.io.File; |
| 15 |
| 16 /** |
| 17 * Statement that captures screenshots if |base| statement fails. |
| 18 * |
| 19 * If --screenshot-path commandline flag is given, this |Statement| |
| 20 * will save a screenshot to the specified path in the case of a test failure. |
| 21 */ |
| 22 public class ScreenshotOnFailureStatement extends Statement { |
| 23 private static final String TAG = "ScreenshotOnFail"; |
| 24 |
| 25 private static final String EXTRA_SCREENSHOT_FILE = |
| 26 "org.chromium.base.test.ScreenshotOnFailureStatement.ScreenshotFile"
; |
| 27 |
| 28 private final Statement mBase; |
| 29 |
| 30 public ScreenshotOnFailureStatement(final Statement base) { |
| 31 mBase = base; |
| 32 } |
| 33 |
| 34 @Override |
| 35 public void evaluate() throws Throwable { |
| 36 try { |
| 37 mBase.evaluate(); |
| 38 } catch (Throwable e) { |
| 39 takeScreenshot(); |
| 40 throw e; |
| 41 } |
| 42 } |
| 43 |
| 44 private void takeScreenshot() { |
| 45 String screenshotFilePath = |
| 46 InstrumentationRegistry.getArguments().getString(EXTRA_SCREENSHO
T_FILE); |
| 47 if (screenshotFilePath == null) { |
| 48 Log.d(TAG, |
| 49 String.format("Did not save screenshot of failure. Must spec
ify %s " |
| 50 + "instrumentation argument to enable this f
eature.", |
| 51 EXTRA_SCREENSHOT_FILE)); |
| 52 return; |
| 53 } |
| 54 |
| 55 UiDevice uiDevice = UiDevice.getInstance(InstrumentationRegistry.getInst
rumentation()); |
| 56 File screenshotFile = new File(screenshotFilePath); |
| 57 File screenshotDir = screenshotFile.getParentFile(); |
| 58 if (screenshotDir == null) { |
| 59 Log.d(TAG, |
| 60 String.format( |
| 61 "Failed to create parent directory for %s. Can't sav
e screenshot.", |
| 62 screenshotFile)); |
| 63 return; |
| 64 } |
| 65 if (!screenshotDir.exists()) { |
| 66 if (!screenshotDir.mkdirs()) { |
| 67 Log.d(TAG, |
| 68 String.format( |
| 69 "Failed to create %s. Can't save screenshot.", s
creenshotDir)); |
| 70 return; |
| 71 } |
| 72 } |
| 73 Log.d(TAG, String.format("Saving screenshot of test failure, %s", screen
shotFile)); |
| 74 uiDevice.takeScreenshot(screenshotFile); |
| 75 } |
| 76 } |
OLD | NEW |