• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* GENERATED SOURCE. DO NOT MODIFY. */
2 // © 2016 and later: Unicode, Inc. and others.
3 // License & terms of use: http://www.unicode.org/copyright.html#License
4 /*
5  *******************************************************************************
6  * Copyright (C) 1996-2015, International Business Machines Corporation and    *
7  * others. All Rights Reserved.                                                *
8  *******************************************************************************
9  */
10 package ohos.global.icu.dev.test;
11 
12 import java.lang.reflect.Constructor;
13 import java.lang.reflect.Method;
14 import java.lang.reflect.Modifier;
15 import java.security.Policy;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.List;
19 import java.util.Locale;
20 import java.util.Map;
21 import java.util.Properties;
22 import java.util.Random;
23 import java.util.TreeMap;
24 
25 import org.junit.After;
26 import org.junit.Assert;
27 import org.junit.Before;
28 
29 import ohos.global.icu.util.TimeZone;
30 import ohos.global.icu.util.ULocale;
31 
32 /**
33  * TestFmwk is a base class for tests that can be run conveniently from the
34  * command line as well as under the Java test harness.
35  * <p>
36  * Sub-classes implement a set of methods named Test <something>. Each of these
37  * methods performs some test. Test methods should indicate errors by calling
38  * either err or errln. This will increment the errorCount field and may
39  * optionally print a message to the log. Debugging information may also be
40  * added to the log via the log and logln methods. These methods will add their
41  * arguments to the log only if the test is being run in verbose mode.
42  */
43 abstract public class TestFmwk extends AbstractTestLog {
44     /**
45      * The default time zone for all of our tests. Used in @Before
46      */
47     private final static TimeZone defaultTimeZone = TimeZone.getTimeZone("America/Los_Angeles");
48 
49     /**
50      * The default locale used for all of our tests. Used in @Before
51      */
52     private final static Locale defaultLocale = Locale.US;
53 
54     private static final String EXHAUSTIVENESS = "ICU.exhaustive";
55     private static final int DEFAULT_EXHAUSTIVENESS = 0;
56     private static final int MAX_EXHAUSTIVENESS = 10;
57 
58     private static final String LOGGING_LEVEL = "ICU.logging";
59     private static final int DEFAULT_LOGGING_LEVEL = 0;
60     private static final int MAX_LOGGING_LEVEL = 3;
61 
62     public static final int LOGGING_NONE = 0;
63     public static final int LOGGING_WARN = 1;
64     public static final int LOGGING_INFO = 2;
65     public static final int LOGGING_DEBUG = 3;
66 
67     private static final String SEED = "ICU.seed";
68     private static final String SECURITY_POLICY = "ICU.securitypolicy";
69 
70     private static final TestParams testParams;
71     static {
72         testParams = TestParams.create();
73     }
74 
TestFmwk()75     protected TestFmwk() {
76     }
77 
78     @Before
testInitialize()79     public final void testInitialize() {
80         Locale.setDefault(defaultLocale);
81         TimeZone.setDefault(defaultTimeZone);
82 
83         if (getParams().testSecurityManager != null) {
84             System.setSecurityManager(getParams().testSecurityManager);
85         }
86 
87         localTestInitialize();
88     }
89 
90     /**
91      * This method is called at the end of {@link #testInitialize()}.
92      * Because JUnit does not guarantee the order of multiple Before
93      * methods, TestFmwk implementation class should override this
94      * method, instead of annotating Before.
95      */
localTestInitialize()96     protected void localTestInitialize() {
97     }
98 
99     /**
100      * This method is called at the beginning of {@link #testTeardown()}.
101      * TestFmwk implementation class hould override this method, instead
102      * of annotating After.
103      */
localTestTeardown()104     protected void localTestTeardown() {
105     }
106 
107     @After
testTeardown()108     public final void testTeardown() {
109         localTestTeardown();
110 
111         if (getParams().testSecurityManager != null) {
112             System.setSecurityManager(getParams().originalSecurityManager);
113         }
114     }
115 
getParams()116     private static TestParams getParams() {
117         //return paramsReference.get();
118         return testParams;
119     }
120 
isVerbose()121     protected static boolean isVerbose() {
122         return getParams().getLoggingLevel() >= LOGGING_INFO;
123     }
124 
125     /**
126      * 0 = fewest tests, 5 is normal build, 10 is most tests
127      */
getExhaustiveness()128     protected static int getExhaustiveness() {
129         return getParams().inclusion;
130     }
131 
isQuick()132     protected static boolean isQuick() {
133         return getParams().getInclusion() == 0;
134     }
135 
136     // use this instead of new random so we get a consistent seed
137     // for our tests
createRandom()138     protected Random createRandom() {
139         return new Random(getParams().getSeed());
140     }
141 
142     /**
143      * Integer Random number generator, produces positive int values.
144      * Similar to C++ std::minstd_rand, with the same algorithm & constants.
145      * Provided for compatibility with ICU4C.
146      * Get & set of the seed allows for reproducible monkey tests.
147      */
148     protected class ICU_Rand {
149         private int fLast;
150 
ICU_Rand(int seed)151         public ICU_Rand(int seed) {
152             seed(seed);
153         }
154 
next()155         public int next() {
156             fLast = (int)((fLast * 48271L) % 2147483647L);
157             return fLast;
158         }
159 
seed(int seed)160         public void seed(int seed) {
161             if (seed <= 0) {
162                 seed = 1;
163             }
164             seed %= 2147483647;   // = 0x7FFFFFFF
165             fLast = seed > 0 ? seed : 1;
166         }
167 
getSeed()168         public int getSeed() {
169             return fLast;
170         }
171 
172     }
173 
174     static final String ICU_TRAC_URL = "http://bugs.icu-project.org/trac/ticket/";
175     static final String CLDR_TRAC_URL = "http://unicode.org/cldr/trac/ticket/";
176     static final String CLDR_TICKET_PREFIX = "cldrbug:";
177 
178     /**
179      * Log the known issue.
180      * This method returns true unless -prop:logKnownIssue=no is specified
181      * in the argument list.
182      *
183      * @param ticket A ticket number string. For an ICU ticket, use numeric characters only,
184      * such as "10245". For a CLDR ticket, use prefix "cldrbug:" followed by ticket number,
185      * such as "cldrbug:5013".
186      * @param comment Additional comment, or null
187      * @return true unless -prop:logKnownIssue=no is specified in the test command line argument.
188      */
logKnownIssue(String ticket, String comment)189     protected static boolean logKnownIssue(String ticket, String comment) {
190         if (!getBooleanProperty("logKnownIssue", true)) {
191             return false;
192         }
193 
194         // TODO: This method currently does not do very much.
195         // See http://bugs.icu-project.org/trac/ticket/12589
196 
197         StringBuffer descBuf = new StringBuffer();
198         // TODO(junit) : what to do about this?
199         //getParams().stack.appendPath(descBuf);
200         if (comment != null && comment.length() > 0) {
201             descBuf.append(" (" + comment + ")");
202         }
203         String description = descBuf.toString();
204 
205         String ticketLink = "Unknown Ticket";
206         if (ticket != null && ticket.length() > 0) {
207             boolean isCldr = false;
208             ticket = ticket.toLowerCase(Locale.ENGLISH);
209             if (ticket.startsWith(CLDR_TICKET_PREFIX)) {
210                 isCldr = true;
211                 ticket = ticket.substring(CLDR_TICKET_PREFIX.length());
212             }
213             ticketLink = (isCldr ? CLDR_TRAC_URL : ICU_TRAC_URL) + ticket;
214         }
215 
216         if (getParams().knownIssues == null) {
217             getParams().knownIssues = new TreeMap<String, List<String>>();
218         }
219         List<String> lines = getParams().knownIssues.get(ticketLink);
220         if (lines == null) {
221             lines = new ArrayList<String>();
222             getParams().knownIssues.put(ticketLink, lines);
223         }
224         if (!lines.contains(description)) {
225             lines.add(description);
226         }
227 
228         return true;
229     }
230 
getProperty(String key)231     protected static String getProperty(String key) {
232         return getParams().getProperty(key);
233     }
234 
getBooleanProperty(String key)235     protected static boolean getBooleanProperty(String key) {
236         return getParams().getBooleanProperty(key);
237     }
238 
getBooleanProperty(String key, boolean defVal)239     protected static boolean getBooleanProperty(String key, boolean defVal) {
240         return getParams().getBooleanProperty(key, defVal);
241     }
242 
getIntProperty(String key, int defVal)243     protected static int getIntProperty(String key, int defVal) {
244         return getParams().getIntProperty(key, defVal);
245     }
246 
getIntProperty(String key, int defVal, int maxVal)247     protected static int getIntProperty(String key, int defVal, int maxVal) {
248         return getParams().getIntProperty(key, defVal, maxVal);
249     }
250 
safeGetTimeZone(String id)251     protected static TimeZone safeGetTimeZone(String id) {
252         TimeZone tz = TimeZone.getTimeZone(id);
253         if (tz == null) {
254             // should never happen
255             errln("FAIL: TimeZone.getTimeZone(" + id + ") => null");
256         }
257         if (!tz.getID().equals(id)) {
258             warnln("FAIL: TimeZone.getTimeZone(" + id + ") => " + tz.getID());
259         }
260         return tz;
261     }
262 
263 
264     // Utility Methods
265 
hex(char[] s)266     protected static String hex(char[] s){
267         StringBuffer result = new StringBuffer();
268         for (int i = 0; i < s.length; ++i) {
269             if (i != 0) result.append(',');
270             result.append(hex(s[i]));
271         }
272         return result.toString();
273     }
274 
hex(byte[] s)275     protected static String hex(byte[] s){
276         StringBuffer result = new StringBuffer();
277         for (int i = 0; i < s.length; ++i) {
278             if (i != 0) result.append(',');
279             result.append(hex(s[i]));
280         }
281         return result.toString();
282     }
283 
hex(char ch)284     protected static String hex(char ch) {
285         StringBuffer result = new StringBuffer();
286         String foo = Integer.toString(ch, 16).toUpperCase();
287         for (int i = foo.length(); i < 4; ++i) {
288             result.append('0');
289         }
290         return result + foo;
291     }
292 
hex(int ch)293     protected static String hex(int ch) {
294         StringBuffer result = new StringBuffer();
295         String foo = Integer.toString(ch, 16).toUpperCase();
296         for (int i = foo.length(); i < 4; ++i) {
297             result.append('0');
298         }
299         return result + foo;
300     }
301 
hex(CharSequence s)302     protected static String hex(CharSequence s) {
303         StringBuilder result = new StringBuilder();
304         for (int i = 0; i < s.length(); ++i) {
305             if (i != 0)
306                 result.append(',');
307             result.append(hex(s.charAt(i)));
308         }
309         return result.toString();
310     }
311 
prettify(CharSequence s)312     protected static String prettify(CharSequence s) {
313         StringBuilder result = new StringBuilder();
314         int ch;
315         for (int i = 0; i < s.length(); i += Character.charCount(ch)) {
316             ch = Character.codePointAt(s, i);
317             if (ch > 0xfffff) {
318                 result.append("\\U00");
319                 result.append(hex(ch));
320             } else if (ch > 0xffff) {
321                 result.append("\\U000");
322                 result.append(hex(ch));
323             } else if (ch < 0x20 || 0x7e < ch) {
324                 result.append("\\u");
325                 result.append(hex(ch));
326             } else {
327                 result.append((char) ch);
328             }
329 
330         }
331         return result.toString();
332     }
333 
334     private static java.util.GregorianCalendar cal;
335 
336     /**
337      * Return a Date given a year, month, and day of month. This is similar to
338      * new Date(y-1900, m, d). It uses the default time zone at the time this
339      * method is first called.
340      *
341      * @param year
342      *            use 2000 for 2000, unlike new Date()
343      * @param month
344      *            use Calendar.JANUARY etc.
345      * @param dom
346      *            day of month, 1-based
347      * @return a Date object for the given y/m/d
348      */
getDate(int year, int month, int dom)349     protected static synchronized java.util.Date getDate(int year, int month,
350             int dom) {
351         if (cal == null) {
352             cal = new java.util.GregorianCalendar();
353         }
354         cal.clear();
355         cal.set(year, month, dom);
356         return cal.getTime();
357     }
358 
359     private static class TestParams {
360 
361         private int inclusion;
362         private long seed;
363         private int loggingLevel;
364 
365         private String policyFileName;
366         private SecurityManager testSecurityManager;
367         private SecurityManager originalSecurityManager;
368 
369         private Map<String, List<String>> knownIssues;
370 
371         private Properties props;
372 
373 
TestParams()374         private TestParams() {
375         }
376 
create()377         static TestParams create() {
378             TestParams params = new TestParams();
379             Properties props = System.getProperties();
380             params.parseProperties(props);
381             return params;
382         }
383 
parseProperties(Properties props)384         private void parseProperties(Properties props) {
385             this.props = props;
386 
387             inclusion = getIntProperty(EXHAUSTIVENESS, DEFAULT_EXHAUSTIVENESS, MAX_EXHAUSTIVENESS);
388             seed = getLongProperty(SEED, System.currentTimeMillis());
389             loggingLevel = getIntProperty(LOGGING_LEVEL, DEFAULT_LOGGING_LEVEL, MAX_LOGGING_LEVEL);
390 
391             policyFileName = getProperty(SECURITY_POLICY);
392             if (policyFileName != null) {
393                 String originalPolicyFileName = System.getProperty("java.security.policy");
394                 originalSecurityManager = System.getSecurityManager();
395                 System.setProperty("java.security.policy", policyFileName);
396                 Policy.getPolicy().refresh();
397                 testSecurityManager = new SecurityManager();
398                 System.setProperty("java.security.policy", originalPolicyFileName==null ? "" : originalPolicyFileName);
399             }
400         }
401 
getProperty(String key)402         public String getProperty(String key) {
403             String val = null;
404             if (key != null && key.length() > 0) {
405                 val = props.getProperty(key);
406             }
407             return val;
408         }
409 
getBooleanProperty(String key)410         public boolean getBooleanProperty(String key) {
411             return getBooleanProperty(key, false);
412         }
413 
getBooleanProperty(String key, boolean defVal)414         public boolean getBooleanProperty(String key, boolean defVal) {
415             String s = getProperty(key);
416             if (s == null) {
417                 return defVal;
418             }
419             if (s.equalsIgnoreCase("yes") || s.equalsIgnoreCase("true") || s.equals("1")) {
420                 return true;
421             }
422             return false;
423         }
424 
getIntProperty(String key, int defVal)425         public int getIntProperty(String key, int defVal) {
426             return getIntProperty(key, defVal, -1);
427         }
428 
getIntProperty(String key, int defVal, int maxVal)429         public int getIntProperty(String key, int defVal, int maxVal) {
430             String s = getProperty(key);
431             if (s == null) {
432                 return defVal;
433             }
434             return (maxVal == -1) ? Integer.valueOf(s) : Math.max(Integer.valueOf(s), maxVal);
435         }
436 
getLongProperty(String key, long defVal)437         public long getLongProperty(String key, long defVal) {
438             String s = getProperty(key);
439             if (s == null) {
440                 return defVal;
441             }
442             return Long.valueOf(s);
443         }
444 
getInclusion()445         public int getInclusion() {
446             return inclusion;
447         }
448 
getSeed()449         public long getSeed() {
450             return seed;
451         }
452 
getLoggingLevel()453         public int getLoggingLevel() {
454             return loggingLevel;
455         }
456     }
457 
458     /**
459      * Check the given array to see that all the strings in the expected array
460      * are present.
461      *
462      * @param msg
463      *            string message, for log output
464      * @param array
465      *            array of strings to check
466      * @param expected
467      *            array of strings we expect to see, or null
468      * @return the length of 'array', or -1 on error
469      */
checkArray(String msg, String array[], String expected[])470     protected static int checkArray(String msg, String array[], String expected[]) {
471         int explen = (expected != null) ? expected.length : 0;
472         if (!(explen >= 0 && explen < 31)) { // [sic] 31 not 32
473             errln("Internal error");
474             return -1;
475         }
476         int i = 0;
477         StringBuffer buf = new StringBuffer();
478         int seenMask = 0;
479         for (; i < array.length; ++i) {
480             String s = array[i];
481             if (i != 0)
482                 buf.append(", ");
483             buf.append(s);
484             // check expected list
485             for (int j = 0, bit = 1; j < explen; ++j, bit <<= 1) {
486                 if ((seenMask & bit) == 0) {
487                     if (s.equals(expected[j])) {
488                         seenMask |= bit;
489                         logln("Ok: \"" + s + "\" seen");
490                     }
491                 }
492             }
493         }
494         logln(msg + " = [" + buf + "] (" + i + ")");
495         // did we see all expected strings?
496         if (((1 << explen) - 1) != seenMask) {
497             for (int j = 0, bit = 1; j < expected.length; ++j, bit <<= 1) {
498                 if ((seenMask & bit) == 0) {
499                     errln("\"" + expected[j] + "\" not seen");
500                 }
501             }
502         }
503         return array.length;
504     }
505 
506     /**
507      * Check the given array to see that all the locales in the expected array
508      * are present.
509      *
510      * @param msg
511      *            string message, for log output
512      * @param array
513      *            array of locales to check
514      * @param expected
515      *            array of locales names we expect to see, or null
516      * @return the length of 'array'
517      */
checkArray(String msg, Locale array[], String expected[])518     protected static int checkArray(String msg, Locale array[], String expected[]) {
519         String strs[] = new String[array.length];
520         for (int i = 0; i < array.length; ++i) {
521             strs[i] = array[i].toString();
522         }
523         return checkArray(msg, strs, expected);
524     }
525 
526     /**
527      * Check the given array to see that all the locales in the expected array
528      * are present.
529      *
530      * @param msg
531      *            string message, for log output
532      * @param array
533      *            array of locales to check
534      * @param expected
535      *            array of locales names we expect to see, or null
536      * @return the length of 'array'
537      */
checkArray(String msg, ULocale array[], String expected[])538     protected static int checkArray(String msg, ULocale array[], String expected[]) {
539         String strs[] = new String[array.length];
540         for (int i = 0; i < array.length; ++i) {
541             strs[i] = array[i].toString();
542         }
543         return checkArray(msg, strs, expected);
544     }
545 
546     // JUnit-like assertions.
547 
assertTrue(String message, boolean condition)548     protected static boolean assertTrue(String message, boolean condition) {
549         return handleAssert(condition, message, "true", null);
550     }
551 
assertFalse(String message, boolean condition)552     protected static boolean assertFalse(String message, boolean condition) {
553         return handleAssert(!condition, message, "false", null);
554     }
555 
assertEquals(String message, boolean expected, boolean actual)556     protected static boolean assertEquals(String message, boolean expected,
557             boolean actual) {
558         return handleAssert(expected == actual, message, String
559                 .valueOf(expected), String.valueOf(actual));
560     }
561 
assertEquals(String message, long expected, long actual)562     protected static boolean assertEquals(String message, long expected, long actual) {
563         return handleAssert(expected == actual, message, String
564                 .valueOf(expected), String.valueOf(actual));
565     }
566 
567     // do NaN and range calculations to precision of float, don't rely on
568     // promotion to double
assertEquals(String message, float expected, float actual, double error)569     protected static boolean assertEquals(String message, float expected,
570             float actual, double error) {
571         boolean result = Float.isInfinite(expected)
572                 ? expected == actual
573                 : !(Math.abs(expected - actual) > error); // handles NaN
574         return handleAssert(result, message, String.valueOf(expected)
575                 + (error == 0 ? "" : " (within " + error + ")"), String
576                 .valueOf(actual));
577     }
578 
assertEquals(String message, double expected, double actual, double error)579     protected static boolean assertEquals(String message, double expected,
580             double actual, double error) {
581         boolean result = Double.isInfinite(expected)
582                 ? expected == actual
583                 : !(Math.abs(expected - actual) > error); // handles NaN
584         return handleAssert(result, message, String.valueOf(expected)
585                 + (error == 0 ? "" : " (within " + error + ")"), String
586                 .valueOf(actual));
587     }
588 
assertEquals(String message, T[] expected, T[] actual)589     protected static <T> boolean assertEquals(String message, T[] expected, T[] actual) {
590         // Use toString on a List to get useful, readable messages
591         String expectedString = expected == null ? "null" : Arrays.asList(expected).toString();
592         String actualString = actual == null ? "null" : Arrays.asList(actual).toString();
593         return assertEquals(message, expectedString, actualString);
594     }
595 
assertEquals(String message, Object expected, Object actual)596     protected static boolean assertEquals(String message, Object expected,
597             Object actual) {
598         boolean result = expected == null ? actual == null : expected
599                 .equals(actual);
600         return handleAssert(result, message, stringFor(expected),
601                 stringFor(actual));
602     }
603 
assertNotEquals(String message, Object expected, Object actual)604     protected static boolean assertNotEquals(String message, Object expected,
605             Object actual) {
606         boolean result = !(expected == null ? actual == null : expected
607                 .equals(actual));
608         return handleAssert(result, message, stringFor(expected),
609                 stringFor(actual), "not equal to", true);
610     }
611 
assertSame(String message, Object expected, Object actual)612     protected boolean assertSame(String message, Object expected, Object actual) {
613         return handleAssert(expected == actual, message, stringFor(expected),
614                 stringFor(actual), "==", false);
615     }
616 
assertNotSame(String message, Object expected, Object actual)617     protected static boolean assertNotSame(String message, Object expected,
618             Object actual) {
619         return handleAssert(expected != actual, message, stringFor(expected),
620                 stringFor(actual), "!=", true);
621     }
622 
assertNull(String message, Object actual)623     protected static boolean assertNull(String message, Object actual) {
624         return handleAssert(actual == null, message, null, stringFor(actual));
625     }
626 
assertNotNull(String message, Object actual)627     protected static boolean assertNotNull(String message, Object actual) {
628         return handleAssert(actual != null, message, null, stringFor(actual),
629                 "!=", true);
630     }
631 
fail()632     protected static void fail() {
633         fail("");
634     }
635 
fail(String message)636     protected static void fail(String message) {
637         if (message == null) {
638             message = "";
639         }
640         if (!message.equals("")) {
641             message = ": " + message;
642         }
643         errln(sourceLocation() + message);
644     }
645 
handleAssert(boolean result, String message, String expected, String actual)646     private static boolean handleAssert(boolean result, String message,
647             String expected, String actual) {
648         return handleAssert(result, message, expected, actual, null, false);
649     }
650 
handleAssert(boolean result, String message, Object expected, Object actual, String relation, boolean flip)651     public static boolean handleAssert(boolean result, String message,
652             Object expected, Object actual, String relation, boolean flip) {
653         if (!result || isVerbose()) {
654             if (message == null) {
655                 message = "";
656             }
657             if (!message.equals("")) {
658                 message = ": " + message;
659             }
660             relation = relation == null ? ", got " : " " + relation + " ";
661             if (result) {
662                 logln("OK " + message + ": "
663                         + (flip ? expected + relation + actual : expected));
664             } else {
665                 // assert must assume errors are true errors and not just warnings
666                 // so cannot warnln here
667                 errln(  message
668                         + ": expected"
669                         + (flip ? relation + expected : " " + expected
670                                 + (actual != null ? relation + actual : "")));
671             }
672         }
673         return result;
674     }
675 
stringFor(Object obj)676     private static final String stringFor(Object obj) {
677         if (obj == null) {
678             return "null";
679         }
680         if (obj instanceof String) {
681             return "\"" + obj + '"';
682         }
683         return obj.getClass().getName() + "<" + obj + ">";
684     }
685 
686     // Return the source code location of the caller located callDepth frames up the stack.
sourceLocation()687     protected static String sourceLocation() {
688         // Walk up the stack to the first call site outside this file
689         for (StackTraceElement st : new Throwable().getStackTrace()) {
690             String source = st.getFileName();
691             if (source != null && !source.equals("TestFmwk.java") && !source.equals("AbstractTestLog.java")) {
692                 String methodName = st.getMethodName();
693                 if (methodName != null &&
694                        (methodName.startsWith("Test") || methodName.startsWith("test") || methodName.equals("main"))) {
695                     return "(" + source + ":" + st.getLineNumber() + ") ";
696                 }
697             }
698         }
699         throw new InternalError();
700     }
701 
checkDefaultPrivateConstructor(String fullyQualifiedClassName)702     protected static boolean checkDefaultPrivateConstructor(String fullyQualifiedClassName) throws Exception {
703         return checkDefaultPrivateConstructor(Class.forName(fullyQualifiedClassName));
704     }
705 
checkDefaultPrivateConstructor(Class<?> classToBeTested)706     protected static boolean checkDefaultPrivateConstructor(Class<?> classToBeTested) throws Exception {
707         Constructor<?> constructor = classToBeTested.getDeclaredConstructor();
708 
709         // Check that the constructor is private.
710         boolean isPrivate = Modifier.isPrivate(constructor.getModifiers());
711 
712         // Call the constructor for coverage.
713         constructor.setAccessible(true);
714         constructor.newInstance();
715 
716         if (!isPrivate) {
717             errln("Default private constructor for class: " + classToBeTested.getName() + " is not private.");
718         }
719         return isPrivate;
720     }
721 
722     /**
723      * Tests the toString method on a private or hard-to-reach class.  Assumes constructor of the class does not
724      * take any arguments.
725      * @param fullyQualifiedClassName
726      * @return The output of the toString method.
727      * @throws Exception
728      */
invokeToString(String fullyQualifiedClassName)729     protected static String invokeToString(String fullyQualifiedClassName) throws Exception {
730         return invokeToString(fullyQualifiedClassName, new Class<?>[]{}, new Object[]{});
731     }
732 
733     /**
734      * Tests the toString method on a private or hard-to-reach class.  Assumes constructor of the class does not
735      * take any arguments.
736      * @param classToBeTested
737      * @return The output of the toString method.
738      * @throws Exception
739      */
invokeToString(Class<?> classToBeTested)740     protected static String invokeToString(Class<?> classToBeTested) throws Exception {
741         return invokeToString(classToBeTested, new Class<?>[]{}, new Object[]{});
742     }
743 
744     /**
745      * Tests the toString method on a private or hard-to-reach class.  Allows you to specify the argument types for
746      * the constructor.
747      * @param fullyQualifiedClassName
748      * @return The output of the toString method.
749      * @throws Exception
750      */
invokeToString(String fullyQualifiedClassName, Class<?>[] constructorParamTypes, Object[] constructorParams)751     protected static String invokeToString(String fullyQualifiedClassName,
752             Class<?>[] constructorParamTypes, Object[] constructorParams) throws Exception {
753         return invokeToString(Class.forName(fullyQualifiedClassName), constructorParamTypes, constructorParams);
754     }
755 
756     /**
757      * Tests the toString method on a private or hard-to-reach class.  Allows you to specify the argument types for
758      * the constructor.
759      * @param classToBeTested
760      * @return The output of the toString method.
761      * @throws Exception
762      */
invokeToString(Class<?> classToBeTested, Class<?>[] constructorParamTypes, Object[] constructorParams)763     protected static String invokeToString(Class<?> classToBeTested,
764             Class<?>[] constructorParamTypes, Object[] constructorParams) throws Exception {
765         Constructor<?> constructor = classToBeTested.getDeclaredConstructor(constructorParamTypes);
766         constructor.setAccessible(true);
767         Object obj = constructor.newInstance(constructorParams);
768         Method toStringMethod = classToBeTested.getDeclaredMethod("toString");
769         toStringMethod.setAccessible(true);
770         return (String) toStringMethod.invoke(obj);
771     }
772 
773 
774     // End JUnit-like assertions
775 
776     // TODO (sgill): added to keep errors away
777     /* (non-Javadoc)
778      * @see ohos.global.icu.dev.test.TestLog#msg(java.lang.String, int, boolean, boolean)
779      */
780     //@Override
msg(String message, int level, boolean incCount, boolean newln)781     protected static void msg(String message, int level, boolean incCount, boolean newln) {
782         if (level == TestLog.WARN || level == TestLog.ERR) {
783             Assert.fail(message);
784         }
785         // TODO(stuartg): turned off - causing OOM running under ant
786 //        while (level > 0) {
787 //            System.out.print(" ");
788 //            level--;
789 //        }
790 //        System.out.print(message);
791 //        if (newln) {
792 //            System.out.println();
793 //        }
794     }
795 
796 }
797