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