1 /*
2  * Copyright (C) 2018 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.signature.cts.api;
18 
19 import android.signature.cts.FailureType;
20 import android.signature.cts.ResultObserver;
21 
22 import java.io.PrintWriter;
23 import java.io.StringWriter;
24 import junit.framework.Assert;
25 import junit.framework.TestCase;
26 
27 /**
28  * Keeps track of any reported failures.
29  */
30 class TestResultObserver implements ResultObserver {
31 
32     private boolean mDidFail = false;
33     private int failures = 0;
34 
35     private StringWriter mErrorString = new StringWriter();
36 
37     @Override
notifyFailure(FailureType type, String name, String errorMessage, Throwable throwable)38     public void notifyFailure(FailureType type, String name, String errorMessage,
39             Throwable throwable) {
40         mDidFail = true;
41         failures++;
42         if (failures <= 100) {
43             mErrorString.append("\n");
44             mErrorString.append(type.toString().toLowerCase());
45             mErrorString.append(":\t");
46             mErrorString.append(name);
47             mErrorString.append("\tError: ");
48             mErrorString.append(errorMessage);
49             if (throwable != null) {
50                 mErrorString.append("\n");
51                 throwable.printStackTrace(new PrintWriter(mErrorString));
52             }
53         } else if (failures == 101) {
54             mErrorString.append("\nMore than 100 failures, aborting test.");
55             finalizeErrorString();
56             Assert.fail(mErrorString.toString());
57         }
58     }
59 
finalizeErrorString()60     private void finalizeErrorString() {
61         ClassLoader classLoader = getClass().getClassLoader();
62         mErrorString.append("\nClassLoader hierarchy\n");
63         while (classLoader != null) {
64             mErrorString.append("    ").append(classLoader.toString()).append("\n");
65             classLoader = classLoader.getParent();
66         }
67         mErrorString.append(String.valueOf(failures)).append("failures");
68     }
69 
onTestComplete()70     public void onTestComplete() {
71         if (mDidFail) {
72             finalizeErrorString();
73             Assert.fail(mErrorString.toString());
74         }
75     }
76 }
77