• 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 **********************************************************************
5 * Copyright (C) 2011-2015, International Business Machines Corporation
6 * and others.  All Rights Reserved.
7 **********************************************************************
8 */
9 /**
10  * IntlTestSpoof tests for USpoofDetector
11  */
12 
13 #include "unicode/utypes.h"
14 
15 #if !UCONFIG_NO_REGULAR_EXPRESSIONS && !UCONFIG_NO_NORMALIZATION && !UCONFIG_NO_FILE_IO
16 
17 #include "itspoof.h"
18 
19 #include "unicode/normlzr.h"
20 #include "unicode/regex.h"
21 #include "unicode/unistr.h"
22 #include "unicode/uscript.h"
23 #include "unicode/uspoof.h"
24 
25 #include "cstring.h"
26 #include "scriptset.h"
27 #include "uhash.h"
28 
29 #include <stdlib.h>
30 #include <stdio.h>
31 
32 #define TEST_ASSERT_SUCCESS(status) UPRV_BLOCK_MACRO_BEGIN { \
33     if (U_FAILURE(status)) { \
34         errcheckln(status, "Failure at file %s, line %d, error = %s", __FILE__, __LINE__, u_errorName(status)); \
35     } \
36 } UPRV_BLOCK_MACRO_END
37 
38 #define TEST_ASSERT(expr) UPRV_BLOCK_MACRO_BEGIN { \
39     if ((expr)==false) { \
40         errln("Test Failure at file %s, line %d: \"%s\" is false.", __FILE__, __LINE__, #expr); \
41     } \
42 } UPRV_BLOCK_MACRO_END
43 
44 #define TEST_ASSERT_MSG(expr, msg) UPRV_BLOCK_MACRO_BEGIN { \
45     if ((expr)==false) { \
46         dataerrln("Test Failure at file %s, line %d, %s: \"%s\" is false.", __FILE__, __LINE__, msg, #expr); \
47     } \
48 } UPRV_BLOCK_MACRO_END
49 
50 #define TEST_ASSERT_EQ(a, b) UPRV_BLOCK_MACRO_BEGIN { \
51     if ((a) != (b)) { \
52         errln("Test Failure at file %s, line %d: \"%s\" (%d) != \"%s\" (%d)", \
53               __FILE__, __LINE__, #a, (a), #b, (b)); \
54     } \
55 } UPRV_BLOCK_MACRO_END
56 
57 #define TEST_ASSERT_NE(a, b) UPRV_BLOCK_MACRO_BEGIN { \
58     if ((a) == (b)) { \
59         errln("Test Failure at file %s, line %d: \"%s\" (%d) == \"%s\" (%d)", \
60               __FILE__, __LINE__, #a, (a), #b, (b)); \
61     } \
62 } UPRV_BLOCK_MACRO_END
63 
64 /*
65  *   TEST_SETUP and TEST_TEARDOWN
66  *         macros to handle the boilerplate around setting up test case.
67  *         Put arbitrary test code between SETUP and TEARDOWN.
68  *         "sc" is the ready-to-go  SpoofChecker for use in the tests.
69  */
70 #define TEST_SETUP UPRV_BLOCK_MACRO_BEGIN { \
71     UErrorCode status = U_ZERO_ERROR; \
72     USpoofChecker *sc;     \
73     sc = uspoof_open(&status);  \
74     TEST_ASSERT_SUCCESS(status);   \
75     USpoofCheckResult *checkResult; \
76     checkResult = uspoof_openCheckResult(&status); \
77     TEST_ASSERT_SUCCESS(status);   \
78     if (U_SUCCESS(status)){
79 
80 #define TEST_TEARDOWN  \
81     }  \
82     TEST_ASSERT_SUCCESS(status);  \
83     uspoof_closeCheckResult(checkResult); \
84     uspoof_close(sc);  \
85 } UPRV_BLOCK_MACRO_END
86 
87 
88 
89 
runIndexedTest(int32_t index,UBool exec,const char * & name,char *)90 void IntlTestSpoof::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ )
91 {
92     if (exec) {
93         logln("TestSuite spoof: ");
94     }
95     TESTCASE_AUTO_BEGIN;
96     TESTCASE_AUTO(testSpoofAPI);
97     TESTCASE_AUTO(testSkeleton);
98     TESTCASE_AUTO(testBidiSkeleton);
99     TESTCASE_AUTO(testAreConfusable);
100     TESTCASE_AUTO(testInvisible);
101     TESTCASE_AUTO(testConfData);
102     TESTCASE_AUTO(testBug8654);
103     TESTCASE_AUTO(testScriptSet);
104     TESTCASE_AUTO(testRestrictionLevel);
105     TESTCASE_AUTO(testMixedNumbers);
106     TESTCASE_AUTO(testBug12153);
107     TESTCASE_AUTO(testBug12825);
108     TESTCASE_AUTO(testBug12815);
109     TESTCASE_AUTO(testBug13314_MixedNumbers);
110     TESTCASE_AUTO(testBug13328_MixedCombiningMarks);
111     TESTCASE_AUTO(testCombiningDot);
112     TESTCASE_AUTO_END;
113 }
114 
testSpoofAPI()115 void IntlTestSpoof::testSpoofAPI() {
116 
117     TEST_SETUP
118         UnicodeString s("xyz");  // Many latin ranges are whole-script confusable with other scripts.
119                                  // If this test starts failing, consult confusablesWholeScript.txt
120         int32_t position = 666;
121         int32_t checkResults = uspoof_checkUnicodeString(sc, s, &position, &status);
122         TEST_ASSERT_SUCCESS(status);
123         TEST_ASSERT_EQ(0, checkResults);
124         TEST_ASSERT_EQ(0, position);
125     TEST_TEARDOWN;
126 
127     TEST_SETUP
128         UnicodeString s1("cxs");
129         UnicodeString s2 = UnicodeString("\\u0441\\u0445\\u0455").unescape();  // Cyrillic "cxs"
130         int32_t checkResults = uspoof_areConfusableUnicodeString(sc, s1, s2, &status);
131         TEST_ASSERT_SUCCESS(status);
132         TEST_ASSERT_EQ(USPOOF_MIXED_SCRIPT_CONFUSABLE | USPOOF_WHOLE_SCRIPT_CONFUSABLE, checkResults);
133 
134     TEST_TEARDOWN;
135 
136     TEST_SETUP
137         UnicodeString s("I1l0O");
138         UnicodeString dest;
139         UnicodeString &retStr = uspoof_getSkeletonUnicodeString(sc, USPOOF_ANY_CASE, s, dest, &status);
140         TEST_ASSERT_SUCCESS(status);
141         TEST_ASSERT(UnicodeString("lllOO") == dest);
142         TEST_ASSERT(&dest == &retStr);
143     TEST_TEARDOWN;
144 
145     TEST_SETUP
146         // Example from UTS #55, Section 5.1.3 https://www.unicode.org/reports/tr55/#General-Security-Profile
147         // of a minimal pair with a ZWNJ in Persian.
148         const UnicodeString behrooz(u"بهروز");
149         const UnicodeString update(u"به‌روز");
150         // These strings differ only by a ZWNJ.
151         TEST_ASSERT(UnicodeString(update).findAndReplace(u"\u200C", u"") == behrooz);
152         int32_t checkResults = uspoof_areConfusableUnicodeString(sc, behrooz, update, &status);
153         TEST_ASSERT_SUCCESS(status);
154         TEST_ASSERT_EQ(USPOOF_SINGLE_SCRIPT_CONFUSABLE, checkResults);
155     TEST_TEARDOWN;
156 }
157 
158 #define CHECK_SKELETON(type, input, expected)                                                           \
159     UPRV_BLOCK_MACRO_BEGIN { checkSkeleton(sc, type, input, expected, __LINE__); }                      \
160     UPRV_BLOCK_MACRO_END
161 
162 #define CHECK_BIDI_SKELETON(type, input, expected)                                                           \
163     UPRV_BLOCK_MACRO_BEGIN { checkBidiSkeleton(sc, type, input, expected, __LINE__); }                      \
164     UPRV_BLOCK_MACRO_END
165 
166 
167 // testSkeleton.   Spot check a number of confusable skeleton substitutions from the
168 //                 Unicode data file confusables.txt
169 //                 Test cases chosen for substitutions of various lengths, and
170 //                 membership in different mapping tables.
171 //          Note: for ICU 55, all tables collapsed to the MA table data.
172 //          TODO: for ICU 56 with Unicode 8, revisit this test.
173 //
testSkeleton()174 void IntlTestSpoof::testSkeleton() {
175     const uint32_t ML = 0;
176     const uint32_t SL = USPOOF_SINGLE_SCRIPT_CONFUSABLE;
177     const uint32_t MA = USPOOF_ANY_CASE;
178     const uint32_t SA = USPOOF_SINGLE_SCRIPT_CONFUSABLE | USPOOF_ANY_CASE;
179 
180     TEST_SETUP
181         CHECK_SKELETON(SL, "nochange", "nochange");
182         CHECK_SKELETON(SA, "nochange", "nochange");
183         CHECK_SKELETON(ML, "nochange", "nochange");
184         CHECK_SKELETON(MA, "nochange", "nochange");
185         CHECK_SKELETON(MA, "love", "love");
186         CHECK_SKELETON(MA, "1ove", "love");   // Digit 1 to letter l
187         CHECK_SKELETON(ML, "OOPS", "OOPS");
188         CHECK_SKELETON(ML, "00PS", "OOPS");
189         CHECK_SKELETON(MA, "OOPS", "OOPS");
190         CHECK_SKELETON(MA, "00PS", "OOPS");   // Digit 0 to letter O in any case mode only
191         CHECK_SKELETON(SL, "\\u059c", "\\u0301");
192         CHECK_SKELETON(SL, "\\u2A74", "\\u003A\\u003A\\u003D");
193         CHECK_SKELETON(SL, "\\u247E", "\\u0028\\u006C\\u006C\\u0029");  // "(ll)"
194         CHECK_SKELETON(SL, "\\uFDFB", "\\u062C\\u0644\\u0020\\u062C\\u0644\\u006c\\u0644\\u006f");
195 
196         // This mapping exists in the ML and MA tables, does not exist in SL, SA
197         // 0C83 ;	0983 ;	ML
198         // 0C83 ;	0983 ;	MA
199         //
200 
201         CHECK_SKELETON(SL, "\\u0C83", "\\u0983");
202         CHECK_SKELETON(SA, "\\u0C83", "\\u0983");
203         CHECK_SKELETON(ML, "\\u0C83", "\\u0983");
204         CHECK_SKELETON(MA, "\\u0C83", "\\u0983");
205 
206         // 0391 mappings exist only in MA and SA tables.
207         CHECK_SKELETON(MA, "\\u0391", "A");
208         CHECK_SKELETON(SA, "\\u0391", "A");
209         CHECK_SKELETON(ML, "\\u0391", "A");
210         CHECK_SKELETON(SL, "\\u0391", "A");
211 
212         // 13CF Mappings in all four tables, different in MA.
213         CHECK_SKELETON(ML, "\\u13CF", "b");
214         CHECK_SKELETON(MA, "\\u13CF", "b");
215         CHECK_SKELETON(SL, "\\u13CF", "b");
216         CHECK_SKELETON(SA, "\\u13CF", "b");
217 
218         // 0022 ;  0027 0027 ;
219         // all tables.
220         CHECK_SKELETON(SL, "\\u0022", "\\u0027\\u0027");
221         CHECK_SKELETON(SA, "\\u0022", "\\u0027\\u0027");
222         CHECK_SKELETON(ML, "\\u0022", "\\u0027\\u0027");
223         CHECK_SKELETON(MA, "\\u0022", "\\u0027\\u0027");
224 
225         // 017F mappings exist only in MA and SA tables.
226         CHECK_SKELETON(MA, "\\u017F", "f");
227         CHECK_SKELETON(SA, "\\u017F", "f");
228         CHECK_SKELETON(ML, "\\u017F", "f");
229         CHECK_SKELETON(SL, "\\u017F", "f");
230 
231     TEST_TEARDOWN;
232 }
233 
testBidiSkeleton()234 void IntlTestSpoof::testBidiSkeleton() {
235     TEST_SETUP
236     CHECK_BIDI_SKELETON(u"A1<שׂ", UBIDI_LTR, u"Al<ש\u0307");
237     CHECK_BIDI_SKELETON(u"Αשֺ>1", UBIDI_LTR, u"Al<ש\u0307");
238     CHECK_BIDI_SKELETON(u"A1<שׂ", UBIDI_RTL, u"ש\u0307>Al");
239     CHECK_BIDI_SKELETON(u"Αשֺ>1", UBIDI_RTL, u"l<ש\u0307A");
240     TEST_TEARDOWN;
241 }
242 
243 
244 //
245 //  Run a single confusable skeleton transformation test case.
246 //
checkSkeleton(const USpoofChecker * sc,uint32_t type,const char * input,const char * expected,int32_t lineNum)247 void IntlTestSpoof::checkSkeleton(const USpoofChecker *sc, uint32_t type,
248                                   const char *input, const char *expected, int32_t lineNum) {
249     UnicodeString uInput = UnicodeString(input).unescape();
250     UnicodeString uExpected = UnicodeString(expected).unescape();
251 
252     UErrorCode status = U_ZERO_ERROR;
253     UnicodeString actual;
254     uspoof_getSkeletonUnicodeString(sc, type, uInput, actual, &status);
255     if (U_FAILURE(status)) {
256         errln("File %s, Line %d, Test case from line %d, status is %s", __FILE__, __LINE__, lineNum,
257               u_errorName(status));
258         return;
259     }
260     if (uExpected != actual) {
261         errln("File %s, Line %d, Test case from line %d, Actual and Expected skeletons differ.",
262                __FILE__, __LINE__, lineNum);
263         errln(UnicodeString(" Actual   Skeleton: \"") + actual + UnicodeString("\"\n") +
264               UnicodeString(" Expected Skeleton: \"") + uExpected + UnicodeString("\""));
265     }
266 }
267 
268 //
269 //  Run a single confusable bidiSkeleton transformation test case.
270 //
checkBidiSkeleton(const USpoofChecker * sc,const UnicodeString & input,UBiDiDirection direction,const UnicodeString & expected,int32_t lineNum)271 void IntlTestSpoof::checkBidiSkeleton(const USpoofChecker *sc, const UnicodeString &input,
272                                       UBiDiDirection direction, const UnicodeString &expected,
273                                       int32_t lineNum) {
274     UnicodeString uInput = input.unescape();
275     UnicodeString uExpected = expected.unescape();
276 
277     UErrorCode status = U_ZERO_ERROR;
278     UnicodeString actual;
279     uspoof_getBidiSkeletonUnicodeString(sc, direction, uInput, actual, &status);
280     if (U_FAILURE(status)) {
281         errln("File %s, Line %d, Test case from line %d, status is %s", __FILE__, __LINE__, lineNum,
282               u_errorName(status));
283         return;
284     }
285     if (uExpected != actual) {
286         errln("File %s, Line %d, Test case from line %d, Actual and Expected skeletons differ.",
287               __FILE__, __LINE__, lineNum);
288         errln(UnicodeString(" Actual   Skeleton: \"") + actual + UnicodeString("\"\n") +
289               UnicodeString(" Expected Skeleton: \"") + uExpected + UnicodeString("\""));
290     }
291 }
292 
testAreConfusable()293 void IntlTestSpoof::testAreConfusable() {
294     TEST_SETUP
295         UnicodeString s1("A long string that will overflow stack buffers.  A long string that will overflow stack buffers. "
296                          "A long string that will overflow stack buffers.  A long string that will overflow stack buffers. ");
297         UnicodeString s2("A long string that wi11 overflow stack buffers.  A long string that will overflow stack buffers. "
298                          "A long string that wi11 overflow stack buffers.  A long string that will overflow stack buffers. ");
299         int32_t result = uspoof_areConfusableUnicodeString(sc, s1, s2, &status);
300         TEST_ASSERT_SUCCESS(status);
301         TEST_ASSERT_EQ(USPOOF_SINGLE_SCRIPT_CONFUSABLE, result);
302 
303     TEST_TEARDOWN;
304 }
305 
testAreBidiConfusable()306 void IntlTestSpoof::testAreBidiConfusable() {
307     TEST_SETUP
308         const UnicodeString jHyphen2(u"J-2");
309         // The following string has RLMs around the 2–, flipping it; it uses an
310         // EN DASH instead of the HYPHEN-MINUS above.
311         const UnicodeString j2Dash(u"J\u200F2\u2013\u200F");
312         TEST_ASSERT(j2Dash == u"J‏2–‏");
313         int32_t result = uspoof_areBidiConfusableUnicodeString(sc, UBIDI_LTR, jHyphen2, j2Dash, &status);
314         TEST_ASSERT_SUCCESS(status);
315         TEST_ASSERT_EQ(USPOOF_SINGLE_SCRIPT_CONFUSABLE, result);
316 
317     TEST_TEARDOWN;
318 }
319 
testInvisible()320 void IntlTestSpoof::testInvisible() {
321     TEST_SETUP
322         UnicodeString  s = UnicodeString("abcd\\u0301ef").unescape();
323         int32_t position = -42;
324         TEST_ASSERT_EQ(0, uspoof_checkUnicodeString(sc, s, &position, &status));
325         TEST_ASSERT_SUCCESS(status);
326         TEST_ASSERT(0 == position);
327 
328         UnicodeString  s2 = UnicodeString("abcd\\u0301\\u0302\\u0301ef").unescape();
329         TEST_ASSERT_EQ(USPOOF_INVISIBLE, uspoof_checkUnicodeString(sc, s2, &position, &status));
330         TEST_ASSERT_SUCCESS(status);
331         TEST_ASSERT_EQ(0, position);
332 
333         // Two acute accents, one from the composed a with acute accent, \u00e1,
334         // and one separate.
335         position = -42;
336         UnicodeString  s3 = UnicodeString("abcd\\u00e1\\u0301xyz").unescape();
337         TEST_ASSERT_EQ(USPOOF_INVISIBLE, uspoof_checkUnicodeString(sc, s3, &position, &status));
338         TEST_ASSERT_SUCCESS(status);
339         TEST_ASSERT_EQ(0, position);
340     TEST_TEARDOWN;
341 }
342 
testBug8654()343 void IntlTestSpoof::testBug8654() {
344     TEST_SETUP
345         UnicodeString s = UnicodeString("B\\u00c1\\u0301").unescape();
346         int32_t position = -42;
347         TEST_ASSERT_EQ(USPOOF_INVISIBLE, uspoof_checkUnicodeString(sc, s, &position, &status) & USPOOF_INVISIBLE );
348         TEST_ASSERT_SUCCESS(status);
349         TEST_ASSERT_EQ(0, position);
350     TEST_TEARDOWN;
351 }
352 
parseHex(const UnicodeString & in)353 static UnicodeString parseHex(const UnicodeString &in) {
354     // Convert a series of hex numbers in a Unicode String to a string with the
355     // corresponding characters.
356     // The conversion is _really_ annoying.  There must be some function to just do it.
357     UnicodeString result;
358     UChar32 cc = 0;
359     for (int32_t i=0; i<in.length(); i++) {
360         char16_t c = in.charAt(i);
361         if (c == 0x20) {   // Space
362             if (cc > 0) {
363                result.append(cc);
364                cc = 0;
365             }
366         } else if (c>=0x30 && c<=0x39) {
367             cc = (cc<<4) + (c - 0x30);
368         } else if ((c>=0x41 && c<=0x46) || (c>=0x61 && c<=0x66)) {
369             cc = (cc<<4) + (c & 0x0f)+9;
370         }
371         // else do something with bad input.
372     }
373     if (cc > 0) {
374         result.append(cc);
375     }
376     return result;
377 }
378 
379 
380 //
381 // Append the hex form of a UChar32 to a UnicodeString.
382 // Used in formatting error messages.
383 // Match the formatting of numbers in confusables.txt
384 // Minimum of 4 digits, no leading zeroes for positions 5 and up.
385 //
appendHexUChar(UnicodeString & dest,UChar32 c)386 static void appendHexUChar(UnicodeString &dest, UChar32 c) {
387     UBool   doZeroes = false;
388     for (int bitNum=28; bitNum>=0; bitNum-=4) {
389         if (bitNum <= 12) {
390             doZeroes = true;
391         }
392         int hexDigit = (c>>bitNum) & 0x0f;
393         if (hexDigit != 0 || doZeroes) {
394             doZeroes = true;
395             dest.append(static_cast<char16_t>(hexDigit <= 9 ? hexDigit + 0x30 : hexDigit - 10 + 0x41));
396         }
397     }
398     dest.append(static_cast<char16_t>(0x20));
399 }
400 
401 U_DEFINE_LOCAL_OPEN_POINTER(LocalStdioFilePointer, FILE, fclose);
402 
403 //  testConfData - Check each data item from the Unicode confusables.txt file,
404 //                 verify that it transforms correctly in a skeleton.
405 //
testConfData()406 void IntlTestSpoof::testConfData() {
407     char buffer[2000];
408     if (getUnidataPath(buffer) == nullptr) {
409         errln("Skipping test spoof/testConfData. Unable to find path to source/data/unidata/.");
410         return;
411     }
412     uprv_strcat(buffer, "confusables.txt");
413 
414     LocalStdioFilePointer f(fopen(buffer, "rb"));
415     if (f.isNull()) {
416         errln("Skipping test spoof/testConfData.  File confusables.txt not accessible.");
417         return;
418     }
419     fseek(f.getAlias(), 0, SEEK_END);
420     int32_t  fileSize = ftell(f.getAlias());
421     LocalArray<char> fileBuf(new char[fileSize]);
422     fseek(f.getAlias(), 0, SEEK_SET);
423     int32_t amt_read = static_cast<int32_t>(fread(fileBuf.getAlias(), 1, fileSize, f.getAlias()));
424     TEST_ASSERT_EQ(amt_read, fileSize);
425     TEST_ASSERT(fileSize>0);
426     if (amt_read != fileSize || fileSize <=0) {
427         return;
428     }
429     UnicodeString confusablesTxt = UnicodeString::fromUTF8(StringPiece(fileBuf.getAlias(), fileSize));
430 
431     UErrorCode status = U_ZERO_ERROR;
432     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
433     TEST_ASSERT_SUCCESS(status);
434 
435     // Parse lines from the confusables.txt file.  Example Line:
436     // FF44 ;	0064 ;	SL	# ( d -> d ) FULLWIDTH ....
437     // Three fields.  The hex fields can contain more than one character,
438     //                and each character may be more than 4 digits (for supplemntals)
439     // This regular expression matches lines and splits the fields into capture groups.
440     RegexMatcher parseLine("(?m)^([0-9A-F]{4}[^#;]*?);([^#;]*?);([^#]*)", confusablesTxt, 0, status);
441     TEST_ASSERT_SUCCESS(status);
442     while (parseLine.find()) {
443         UnicodeString from = parseHex(parseLine.group(1, status));
444         if (!Normalizer::isNormalized(from, UNORM_NFD, status)) {
445             // The source character was not NFD.
446             // Skip this case; the first step in obtaining a skeleton is to NFD the input,
447             //  so the mapping in this line of confusables.txt will never be applied.
448             continue;
449         }
450 
451         if (u_hasBinaryProperty(from.char32At(0), UCHAR_DEFAULT_IGNORABLE_CODE_POINT)) {
452             // The source character is a default ignorable code point.
453             // Skip this case; the second step in obtaining a skeleton is to remove DIs,
454             // so the mapping in this line of confusables.txt will never be applied.
455             continue;
456         }
457 
458         UnicodeString rawExpected = parseHex(parseLine.group(2, status));
459         UnicodeString expected;
460         Normalizer::decompose(rawExpected, false /*NFD*/, 0, expected, status);
461         TEST_ASSERT_SUCCESS(status);
462 
463         int32_t skeletonType = 0;
464         UnicodeString tableType = parseLine.group(3, status);
465         TEST_ASSERT_SUCCESS(status);
466         if (tableType.indexOf("SL") >= 0) {
467             skeletonType = USPOOF_SINGLE_SCRIPT_CONFUSABLE;
468         } else if (tableType.indexOf("SA") >= 0) {
469             skeletonType = USPOOF_SINGLE_SCRIPT_CONFUSABLE | USPOOF_ANY_CASE;
470         } else if (tableType.indexOf("ML") >= 0) {
471             skeletonType = 0;
472         } else if (tableType.indexOf("MA") >= 0) {
473             skeletonType = USPOOF_ANY_CASE;
474         }
475 
476         UnicodeString actual;
477         uspoof_getSkeletonUnicodeString(sc.getAlias(), skeletonType, from, actual, &status);
478         TEST_ASSERT_SUCCESS(status);
479         TEST_ASSERT(actual == expected);
480         if (actual != expected) {
481             errln(parseLine.group(0, status));
482             UnicodeString line = "Actual: ";
483             int i = 0;
484             while (i < actual.length()) {
485                 appendHexUChar(line, actual.char32At(i));
486                 i = actual.moveIndex32(i, 1);
487             }
488             errln(line);
489         }
490         if (U_FAILURE(status)) {
491             break;
492         }
493     }
494 }
495 
496 
testScriptSet()497 void IntlTestSpoof::testScriptSet() {
498     // ScriptSet::SCRIPT_LIMIT is hardcoded.
499     // Increase it by multiples of 32 if there are too many script codes.
500     TEST_ASSERT(USCRIPT_CODE_LIMIT <= ScriptSet::SCRIPT_LIMIT);
501     // USCRIPT_CODE_LIMIT should include all script codes,
502     // but theoretically the data may define more.
503     TEST_ASSERT(u_getIntPropertyMaxValue(UCHAR_SCRIPT) < ScriptSet::SCRIPT_LIMIT);
504 
505     ScriptSet s1;
506     ScriptSet s2;
507     UErrorCode status = U_ZERO_ERROR;
508 
509     TEST_ASSERT(s1 == s2);
510     s1.set(USCRIPT_ARABIC,status);
511     TEST_ASSERT_SUCCESS(status);
512     TEST_ASSERT(!(s1 == s2));
513     TEST_ASSERT(s1.test(USCRIPT_ARABIC, status));
514     TEST_ASSERT(s1.test(USCRIPT_GREEK, status) == false);
515 
516     status = U_ZERO_ERROR;
517     s1.reset(USCRIPT_ARABIC, status);
518     TEST_ASSERT(s1 == s2);
519 
520     static constexpr UScriptCode LAST_SCRIPT_CODE = static_cast<UScriptCode>(USCRIPT_CODE_LIMIT - 1);
521     status = U_ZERO_ERROR;
522     s1.setAll();
523     TEST_ASSERT(s1.test(USCRIPT_COMMON, status));
524     TEST_ASSERT(s1.test(USCRIPT_ETHIOPIC, status));
525     TEST_ASSERT(s1.test(LAST_SCRIPT_CODE, status));
526     s1.resetAll();
527     TEST_ASSERT(!s1.test(USCRIPT_COMMON, status));
528     TEST_ASSERT(!s1.test(USCRIPT_ETHIOPIC, status));
529     TEST_ASSERT(!s1.test(LAST_SCRIPT_CODE, status));
530 
531     status = U_ZERO_ERROR;
532     s1.set(USCRIPT_TAKRI, status);
533     s1.set(USCRIPT_BLISSYMBOLS, status);
534     s2.setAll();
535     TEST_ASSERT(s2.contains(s1));
536     TEST_ASSERT(!s1.contains(s2));
537     TEST_ASSERT(s2.intersects(s1));
538     TEST_ASSERT(s1.intersects(s2));
539     s2.reset(USCRIPT_TAKRI, status);
540     TEST_ASSERT(!s2.contains(s1));
541     TEST_ASSERT(!s1.contains(s2));
542     TEST_ASSERT(s1.intersects(s2));
543     TEST_ASSERT(s2.intersects(s1));
544     TEST_ASSERT_SUCCESS(status);
545 
546     status = U_ZERO_ERROR;
547     s1.resetAll();
548     s1.set(USCRIPT_NKO, status);
549     s1.set(USCRIPT_COMMON, status);
550     s2 = s1;
551     TEST_ASSERT(s2 == s1);
552     TEST_ASSERT_EQ(2, s2.countMembers());
553     s2.intersect(s1);
554     TEST_ASSERT(s2 == s1);
555     s2.setAll();
556     TEST_ASSERT(!(s2 == s1));
557     TEST_ASSERT(s2.countMembers() >= USCRIPT_CODE_LIMIT);
558     s2.intersect(s1);
559     TEST_ASSERT(s2 == s1);
560 
561     s2.setAll();
562     s2.reset(USCRIPT_COMMON, status);
563     s2.intersect(s1);
564     TEST_ASSERT(s2.countMembers() == 1);
565 
566     s1.resetAll();
567     TEST_ASSERT(s1.isEmpty());
568     s1.set(USCRIPT_LATIN, status);
569     TEST_ASSERT(!s1.isEmpty());
570     s1.setAll();
571     TEST_ASSERT(!s1.isEmpty());
572     TEST_ASSERT_SUCCESS(status);
573 
574     s1.resetAll();
575     s1.set(USCRIPT_AFAKA, status);
576     s1.set(USCRIPT_VAI, status);
577     s1.set(USCRIPT_INHERITED, status);
578     int32_t n = -1;
579     for (int32_t i=0; i<4; i++) {
580         n = s1.nextSetBit(n+1);
581         switch (i) {
582           case 0: TEST_ASSERT_EQ(USCRIPT_INHERITED, n); break;
583           case 1: TEST_ASSERT_EQ(USCRIPT_VAI, n); break;
584           case 2: TEST_ASSERT_EQ(USCRIPT_AFAKA, n); break;
585           case 3: TEST_ASSERT_EQ(-1, (int32_t)n); break;
586           default: TEST_ASSERT(false);
587         }
588     }
589     TEST_ASSERT_SUCCESS(status);
590 
591     // Script extensions.  Depends on data.
592     s1.resetAll();
593     s1.setScriptExtensions(0x67, status);
594     TEST_ASSERT(s1.countMembers() == 1);
595     TEST_ASSERT(s1.test(USCRIPT_LATIN, status));
596     TEST_ASSERT_SUCCESS(status);
597 
598     s1.resetAll();
599     s1.setScriptExtensions(0x303C, status);
600     TEST_ASSERT(s1.countMembers() == 3);
601     TEST_ASSERT(s1.test(USCRIPT_HAN, status));
602     TEST_ASSERT(s1.test(USCRIPT_HIRAGANA, status));
603     TEST_ASSERT(s1.test(USCRIPT_KATAKANA, status));
604     TEST_ASSERT_SUCCESS(status);
605 
606     // Additional tests
607     ScriptSet bitset12; bitset12.set(USCRIPT_LATIN, status).set(USCRIPT_HANGUL, status);
608     ScriptSet bitset2;  bitset2.set(USCRIPT_HANGUL, status);
609     TEST_ASSERT(bitset12.contains(bitset2));
610     TEST_ASSERT(bitset12.contains(bitset12));
611     TEST_ASSERT(!bitset2.contains(bitset12));
612 
613     ScriptSet arabSet;  arabSet.set(USCRIPT_ARABIC, status);
614     ScriptSet latinSet; latinSet.set(USCRIPT_LATIN, status);
615     UElement arabEl;  arabEl.pointer = &arabSet;
616     UElement latinEl; latinEl.pointer = &latinSet;
617     TEST_ASSERT(uhash_compareScriptSet(arabEl, latinEl) < 0);
618     TEST_ASSERT(uhash_compareScriptSet(latinEl, arabEl) > 0);
619 
620     UnicodeString scriptString;
621     bitset12.displayScripts(scriptString);
622     TEST_ASSERT(UNICODE_STRING_SIMPLE("Hang Latn") == scriptString);
623 }
624 
625 
testRestrictionLevel()626 void IntlTestSpoof::testRestrictionLevel() {
627     struct Test {
628         const char         *fId;
629         URestrictionLevel   fExpectedRestrictionLevel;
630     } tests[] = {
631         {"\\u0061\\u03B3\\u2665", USPOOF_UNRESTRICTIVE},
632         {"a",                     USPOOF_ASCII},
633         {"\\u03B3",               USPOOF_SINGLE_SCRIPT_RESTRICTIVE},
634         {"\\u0061\\u30A2\\u30FC", USPOOF_HIGHLY_RESTRICTIVE},
635         {"\\u0061\\u0904",        USPOOF_MODERATELY_RESTRICTIVE},
636         {"\\u0061\\u03B3",        USPOOF_MINIMALLY_RESTRICTIVE},
637         {"\\u0061\\u2665",                USPOOF_UNRESTRICTIVE},
638         {"\\u0061\\u303C",                USPOOF_HIGHLY_RESTRICTIVE},
639         {"\\u0061\\u30FC\\u303C",         USPOOF_HIGHLY_RESTRICTIVE},
640         {"\\u0061\\u30FC\\u303C\\u30A2",  USPOOF_HIGHLY_RESTRICTIVE},
641         {"\\u30A2\\u0061\\u30FC\\u303C",  USPOOF_HIGHLY_RESTRICTIVE},
642         {"\\u0061\\u0031\\u0661",         USPOOF_MODERATELY_RESTRICTIVE},
643         {"\\u0061\\u0031\\u0661\\u06F1",  USPOOF_MODERATELY_RESTRICTIVE},
644         {"\\u0661\\u30FC\\u303C\\u0061\\u30A2\\u0031\\u0967\\u06F1",  USPOOF_MINIMALLY_RESTRICTIVE},
645         {"\\u0061\\u30A2\\u30FC\\u303C\\u0031\\u0967\\u0661\\u06F1",  USPOOF_MINIMALLY_RESTRICTIVE}
646     };
647     char msgBuffer[100];
648     URestrictionLevel restrictionLevels[] = { USPOOF_ASCII, USPOOF_SINGLE_SCRIPT_RESTRICTIVE,
649         USPOOF_HIGHLY_RESTRICTIVE, USPOOF_MODERATELY_RESTRICTIVE, USPOOF_MINIMALLY_RESTRICTIVE,
650         USPOOF_UNRESTRICTIVE};
651 
652     UErrorCode status = U_ZERO_ERROR;
653     UnicodeSet allowedChars;
654     // Allowed Identifier Characters. In addition to the Recommended Set,
655     //    allow u303c, which has an interesting script extension of Hani Hira Kana.
656     allowedChars.addAll(*uspoof_getRecommendedUnicodeSet(&status)).add(0x303C);
657 
658     for (int32_t testNum=0; testNum < UPRV_LENGTHOF(tests); testNum++) {
659         status = U_ZERO_ERROR;
660         const Test &test = tests[testNum];
661         UnicodeString testString = UnicodeString(test.fId).unescape();
662         URestrictionLevel expectedLevel = test.fExpectedRestrictionLevel;
663         for (int levelIndex=0; levelIndex<UPRV_LENGTHOF(restrictionLevels); levelIndex++) {
664             status = U_ZERO_ERROR;
665             URestrictionLevel levelSetInSpoofChecker = restrictionLevels[levelIndex];
666             USpoofChecker *sc = uspoof_open(&status);
667             uspoof_setAllowedChars(sc, allowedChars.toUSet(), &status);
668             uspoof_setRestrictionLevel(sc, levelSetInSpoofChecker);
669             uspoof_setChecks(sc, USPOOF_RESTRICTION_LEVEL, &status);
670             int32_t actualValue = uspoof_checkUnicodeString(sc, testString, nullptr, &status);
671 
672             // we want to fail if the text is (say) MODERATE and the testLevel is ASCII
673             int32_t expectedValue = 0;
674             if (expectedLevel > levelSetInSpoofChecker) {
675                 expectedValue |= USPOOF_RESTRICTION_LEVEL;
676             }
677             snprintf(msgBuffer, sizeof(msgBuffer), "testNum = %d, levelIndex = %d, expected = %#x, actual = %#x",
678                     testNum, levelIndex, expectedValue, actualValue);
679             TEST_ASSERT_MSG(expectedValue == actualValue, msgBuffer);
680             TEST_ASSERT_SUCCESS(status);
681 
682             // Run the same check again, with the Spoof Checker configured to return
683             // the actual restriction level.
684             uspoof_setAllowedChars(sc, allowedChars.toUSet(), &status);
685             uspoof_setRestrictionLevel(sc, levelSetInSpoofChecker);
686             uspoof_setChecks(sc, USPOOF_AUX_INFO | USPOOF_RESTRICTION_LEVEL, &status);
687             int32_t result = uspoof_checkUnicodeString(sc, testString, nullptr, &status);
688             TEST_ASSERT_SUCCESS(status);
689             if (U_SUCCESS(status)) {
690                 TEST_ASSERT_EQ(expectedLevel, result & USPOOF_RESTRICTION_LEVEL_MASK);
691                 TEST_ASSERT_EQ(expectedValue, result & USPOOF_ALL_CHECKS);
692             }
693             uspoof_close(sc);
694         }
695     }
696 
697 }
698 
testMixedNumbers()699 void IntlTestSpoof::testMixedNumbers() {
700     struct Test {
701         const char *fTestString;
702         const char *fExpectedSet;
703     } tests[] = {
704         {"1",              "[0]"},
705         {"\\u0967",        "[\\u0966]"},
706         {"1\\u0967",       "[0\\u0966]"},
707         {"\\u0661\\u06F1", "[\\u0660\\u06F0]"},
708         {"\\u0061\\u2665", "[]"},
709         {"\\u0061\\u303C", "[]"},
710         {"\\u0061\\u30FC\\u303C", "[]"},
711         {"\\u0061\\u30FC\\u303C\\u30A2", "[]"},
712         {"\\u30A2\\u0061\\u30FC\\u303C", "[]"},
713         {"\\u0061\\u0031\\u0661", "[\\u0030\\u0660]"},
714         {"\\u0061\\u0031\\u0661\\u06F1", "[\\u0030\\u0660\\u06F0]"},
715         {"\\u0661\\u30FC\\u303C\\u0061\\u30A2\\u0031\\u0967\\u06F1", "[\\u0030\\u0660\\u06F0\\u0966]"},
716         {"\\u0061\\u30A2\\u30FC\\u303C\\u0031\\u0967\\u0661\\u06F1", "[\\u0030\\u0660\\u06F0\\u0966]"}
717     };
718     UErrorCode status = U_ZERO_ERROR;
719     for (int32_t testNum=0; testNum < UPRV_LENGTHOF(tests); testNum++) {
720         char msgBuf[100];
721         snprintf(msgBuf, sizeof(msgBuf), "testNum = %d ", testNum);
722         Test &test = tests[testNum];
723 
724         status = U_ZERO_ERROR;
725         UnicodeString testString = UnicodeString(test.fTestString).unescape();
726         UnicodeSet expectedSet(UnicodeString(test.fExpectedSet).unescape(), status);
727 
728         status = U_ZERO_ERROR;
729         TEST_SETUP
730             uspoof_setChecks(sc, USPOOF_MIXED_NUMBERS, &status); // only check this
731             uspoof_check2UnicodeString(sc, testString, checkResult, &status);
732             UBool mixedNumberFailure = ((uspoof_getCheckResultChecks(checkResult, &status) & USPOOF_MIXED_NUMBERS) != 0);
733             TEST_ASSERT_MSG((expectedSet.size() > 1) == mixedNumberFailure, msgBuf);
734             const UnicodeSet* actualSet = UnicodeSet::fromUSet(uspoof_getCheckResultNumerics(checkResult, &status));
735             TEST_ASSERT_MSG(expectedSet == *actualSet, msgBuf);
736         TEST_TEARDOWN;
737     }
738 }
739 
740 // Bug #12153 - uspoof_setRestrictionLevel() should enable restriction level testing.
741 //
testBug12153()742 void IntlTestSpoof::testBug12153() {
743     UErrorCode status = U_ZERO_ERROR;
744     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
745     if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; }
746     int32_t checks = uspoof_getChecks(sc.getAlias(), &status);
747     TEST_ASSERT((checks & USPOOF_RESTRICTION_LEVEL) != 0);
748     checks &= ~USPOOF_RESTRICTION_LEVEL;
749     uspoof_setChecks(sc.getAlias(), checks, &status);
750     checks = uspoof_getChecks(sc.getAlias(), &status);
751     TEST_ASSERT((checks & USPOOF_RESTRICTION_LEVEL) == 0);
752 
753     uspoof_setRestrictionLevel(sc.getAlias(), USPOOF_MODERATELY_RESTRICTIVE);
754     checks = uspoof_getChecks(sc.getAlias(), &status);
755     TEST_ASSERT((checks & USPOOF_RESTRICTION_LEVEL) != 0);
756     TEST_ASSERT_SUCCESS(status);
757 }
758 
759 // uspoof_checkUnicodeString should NOT have an infinite loop.
testBug12825()760 void IntlTestSpoof::testBug12825() {
761     UErrorCode status = U_ZERO_ERROR;
762     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
763     TEST_ASSERT_SUCCESS(status);
764     uspoof_setChecks(sc.getAlias(), USPOOF_ALL_CHECKS | USPOOF_AUX_INFO, &status);
765     TEST_ASSERT_SUCCESS(status);
766     uspoof_checkUnicodeString(sc.getAlias(), UnicodeString("\\u30FB").unescape(), nullptr, &status);
767     TEST_ASSERT_SUCCESS(status);
768 }
769 
770 // uspoof_getSkeleton should NOT set an ILLEGAL_ARGUMENT_EXCEPTION.
testBug12815()771 void IntlTestSpoof::testBug12815() {
772     UErrorCode status = U_ZERO_ERROR;
773     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
774     TEST_ASSERT_SUCCESS(status);
775     uspoof_setChecks(sc.getAlias(), USPOOF_RESTRICTION_LEVEL, &status);
776     TEST_ASSERT_SUCCESS(status);
777     UnicodeString result;
778     uspoof_getSkeletonUnicodeString(sc.getAlias(), 0, UnicodeString("hello world"), result, &status);
779     TEST_ASSERT_SUCCESS(status);
780 }
781 
testBug13314_MixedNumbers()782 void IntlTestSpoof::testBug13314_MixedNumbers() {
783     UErrorCode status = U_ZERO_ERROR;
784     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
785     if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; }
786     uspoof_setChecks(sc.getAlias(), USPOOF_ALL_CHECKS, &status);
787     TEST_ASSERT_SUCCESS(status);
788     int32_t failedChecks = uspoof_areConfusableUnicodeString(sc.getAlias(), u"列", u"列", &status);
789     TEST_ASSERT_SUCCESS(status);
790     assertEquals("The CJK strings should be confusable", USPOOF_SINGLE_SCRIPT_CONFUSABLE, failedChecks);
791     failedChecks = uspoof_check2UnicodeString(sc.getAlias(), u"3Ȝ", nullptr, &status);
792     TEST_ASSERT_SUCCESS(status);
793     assertEquals("The '33' string does not fail spoof", 0, failedChecks);
794 }
795 
testBug13328_MixedCombiningMarks()796 void IntlTestSpoof::testBug13328_MixedCombiningMarks() {
797     UErrorCode status = U_ZERO_ERROR;
798     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
799     if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; }
800     int32_t failedChecks = uspoof_check2UnicodeString(sc.getAlias(), u"\u0061\u0F84", nullptr, &status);
801     TEST_ASSERT_SUCCESS(status);
802     assertEquals(
803             "The mismatched combining marks string fails spoof",
804             USPOOF_RESTRICTION_LEVEL,
805             failedChecks);
806 }
807 
testCombiningDot()808 void IntlTestSpoof::testCombiningDot() {
809     UErrorCode status = U_ZERO_ERROR;
810     LocalUSpoofCheckerPointer sc(uspoof_open(&status));
811     if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; }
812     uspoof_setChecks(sc.getAlias(), USPOOF_HIDDEN_OVERLAY, &status);
813     TEST_ASSERT_SUCCESS(status);
814 
815     static const struct TestCase {
816         bool shouldFail;
817         const char16_t* input;
818     } cases[] = {
819             {false, u"i"},
820             {false, u"j"},
821             {false, u"l"},
822             {true, u"i\u0307"},
823             {true, u"j\u0307"},
824             {true, u"l\u0307"},
825             {true, u"ı\u0307"},
826             {true, u"ȷ\u0307"},
827             {true, u"��\u0307"},
828             {true, u"��\u0307"},
829             {false, u"m\u0307"},
830             {true, u"1\u0307"},
831             {true, u"ij\u0307"},
832             {true, u"i\u0307\u0307"},
833             {true, u"abci\u0307def"},
834             {false, u"i\u0301\u0307"}, // U+0301 has combining class ABOVE (230)
835             {true, u"i\u0320\u0307"}, // U+0320 has combining class BELOW
836             {true, u"i\u0320\u0321\u0307"}, // U+0321 also has combining class BELOW
837             {false, u"i\u0320\u0301\u0307"},
838             {false, u"iz\u0307"},
839     };
840 
841     for (const auto& cas : cases) {
842         int32_t failedChecks = uspoof_check2(sc.getAlias(), cas.input, -1, nullptr, &status);
843         TEST_ASSERT_SUCCESS(status);
844         int32_t expected = cas.shouldFail ? USPOOF_HIDDEN_OVERLAY : 0;
845         assertEquals(cas.input, expected, failedChecks);
846     }
847 }
848 
849 #endif /* !UCONFIG_NO_REGULAR_EXPRESSIONS && !UCONFIG_NO_NORMALIZATION && !UCONFIG_NO_FILE_IO */
850