• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /********************************************************************
2  * COPYRIGHT:
3  * Copyright (c) 1997-2006, International Business Machines Corporation and
4  * others. All Rights Reserved.
5  ********************************************************************/
6 /********************************************************************************
7 *
8 * File CINTLTST.C
9 *
10 * Modification History:
11 *        Name                     Description
12 *     Madhu Katragadda               Creation
13 *********************************************************************************
14 */
15 
16 /*The main root for C API tests*/
17 
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
21 #include "unicode/utypes.h"
22 #include "unicode/putil.h"
23 #include "cstring.h"
24 #include "cintltst.h"
25 #include "umutex.h"
26 #include "uassert.h"
27 #include "cmemory.h"
28 #include "unicode/uchar.h"
29 #include "unicode/ustring.h"
30 #include "unicode/ucnv.h"
31 #include "unicode/ures.h"
32 #include "unicode/uclean.h"
33 #include "unicode/ucal.h"
34 #include "uoptions.h"
35 #include "putilimp.h" /* for uprv_getUTCtime() */
36 
37 #ifdef XP_MAC_CONSOLE
38 #   include <console.h>
39 #endif
40 
41 #define CTST_LEAK_CHECK 1
42 #ifdef CTST_LEAK_CHECK
43 U_CFUNC void ctst_freeAll(void);
44 #endif
45 
46 static char* _testDataPath=NULL;
47 
48 /*
49  *  Forward Declarations
50  */
51 void ctest_setICU_DATA(void);
52 
53 
54 
55 #if UCONFIG_NO_LEGACY_CONVERSION
56 #   define TRY_CNV_1 "iso-8859-1"
57 #   define TRY_CNV_2 "ibm-1208"
58 #else
59 #   define TRY_CNV_1 "iso-8859-7"
60 #   define TRY_CNV_2 "sjis"
61 #endif
62 
63 
64 /*
65  * Tracing functions.
66  */
67 static int traceFnNestingDepth = 0;
68 U_CDECL_BEGIN
TraceEntry(const void * context,int32_t fnNumber)69 static void U_CALLCONV TraceEntry(const void *context, int32_t fnNumber) {
70     char buf[500];
71     utrace_format(buf, sizeof(buf), traceFnNestingDepth*3, "%s() enter.\n", utrace_functionName(fnNumber));
72     buf[sizeof(buf)-1]=0;
73     fputs(buf, stdout);
74     traceFnNestingDepth++;
75 }
76 
TraceExit(const void * context,int32_t fnNumber,const char * fmt,va_list args)77 static void U_CALLCONV TraceExit(const void *context, int32_t fnNumber, const char *fmt, va_list args) {
78     char buf[500];
79 
80     if (traceFnNestingDepth>0) {
81         traceFnNestingDepth--;
82     }
83     utrace_format(buf, sizeof(buf), traceFnNestingDepth*3, "%s() ", utrace_functionName(fnNumber));
84     buf[sizeof(buf)-1]=0;
85     fputs(buf, stdout);
86     utrace_vformat(buf, sizeof(buf), traceFnNestingDepth*3, fmt, args);
87     buf[sizeof(buf)-1]=0;
88     fputs(buf, stdout);
89     putc('\n', stdout);
90 }
91 
TraceData(const void * context,int32_t fnNumber,int32_t level,const char * fmt,va_list args)92 static void U_CALLCONV TraceData(const void *context, int32_t fnNumber,
93                           int32_t level, const char *fmt, va_list args) {
94     char buf[500];
95     utrace_vformat(buf, sizeof(buf), traceFnNestingDepth*3, fmt, args);
96     buf[sizeof(buf)-1]=0;
97     fputs(buf, stdout);
98     putc('\n', stdout);
99 }
100 U_CDECL_END
101 
102 
103 
main(int argc,const char * const argv[])104 int main(int argc, const char* const argv[])
105 {
106     int nerrors = 0;
107     int warnOnMissingData = 0;
108     int i, j;
109     UBool   defaultDataFound;
110     TestNode *root;
111     const char *warnOrErr = "Failure";
112     const char** argv2;
113     UDate startTime, endTime;
114     int32_t diffTime;
115 
116     /* initial check for the default converter */
117     UErrorCode errorCode = U_ZERO_ERROR;
118     UResourceBundle *rb;
119     UConverter *cnv;
120 
121     U_MAIN_INIT_ARGS(argc, argv);
122 
123     startTime = uprv_getUTCtime();
124 
125     argv2 = (const char**) malloc(sizeof(char*) * argc);
126     if (argv2 == NULL) {
127         printf("*** Error: Out of memory (too many cmd line args?)\n");
128         return 1;
129     }
130     argv2[0] = argv[0];
131 
132 
133     /* Checkargs */
134     /* TODO:  Test framework arg handling needs to be decoupled from test execution
135      *        so that the args being processed here don't need special handling,
136      *        separate from the other test args.
137      */
138     ICU_TRACE = UTRACE_OFF;
139     for(i=1,j=1;i<argc;i++) {
140         argv2[j++] = argv[i];
141         if(!strcmp(argv[i],"-w")) {
142             warnOnMissingData = 1;
143             warnOrErr = "Warning";
144         }
145         else if (strcmp( argv[i], "-t_error") == 0) {
146             ICU_TRACE = UTRACE_ERROR;
147         }
148         else if (strcmp( argv[i], "-t_warn") == 0) {
149             ICU_TRACE = UTRACE_WARNING;
150         }
151         else if (strcmp( argv[i], "-t_oc") == 0) {
152             ICU_TRACE = UTRACE_OPEN_CLOSE;
153         }
154         else if (strcmp( argv[i], "-t_info") == 0) {
155             ICU_TRACE = UTRACE_INFO;
156         }
157         else if (strcmp( argv[i], "-t_verbose") == 0) {
158             ICU_TRACE = UTRACE_VERBOSE;
159         }
160     }
161     argc = j;
162 
163 
164     utrace_setFunctions(NULL, TraceEntry, TraceExit, TraceData);
165     utrace_setLevel(ICU_TRACE);
166 
167 
168     while (REPEAT_TESTS > 0) {   /* Loop runs once per complete execution of the tests
169                                   *   used for -r  (repeat) test option.                */
170 
171         /* Check whether ICU will initialize without forcing the build data directory into
172          *  the ICU_DATA path.  Success here means either the data dll contains data, or that
173          *  this test program was run with ICU_DATA set externally.  Failure of this check
174          *  is normal when ICU data is not packaged into a shared library.
175          *
176          *  Whether or not this test succeeds, we want to cleanup and reinitialize
177          *  with a data path so that data loading from individual files can be tested.
178          */
179         defaultDataFound = TRUE;
180         u_init(&errorCode);
181         if (U_FAILURE(errorCode)) {
182             fprintf(stderr,
183                 "#### Note:  ICU Init without build-specific setDataDirectory() failed. %s\n", u_errorName(errorCode));
184             defaultDataFound = FALSE;
185         }
186         u_cleanup();
187         errorCode = U_ZERO_ERROR;
188         utrace_setFunctions(NULL, TraceEntry, TraceExit, TraceData);
189         utrace_setLevel(ICU_TRACE);
190 
191         /* Initialize ICU */
192         if (!defaultDataFound) {
193             ctest_setICU_DATA();    /* u_setDataDirectory() must happen Before u_init() */
194         }
195         u_init(&errorCode);
196         if (U_FAILURE(errorCode)) {
197             fprintf(stderr,
198                 "#### ERROR! %s: u_init() failed with status = \"%s\".\n"
199                 "*** Check the ICU_DATA environment variable and \n"
200                 "*** check that the data files are present.\n", argv[0], u_errorName(errorCode));
201                 if(warnOnMissingData == 0) {
202                     fprintf(stderr, "*** Exiting.  Use the '-w' option if data files were\n*** purposely removed, to continue test anyway.\n");
203                     u_cleanup();
204                     return 1;
205                 }
206         }
207 
208 
209 
210         /* try more data */
211         cnv = ucnv_open(TRY_CNV_2, &errorCode);
212         if(cnv != 0) {
213             /* ok */
214             ucnv_close(cnv);
215         } else {
216             fprintf(stderr,
217                     "*** %s! The converter for " TRY_CNV_2 " cannot be opened.\n"
218                     "*** Check the ICU_DATA environment variable and \n"
219                     "*** check that the data files are present.\n", warnOrErr);
220             if(warnOnMissingData == 0) {
221                 fprintf(stderr, "*** Exitting.  Use the '-w' option if data files were\n*** purposely removed, to continue test anyway.\n");
222                 u_cleanup();
223                 return 1;
224             }
225         }
226 
227         rb = ures_open(NULL, "en", &errorCode);
228         if(U_SUCCESS(errorCode)) {
229             /* ok */
230             ures_close(rb);
231         } else {
232             fprintf(stderr,
233                     "*** %s! The \"en\" locale resource bundle cannot be opened.\n"
234                     "*** Check the ICU_DATA environment variable and \n"
235                     "*** check that the data files are present.\n", warnOrErr);
236             if(warnOnMissingData == 0) {
237                 fprintf(stderr, "*** Exitting.  Use the '-w' option if data files were\n*** purposely removed, to continue test anyway.\n");
238                 u_cleanup();
239                 return 1;
240             }
241         }
242 
243         errorCode = U_ZERO_ERROR;
244         rb = ures_open(NULL, NULL, &errorCode);
245         if(U_SUCCESS(errorCode)) {
246             /* ok */
247             if (errorCode == U_USING_DEFAULT_WARNING || errorCode == U_USING_FALLBACK_WARNING) {
248                 fprintf(stderr,
249                         "#### Note: The default locale %s is not available\n", uloc_getDefault());
250             }
251             ures_close(rb);
252         } else {
253             fprintf(stderr,
254                     "*** %s! Can not open a resource bundle for the default locale %s\n", warnOrErr, uloc_getDefault());
255             if(warnOnMissingData == 0) {
256                 fprintf(stderr, "*** Exitting.  Use the '-w' option if data files were\n"
257                     "*** purposely removed, to continue test anyway.\n");
258                 u_cleanup();
259                 return 1;
260             }
261         }
262         fprintf(stdout, "Default locale for this run is %s\n", uloc_getDefault());
263 
264         /* Build a tree of all tests.
265          *   Subsequently will be used to find / iterate the tests to run */
266         root = NULL;
267         addAllTests(&root);
268 
269         /*  Tests acutally run HERE.   TODO:  separate command line option parsing & setting from test execution!! */
270         nerrors = processArgs(root, argc, argv2);
271 
272         if (--REPEAT_TESTS > 0) {
273             printf("Repeating tests %d more time(s)\n", REPEAT_TESTS);
274         }
275         cleanUpTestTree(root);
276 
277 #ifdef CTST_LEAK_CHECK
278         ctst_freeAll();
279         /* To check for leaks */
280         u_cleanup(); /* nuke the hashtable.. so that any still-open cnvs are leaked */
281 #endif
282 
283     }  /* End of loop that repeats the entire test, if requested.  (Normally doesn't loop)  */
284 
285     free((void*)argv2);
286 
287     endTime = uprv_getUTCtime();
288     diffTime = (int32_t)(endTime - startTime);
289     printf("Elapsed Time: %02d:%02d:%02d.%03d\n",
290         (int)((diffTime%U_MILLIS_PER_DAY)/U_MILLIS_PER_HOUR),
291         (int)((diffTime%U_MILLIS_PER_HOUR)/U_MILLIS_PER_MINUTE),
292         (int)((diffTime%U_MILLIS_PER_MINUTE)/U_MILLIS_PER_SECOND),
293         (int)(diffTime%U_MILLIS_PER_SECOND));
294 
295     return nerrors ? 1 : 0;
296 }
297 
298 /*
299 static void ctest_appendToDataDirectory(const char *toAppend)
300 {
301     const char *oldPath ="";
302     char newBuf [1024];
303     char *newPath = newBuf;
304     int32_t oldLen;
305     int32_t newLen;
306 
307     if((toAppend == NULL) || (*toAppend == 0)) {
308         return;
309     }
310 
311     oldPath = u_getDataDirectory();
312     if( (oldPath==NULL) || (*oldPath == 0)) {
313         u_setDataDirectory(toAppend);
314     } else {
315         oldLen = strlen(oldPath);
316         newLen = strlen(toAppend)+1+oldLen;
317 
318         if(newLen > 1022)
319         {
320             newPath = (char *)ctst_malloc(newLen);
321         }
322 
323         strcpy(newPath, oldPath);
324         strcpy(newPath+oldLen, U_PATH_SEP_STRING);
325         strcpy(newPath+oldLen+1, toAppend);
326 
327         u_setDataDirectory(newPath);
328 
329         if(newPath != newBuf)
330         {
331             free(newPath);
332         }
333     }
334 }
335 */
336 
337 /* returns the path to icu/source/data */
ctest_dataSrcDir()338 const char *  ctest_dataSrcDir()
339 {
340     static const char *dataSrcDir = NULL;
341 
342     if(dataSrcDir) {
343         return dataSrcDir;
344     }
345 
346     /* U_TOPSRCDIR is set by the makefiles on UNIXes when building cintltst and intltst
347     //              to point to the top of the build hierarchy, which may or
348     //              may not be the same as the source directory, depending on
349     //              the configure options used.  At any rate,
350     //              set the data path to the built data from this directory.
351     //              The value is complete with quotes, so it can be used
352     //              as-is as a string constant.
353     */
354 #if defined (U_TOPSRCDIR)
355     {
356         dataSrcDir = U_TOPSRCDIR  U_FILE_SEP_STRING "data" U_FILE_SEP_STRING;
357     }
358 #else
359 
360     /* On Windows, the file name obtained from __FILE__ includes a full path.
361      *             This file is "wherever\icu\source\test\cintltst\cintltst.c"
362      *             Change to    "wherever\icu\source\data"
363      */
364     {
365         static char p[sizeof(__FILE__) + 20];
366         char *pBackSlash;
367         int i;
368 
369         strcpy(p, __FILE__);
370         /* We want to back over three '\' chars.                            */
371         /*   Only Windows should end up here, so looking for '\' is safe.   */
372         for (i=1; i<=3; i++) {
373             pBackSlash = strrchr(p, U_FILE_SEP_CHAR);
374             if (pBackSlash != NULL) {
375                 *pBackSlash = 0;        /* Truncate the string at the '\'   */
376             }
377         }
378 
379         if (pBackSlash != NULL) {
380             /* We found and truncated three names from the path.
381              *  Now append "source\data" and set the environment
382              */
383             strcpy(pBackSlash, U_FILE_SEP_STRING "data" U_FILE_SEP_STRING );
384             dataSrcDir = p;
385         }
386         else {
387             /* __FILE__ on MSVC7 does not contain the directory */
388             FILE *file = fopen(".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING "data" U_FILE_SEP_STRING "Makefile.in", "r");
389             if (file) {
390                 fclose(file);
391                 dataSrcDir = ".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING "data" U_FILE_SEP_STRING;
392             }
393             else {
394                 dataSrcDir = ".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING "data" U_FILE_SEP_STRING;
395             }
396         }
397     }
398 #endif
399 
400     return dataSrcDir;
401 
402 }
403 
404 /* returns the path to icu/source/data/out */
ctest_dataOutDir()405 const char *ctest_dataOutDir()
406 {
407     static const char *dataOutDir = NULL;
408 
409     if(dataOutDir) {
410         return dataOutDir;
411     }
412 
413     /* U_TOPBUILDDIR is set by the makefiles on UNIXes when building cintltst and intltst
414     //              to point to the top of the build hierarchy, which may or
415     //              may not be the same as the source directory, depending on
416     //              the configure options used.  At any rate,
417     //              set the data path to the built data from this directory.
418     //              The value is complete with quotes, so it can be used
419     //              as-is as a string constant.
420     */
421 #if defined (U_TOPBUILDDIR)
422     {
423         dataOutDir = U_TOPBUILDDIR "data"U_FILE_SEP_STRING"out"U_FILE_SEP_STRING;
424     }
425 #else
426 
427     /* On Windows, the file name obtained from __FILE__ includes a full path.
428      *             This file is "wherever\icu\source\test\cintltst\cintltst.c"
429      *             Change to    "wherever\icu\source\data"
430      */
431     {
432         static char p[sizeof(__FILE__) + 20];
433         char *pBackSlash;
434         int i;
435 
436         strcpy(p, __FILE__);
437         /* We want to back over three '\' chars.                            */
438         /*   Only Windows should end up here, so looking for '\' is safe.   */
439         for (i=1; i<=3; i++) {
440             pBackSlash = strrchr(p, U_FILE_SEP_CHAR);
441             if (pBackSlash != NULL) {
442                 *pBackSlash = 0;        /* Truncate the string at the '\'   */
443             }
444         }
445 
446         if (pBackSlash != NULL) {
447             /* We found and truncated three names from the path.
448              *  Now append "source\data" and set the environment
449              */
450             strcpy(pBackSlash, U_FILE_SEP_STRING "data" U_FILE_SEP_STRING "out" U_FILE_SEP_STRING);
451             dataOutDir = p;
452         }
453         else {
454             /* __FILE__ on MSVC7 does not contain the directory */
455             FILE *file = fopen(".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING "data" U_FILE_SEP_STRING "Makefile.in", "r");
456             if (file) {
457                 fclose(file);
458                 dataOutDir = ".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING "data" U_FILE_SEP_STRING "out" U_FILE_SEP_STRING;
459             }
460             else {
461                 dataOutDir = ".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING "data" U_FILE_SEP_STRING "out" U_FILE_SEP_STRING;
462             }
463         }
464     }
465 #endif
466 
467     return dataOutDir;
468 }
469 
470 /*  ctest_setICU_DATA  - if the ICU_DATA environment variable is not already
471  *                       set, try to deduce the directory in which ICU was built,
472  *                       and set ICU_DATA to "icu/source/data" in that location.
473  *                       The intent is to allow the tests to have a good chance
474  *                       of running without requiring that the user manually set
475  *                       ICU_DATA.  Common data isn't a problem, since it is
476  *                       picked up via a static (build time) reference, but the
477  *                       tests dynamically load some data.
478  */
ctest_setICU_DATA()479 void ctest_setICU_DATA() {
480 
481     /* No location for the data dir was identifiable.
482      *   Add other fallbacks for the test data location here if the need arises
483      */
484     if (getenv("ICU_DATA") == NULL) {
485         /* If ICU_DATA isn't set, set it to the usual location */
486         u_setDataDirectory(ctest_dataOutDir());
487     }
488 }
489 
CharsToUChars(const char * str)490 UChar* CharsToUChars(const char* str) {
491     /* Might be faster to just use uprv_strlen() as the preflight len - liu */
492     int32_t len = u_unescape(str, 0, 0); /* preflight */
493     /* Do NOT use malloc() - we are supposed to be acting like user code! */
494     UChar *buf = (UChar*) malloc(sizeof(UChar) * (len + 1));
495     u_unescape(str, buf, len + 1);
496     return buf;
497 }
498 
austrdup(const UChar * unichars)499 char *austrdup(const UChar* unichars)
500 {
501     int   length;
502     char *newString;
503 
504     length    = u_strlen ( unichars );
505     /*newString = (char*)malloc  ( sizeof( char ) * 4 * ( length + 1 ) );*/ /* this leaks for now */
506     newString = (char*)ctst_malloc  ( sizeof( char ) * 4 * ( length + 1 ) ); /* this shouldn't */
507 
508     if ( newString == NULL )
509         return NULL;
510 
511     u_austrcpy ( newString, unichars );
512 
513     return newString;
514 }
515 
aescstrdup(const UChar * unichars,int32_t length)516 char *aescstrdup(const UChar* unichars,int32_t length){
517     char *newString,*targetLimit,*target;
518     UConverterFromUCallback cb;
519     const void *p;
520     UErrorCode errorCode = U_ZERO_ERROR;
521 #if U_CHARSET_FAMILY==U_EBCDIC_FAMILY
522 #   ifdef OS390
523         static const char convName[] = "ibm-1047";
524 #   else
525         static const char convName[] = "ibm-37";
526 #   endif
527 #else
528     static const char convName[] = "US-ASCII";
529 #endif
530     UConverter* conv = ucnv_open(convName, &errorCode);
531     if(length==-1){
532         length = u_strlen( unichars);
533     }
534     newString = (char*)ctst_malloc ( sizeof(char) * 8 * (length +1));
535     target = newString;
536     targetLimit = newString+sizeof(char) * 8 * (length +1);
537     ucnv_setFromUCallBack(conv, UCNV_FROM_U_CALLBACK_ESCAPE, UCNV_ESCAPE_JAVA, &cb, &p, &errorCode);
538     ucnv_fromUnicode(conv,&target,targetLimit, &unichars, (UChar*)(unichars+length),NULL,TRUE,&errorCode);
539     ucnv_close(conv);
540     *target = '\0';
541     return newString;
542 }
543 
loadTestData(UErrorCode * err)544 const char* loadTestData(UErrorCode* err){
545     if( _testDataPath == NULL){
546         const char*      directory=NULL;
547         UResourceBundle* test =NULL;
548         char* tdpath=NULL;
549         const char* tdrelativepath;
550 #if defined (U_TOPBUILDDIR)
551         tdrelativepath = "test"U_FILE_SEP_STRING"testdata"U_FILE_SEP_STRING"out"U_FILE_SEP_STRING;
552         directory = U_TOPBUILDDIR;
553 #else
554         tdrelativepath = ".."U_FILE_SEP_STRING".."U_FILE_SEP_STRING"test"U_FILE_SEP_STRING"testdata"U_FILE_SEP_STRING"out"U_FILE_SEP_STRING;
555         directory= ctest_dataOutDir();
556 #endif
557 
558         tdpath = (char*) ctst_malloc(sizeof(char) *(( strlen(directory) * strlen(tdrelativepath)) + 10));
559 
560 
561         /* u_getDataDirectory shoul return \source\data ... set the
562          * directory to ..\source\data\..\test\testdata\out\testdata
563          *
564          * Fallback: When Memory mapped file is built
565          * ..\source\data\out\..\..\test\testdata\out\testdata
566          */
567         strcpy(tdpath, directory);
568         strcat(tdpath, tdrelativepath);
569         strcat(tdpath,"testdata");
570 
571 
572         test=ures_open(tdpath, "testtypes", err);
573 
574         /* Fall back did not succeed either so return */
575         if(U_FAILURE(*err)){
576             *err = U_FILE_ACCESS_ERROR;
577             log_err("Could not load testtypes.res in testdata bundle with path %s - %s\n", tdpath, u_errorName(*err));
578             return "";
579         }
580         ures_close(test);
581         _testDataPath = tdpath;
582         return _testDataPath;
583     }
584     return _testDataPath;
585 }
586 
587 #define CTEST_MAX_TIMEZONE_SIZE 256
588 static UChar gOriginalTimeZone[CTEST_MAX_TIMEZONE_SIZE] = {0};
589 
590 /**
591  * Call this once to get a consistent timezone. Use ctest_resetTimeZone to set it back to the original value.
592  * @param optionalTimeZone Set this to a requested timezone.
593  *      Set to NULL to use the standard test timezone (Pacific Time)
594  */
ctest_setTimeZone(const char * optionalTimeZone,UErrorCode * status)595 U_CFUNC void ctest_setTimeZone(const char *optionalTimeZone, UErrorCode *status) {
596 #if !UCONFIG_NO_FORMATTING
597     UChar zoneID[CTEST_MAX_TIMEZONE_SIZE];
598 
599     if (optionalTimeZone == NULL) {
600         optionalTimeZone = "America/Los_Angeles";
601     }
602     if (gOriginalTimeZone[0]) {
603         log_err("*** Error: time zone saved twice. New value will be %s\n",
604                optionalTimeZone);
605     }
606     ucal_getDefaultTimeZone(gOriginalTimeZone, CTEST_MAX_TIMEZONE_SIZE, status);
607     if (U_FAILURE(*status)) {
608         log_err("*** Error: Failed to save default time zone: %s\n",
609                u_errorName(*status));
610         *status = U_ZERO_ERROR;
611     }
612 
613     u_uastrncpy(zoneID, optionalTimeZone, CTEST_MAX_TIMEZONE_SIZE-1);
614     zoneID[CTEST_MAX_TIMEZONE_SIZE-1] = 0;
615     ucal_setDefaultTimeZone(zoneID, status);
616     if (U_FAILURE(*status)) {
617         log_err("*** Error: Failed to set default time zone to \"%s\": %s\n",
618                optionalTimeZone, u_errorName(*status));
619     }
620 #endif
621 }
622 
623 /**
624  * Call this once get back the original timezone
625  */
ctest_resetTimeZone(void)626 U_CFUNC void ctest_resetTimeZone(void) {
627 #if !UCONFIG_NO_FORMATTING
628     UErrorCode status = U_ZERO_ERROR;
629 
630     ucal_setDefaultTimeZone(gOriginalTimeZone, &status);
631     if (U_FAILURE(status)) {
632         log_err("*** Error: Failed to reset default time zone: %s\n",
633                u_errorName(status));
634     }
635     /* Set to an empty state */
636     gOriginalTimeZone[0] = 0;
637 #endif
638 }
639 
640 #define CTST_MAX_ALLOC 8192
641 /* Array used as a queue */
642 static void * ctst_allocated_stuff[CTST_MAX_ALLOC] = {0};
643 static int ctst_allocated = 0;
644 static UBool ctst_free = FALSE;
645 
ctst_malloc(size_t size)646 void *ctst_malloc(size_t size) {
647     if(ctst_allocated >= CTST_MAX_ALLOC - 1) {
648         ctst_allocated = 0;
649         ctst_free = TRUE;
650     }
651     if(ctst_allocated_stuff[ctst_allocated]) {
652         free(ctst_allocated_stuff[ctst_allocated]);
653     }
654     return ctst_allocated_stuff[ctst_allocated++] = malloc(size);
655 }
656 
657 #ifdef CTST_LEAK_CHECK
ctst_freeAll()658 void ctst_freeAll() {
659     int i;
660     if(ctst_free == 0) {
661         for(i=0; i<ctst_allocated; i++) {
662             free(ctst_allocated_stuff[i]);
663             ctst_allocated_stuff[i] = NULL;
664         }
665     } else {
666         for(i=0; i<CTST_MAX_ALLOC; i++) {
667             free(ctst_allocated_stuff[i]);
668             ctst_allocated_stuff[i] = NULL;
669         }
670     }
671     ctst_allocated = 0;
672     _testDataPath=NULL;
673 }
674 
675 #define VERBOSE_ASSERTIONS
676 
assertSuccess(const char * msg,UErrorCode * ec)677 U_CFUNC UBool assertSuccess(const char* msg, UErrorCode* ec) {
678     U_ASSERT(ec!=NULL);
679     if (U_FAILURE(*ec)) {
680         log_err("FAIL: %s (%s)\n", msg, u_errorName(*ec));
681         return FALSE;
682     }
683     return TRUE;
684 }
685 
686 /* if 'condition' is a UBool, the compiler complains bitterly about
687    expressions like 'a > 0' which it evaluates as int */
assertTrue(const char * msg,int condition)688 U_CFUNC UBool assertTrue(const char* msg, int /*not UBool*/ condition) {
689     if (!condition) {
690         log_err("FAIL: assertTrue() failed: %s\n", msg);
691     }
692 #ifdef VERBOSE_ASSERTIONS
693     else {
694         log_verbose("Ok: %s\n", msg);
695     }
696 #endif
697     return (UBool)condition;
698 }
699 
assertEquals(const char * message,const char * expected,const char * actual)700 U_CFUNC UBool assertEquals(const char* message, const char* expected,
701                            const char* actual) {
702     if (uprv_strcmp(expected, actual) != 0) {
703         log_err("FAIL: %s; got \"%s\"; expected \"%s\"\n",
704                 message, actual, expected);
705         return FALSE;
706     }
707 #ifdef VERBOSE_ASSERTIONS
708     else {
709         log_verbose("Ok: %s; got \"%s\"\n", message, actual);
710     }
711 #endif
712     return TRUE;
713 }
714 /*--------------------------------------------------------------------
715  * Time bomb - allows temporary behavior that expires at a given
716  *             release
717  *--------------------------------------------------------------------
718  */
719 
isICUVersionAtLeast(const UVersionInfo x)720 U_CFUNC UBool isICUVersionAtLeast(const UVersionInfo x) {
721     UVersionInfo v;
722     u_getVersion(v);
723     return (uprv_memcmp(v, x, U_MAX_VERSION_LENGTH) >= 0);
724 }
725 #endif
726