1/*
2 * Copyright (C) 2017 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 */
16package android.multiuser;
17
18import android.app.Activity;
19import android.app.Instrumentation;
20import android.os.Bundle;
21import android.support.test.InstrumentationRegistry;
22import android.util.Log;
23
24import org.junit.rules.TestRule;
25import org.junit.runner.Description;
26import org.junit.runners.model.Statement;
27
28import java.util.ArrayList;
29
30public class BenchmarkResultsReporter implements TestRule {
31    private final BenchmarkRunner mRunner;
32
33    public BenchmarkResultsReporter(BenchmarkRunner benchmarkRunner) {
34        mRunner = benchmarkRunner;
35    }
36
37    @Override
38    public Statement apply(final Statement base, final Description description) {
39        return new Statement() {
40            @Override
41            public void evaluate() throws Throwable {
42                base.evaluate();
43                final Bundle stats = mRunner.getStatsToReport();
44                final String summary = getSummaryString(description.getMethodName(),
45                        mRunner.getStatsToLog());
46                logSummary(description.getTestClass().getSimpleName(), summary,
47                        mRunner.getAllDurations());
48                stats.putString(Instrumentation.REPORT_KEY_STREAMRESULT, summary);
49                InstrumentationRegistry.getInstrumentation().sendStatus(
50                        Activity.RESULT_OK, stats);
51            }
52        };
53    }
54
55    private void logSummary(String tag, String summary, ArrayList<Long> durations) {
56        final StringBuilder sb = new StringBuilder(summary);
57        final int size = durations.size();
58        for (int i = 0; i < size; ++i) {
59            sb.append("\n").append(i).append("->").append(durations.get(i));
60        }
61        Log.d(tag, sb.toString());
62    }
63
64    private String getSummaryString(String testName, Bundle stats) {
65        final StringBuilder sb = new StringBuilder();
66        sb.append("\n\n").append(getKey(testName));
67        for (String key : stats.keySet()) {
68            sb.append("\n").append(key).append(": ").append(stats.get(key));
69        }
70        return sb.toString();
71    }
72
73    private String getKey(String testName) {
74        return testName.replaceAll("Perf$", "");
75    }
76}
77