1/*
2 * Copyright (C) 2015 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
17package com.android.mtp;
18
19import android.os.Bundle;
20import android.test.InstrumentationTestRunner;
21
22import junit.framework.AssertionFailedError;
23import junit.framework.Test;
24import junit.framework.TestListener;
25
26/**
27 * Instrumentation that can show the test result in the TestResultActivity.
28 * It's useful when it runs testcases with a real USB device and could not use USB port for ADB.
29 */
30public class TestResultInstrumentation extends InstrumentationTestRunner implements TestListener {
31    private boolean mHasError = false;
32
33    @Override
34    public void onCreate(Bundle arguments) {
35        if (arguments == null) {
36            arguments = new Bundle();
37        }
38        final boolean includeRealDeviceTest =
39                Boolean.parseBoolean(arguments.getString("realDeviceTest", "false"));
40        if (!includeRealDeviceTest) {
41            arguments.putString("notAnnotation", "com.android.mtp.RealDeviceTest");
42        }
43        super.onCreate(arguments);
44        if (includeRealDeviceTest) {
45            // Show the test result by using activity because we need to disconnect USB cable
46            // from adb host while testing with real MTP device.
47            addTestListener(this);
48        }
49    }
50
51    @Override
52    public void addError(Test test, Throwable t) {
53        mHasError = true;
54        show("ERROR", test, t);
55    }
56
57    @Override
58    public void addFailure(Test test, AssertionFailedError t) {
59        mHasError = true;
60        show("FAIL", test, t);
61    }
62
63    @Override
64    public void endTest(Test test) {
65        if (!mHasError) {
66            show("PASS", test, null);
67        }
68    }
69
70    @Override
71    public void startTest(Test test) {
72        mHasError = false;
73    }
74
75    void show(String message) {
76        TestResultActivity.show(getContext(), "    " + message);
77    }
78
79    private void show(String tag, Test test, Throwable t) {
80        String message = "";
81        if (t != null && t.getMessage() != null) {
82            message = t.getMessage();
83        }
84        TestResultActivity.show(
85                getContext(), String.format("[%s] %s %s", tag, test.toString(), message));
86    }
87}
88