checked in very nice ICU normalization examples
[pazpar2-moved-to-github.git] / src / test_icu_I18N.c
1 /* $Id: test_icu_I18N.c,v 1.17 2007-05-11 22:23:33 marc Exp $
2    Copyright (c) 2006-2007, Index Data.
3
4    This file is part of Pazpar2.
5
6    Pazpar2 is free software; you can redistribute it and/or modify it under
7    the terms of the GNU General Public License as published by the Free
8    Software Foundation; either version 2, or (at your option) any later
9    version.
10
11    Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
12    WARRANTY; without even the implied warranty of MERCHANTABILITY or
13    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14    for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with Pazpar2; see the file LICENSE.  If not, write to the
18    Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
19    02111-1307, USA.
20 */
21
22 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
23  
24
25 #if HAVE_CONFIG_H
26 #include "cconfig.h"
27 #endif
28
29 #define USE_TIMING 0
30 #if USE_TIMING
31 #include <yaz/timing.h>
32 #endif
33
34 #include <yaz/test.h>
35
36
37
38 #ifdef HAVE_ICU
39 #include "icu_I18N.h"
40
41 #include <string.h>
42 #include <stdlib.h>
43
44 //#include <unicode/ustring.h>  
45 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
46
47
48 #define MAX_KEY_SIZE 256
49 struct icu_termmap
50 {
51     uint8_t sort_key[MAX_KEY_SIZE]; // standard C string '\0' terminated
52     char disp_term[MAX_KEY_SIZE];  // standard C utf-8 string
53 };
54
55
56
57 int icu_termmap_cmp(const void *vp1, const void *vp2)
58 {
59     struct icu_termmap *itmp1 = *(struct icu_termmap **) vp1;
60     struct icu_termmap *itmp2 = *(struct icu_termmap **) vp2;
61
62     int cmp = 0;
63     
64     cmp = strcmp((const char *)itmp1->sort_key, 
65                  (const char *)itmp2->sort_key);
66     return cmp;
67 };
68
69
70
71
72 int test_icu_casemap(const char * locale, char action,
73                      const char * src8cstr, const char * chk8cstr)
74 {
75     int success = 0;
76     UErrorCode status = U_ZERO_ERROR;
77
78     struct icu_buf_utf8 * src8 = icu_buf_utf8_create(0);
79     struct icu_buf_utf8 * dest8 = icu_buf_utf8_create(0);
80     struct icu_buf_utf16 * src16 = icu_buf_utf16_create(0);
81     struct icu_buf_utf16 * dest16 = icu_buf_utf16_create(0);
82
83
84     int src8cstr_len = strlen(src8cstr);
85     int chk8cstr_len = strlen(chk8cstr);
86
87     // converting to UTF16
88     icu_utf16_from_utf8_cstr(src16, src8cstr, &status);
89
90     // perform case mapping
91     icu_utf16_casemap(dest16, src16, locale, action, &status);
92   
93     // converting to UTF8
94     icu_utf16_to_utf8(dest8, dest16, &status);
95       
96
97   
98     // determine success
99     if (dest8->utf8 
100         && (dest8->utf8_len == strlen(chk8cstr))
101         && !strcmp(chk8cstr, (const char *) dest8->utf8))
102         success = 1;
103     else
104         success = 0;
105
106     // report failures
107     if (!success){
108         printf("\nERROR\n");
109         printf("original string:   '%s' (%d)\n", src8cstr, src8cstr_len);
110         printf("icu_casemap '%s:%c' '%s' (%d)\n", 
111                locale, action, dest8->utf8, dest8->utf8_len);
112         printf("expected string:   '%s' (%d)\n", chk8cstr, chk8cstr_len);
113     }
114   
115     // clean the buffers  
116     icu_buf_utf8_destroy(src8);
117     icu_buf_utf8_destroy(dest8);
118     icu_buf_utf16_destroy(src16);
119     icu_buf_utf16_destroy(dest16);
120   
121   
122     return success;
123 }
124
125
126
127 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
128
129 void test_icu_I18N_casemap(int argc, char **argv)
130 {
131
132     // Locale 'en'
133
134     // sucessful tests
135     YAZ_CHECK(test_icu_casemap("en", 'l',
136                                "A ReD fOx hunTS sQUirriLs", 
137                                "a red fox hunts squirrils"));
138     
139     YAZ_CHECK(test_icu_casemap("en", 'u',
140                                "A ReD fOx hunTS sQUirriLs", 
141                                "A RED FOX HUNTS SQUIRRILS"));
142     
143     YAZ_CHECK(test_icu_casemap("en", 'f',
144                                "A ReD fOx hunTS sQUirriLs", 
145                                "a red fox hunts squirrils"));
146     
147     YAZ_CHECK(test_icu_casemap("en", 't',
148                                "A ReD fOx hunTS sQUirriLs", 
149                                "A Red Fox Hunts Squirrils"));
150     
151
152     // Locale 'da'
153
154     // sucess expected    
155     YAZ_CHECK(test_icu_casemap("da", 'l',
156                                "åh ÆbLE, øs fLØde i Åen efter bLåBærGRødeN", 
157                                "åh æble, øs fløde i åen efter blåbærgrøden"));
158
159     YAZ_CHECK(test_icu_casemap("da", 'u',
160                                "åh ÆbLE, øs fLØde i Åen efter bLåBærGRødeN", 
161                                "ÅH ÆBLE, ØS FLØDE I ÅEN EFTER BLÅBÆRGRØDEN"));
162
163     YAZ_CHECK(test_icu_casemap("da", 'f',
164                                "åh ÆbLE, øs fLØde i Åen efter bLåBærGRødeN", 
165                                "åh æble, øs fløde i åen efter blåbærgrøden"));
166
167     YAZ_CHECK(test_icu_casemap("da", 't',
168                                "åh ÆbLE, øs fLØde i Åen efter bLåBærGRødeN", 
169                                "Åh Æble, Øs Fløde I Åen Efter Blåbærgrøden"));
170
171     // Locale 'de'
172
173     // sucess expected    
174     YAZ_CHECK(test_icu_casemap("de", 'l',
175                                "zWÖlf ärgerliche Würste rollen ÜBer die StRAße",
176                                "zwölf ärgerliche würste rollen über die straße"));
177
178     YAZ_CHECK(test_icu_casemap("de", 'u',
179                                "zWÖlf ärgerliche Würste rollen ÜBer die StRAße",
180                                "ZWÖLF ÄRGERLICHE WÜRSTE ROLLEN ÜBER DIE STRASSE"));
181
182     YAZ_CHECK(test_icu_casemap("de", 'f',
183                                "zWÖlf ärgerliche Würste rollen ÜBer die StRAße",
184                                "zwölf ärgerliche würste rollen über die strasse"));
185
186     YAZ_CHECK(test_icu_casemap("de", 't',
187                                "zWÖlf ärgerliche Würste rollen ÜBer die StRAße",
188                                "Zwölf Ärgerliche Würste Rollen Über Die Straße"));
189
190 }
191
192
193 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
194
195 int test_icu_sortmap(const char * locale, int src_list_len,
196                      const char ** src_list, const char ** chk_list)
197 {
198     int success = 1;
199
200     UErrorCode status = U_ZERO_ERROR;
201
202     struct icu_buf_utf8 * buf8 = icu_buf_utf8_create(0);
203     struct icu_buf_utf16 * buf16 = icu_buf_utf16_create(0);
204
205     int i;
206
207     struct icu_termmap * list[src_list_len];
208
209     UCollator *coll = ucol_open(locale, &status); 
210     icu_check_status(status);
211
212     if(U_FAILURE(status))
213         return 0;
214
215     // assigning display terms and sort keys using buf 8 and buf16
216     for( i = 0; i < src_list_len; i++) 
217         {
218
219             list[i] = (struct icu_termmap *) malloc(sizeof(struct icu_termmap));
220
221             // copy display term
222             strcpy(list[i]->disp_term, src_list[i]);    
223
224             // transforming to UTF16
225             icu_utf16_from_utf8_cstr(buf16, list[i]->disp_term, &status);
226             icu_check_status(status);
227
228             // computing sortkeys
229             icu_sortkey8_from_utf16(coll, buf8, buf16, &status);
230             icu_check_status(status);
231     
232             // assigning sortkeys
233             memcpy(list[i]->sort_key, buf8->utf8, buf8->utf8_len);    
234             //strncpy(list[i]->sort_key, buf8->utf8, buf8->utf8_len);    
235             //strcpy((char *) list[i]->sort_key, (const char *) buf8->utf8);
236         } 
237
238
239     // do the sorting
240     qsort(list, src_list_len, 
241           sizeof(struct icu_termmap *), icu_termmap_cmp);
242
243     // checking correct sorting
244     for (i = 0; i < src_list_len; i++){
245         if (0 != strcmp(list[i]->disp_term, chk_list[i])){
246             success = 0;
247         }
248     }
249
250     if(!success){
251         printf("\nERROR\n"); 
252         printf("Input str: '%s' : ", locale); 
253         for (i = 0; i < src_list_len; i++) {
254             printf(" '%s'", list[i]->disp_term); 
255         }
256         printf("\n");
257         printf("ICU sort:  '%s' : ", locale); 
258         for (i = 0; i < src_list_len; i++) {
259             printf(" '%s'", list[i]->disp_term); 
260             //printf("(%d|%d)", list[i]->sort_key[0],list[i]->sort_key[1]); 
261         }
262         printf("\n"); 
263         printf("Expected:  '%s' : ", locale); 
264         for (i = 0; i < src_list_len; i++) {
265             printf(" '%s'", chk_list[i]); 
266         }
267         printf("\n"); 
268     }
269   
270   
271     ucol_close(coll);
272
273     icu_buf_utf8_destroy(buf8);
274     icu_buf_utf16_destroy(buf16);
275
276
277
278     return success;  
279 }
280
281
282 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
283
284 void test_icu_I18N_sortmap(int argc, char **argv)
285 {
286
287     // sucessful tests
288     size_t en_1_len = 6;
289     const char * en_1_src[6] = {"z", "K", "a", "A", "Z", "k"};
290     const char * en_1_cck[6] = {"a", "A", "k", "K", "z", "Z"};
291     YAZ_CHECK(test_icu_sortmap("en", en_1_len, en_1_src, en_1_cck));
292     YAZ_CHECK(test_icu_sortmap("en_AU", en_1_len, en_1_src, en_1_cck));
293     YAZ_CHECK(test_icu_sortmap("en_CA", en_1_len, en_1_src, en_1_cck));
294     YAZ_CHECK(test_icu_sortmap("en_GB", en_1_len, en_1_src, en_1_cck));
295     YAZ_CHECK(test_icu_sortmap("en_US", en_1_len, en_1_src, en_1_cck));
296     
297     // sucessful tests 
298     size_t da_1_len = 6;
299     const char * da_1_src[6] = {"z", "å", "o", "æ", "a", "ø"};
300     const char * da_1_cck[6] = {"a", "o", "z", "æ", "ø", "å"};
301     YAZ_CHECK(test_icu_sortmap("da", da_1_len, da_1_src, da_1_cck));
302     YAZ_CHECK(test_icu_sortmap("da_DK", da_1_len, da_1_src, da_1_cck));
303     
304     // sucessful tests
305     size_t de_1_len = 9;
306     const char * de_1_src[9] = {"u", "ä", "o", "t", "s", "ß", "ü", "ö", "a"};
307     const char * de_1_cck[9] = {"a","ä", "o", "ö", "s", "ß", "t", "u", "ü"};
308     YAZ_CHECK(test_icu_sortmap("de", de_1_len, de_1_src, de_1_cck));
309     YAZ_CHECK(test_icu_sortmap("de_AT", de_1_len, de_1_src, de_1_cck));
310     YAZ_CHECK(test_icu_sortmap("de_DE", de_1_len, de_1_src, de_1_cck));
311     
312 }
313
314
315 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
316
317 int test_icu_transliterator(const char * rules8cstr,
318                             const char * src8cstr,
319                             const char * chk8cstr)
320 {
321     int success = 0;
322     
323     UErrorCode status = U_ZERO_ERROR;
324     UParseError parse_error[256];
325
326
327     struct icu_buf_utf16 * rules16 = icu_buf_utf16_create(0);
328     struct icu_buf_utf16 * src16 = icu_buf_utf16_create(0);
329     struct icu_buf_utf16 * dest16 = icu_buf_utf16_create(0);
330     struct icu_buf_utf8 * dest8 = icu_buf_utf8_create(0);
331
332     icu_utf16_from_utf8_cstr(rules16, rules8cstr, &status);
333     icu_check_status(status);
334
335     icu_utf16_from_utf8_cstr(src16, src8cstr, &status);
336     icu_check_status(status);
337
338     UTransliterator * trans
339         = utrans_openU(rules16->utf16, rules16->utf16_len,
340                        UTRANS_FORWARD,
341                        0, 0, 
342                        parse_error, &status);
343
344     //= utrans_openU(0, 0, UTRANS_FORWARD,
345     //                   rules16->utf16, rules16->utf16_len, 
346     //                   parse_error, &status);
347
348     icu_check_status(status);
349     if(U_FAILURE(status)) {
350       printf("Parse Error: \n line %d offset %d \n '%s'\n", 
351               parse_error->line, parse_error->offset,
352              rules8cstr);
353     }
354
355     utrans_transUChars (trans, src16->utf16, &(src16->utf16_len),
356                         src16->utf16_cap,
357                         0, &(src16->utf16_len), &status);
358
359     icu_utf16_to_utf8(dest8, src16, &status);
360     icu_check_status(status);
361
362
363     if(!strcmp((const char *) dest8->utf8, 
364                (const char *) chk8cstr))
365         success = 1;
366     else {
367         success = 0;
368         printf("Normaliozation;");
369         printf("Rules:      '%s'\n", rules8cstr);
370         printf("Input:      '%s'\n", src8cstr);
371         printf("Normalized: '%s'\n", dest8->utf8);
372         printf("Expected:   '%s'\n", chk8cstr);
373     }
374     
375
376     utrans_close (trans);
377     icu_buf_utf16_destroy(rules16);
378     icu_buf_utf16_destroy(src16);
379     icu_buf_utf16_destroy(dest16);
380     icu_buf_utf8_destroy(dest8);
381
382     return success;
383 }
384
385 #if 0
386     printf("\n\nUnicode Set Patterns:\n"
387              "   Pattern         Description\n"
388              "   Ranges          [a-z]  The lower case letters a through z\n"
389              "   Named Chars     [abc123] The six characters a,b,c,1,2 and 3\n"
390              "   String          [abc{def}] chars a, b and c, and string 'def'\n"
391              "   Categories      [\\p{Letter}] Perl General Category 'Letter'.\n"
392              "   Categories      [:Letter:] Posix General Category 'Letter'.\n"
393              "\n"
394              "   Combination     Example\n"
395              "   Union           [[:Greek:] [:letter:]]\n"
396              "   Intersection    [[:Greek:] & [:letter:]]\n"
397              "   Set Complement  [[:Greek:] - [:letter:]]\n"
398              "   Complement      [^[:Greek:] [:letter:]]\n"
399              "\n"
400              "see: http://icu.sourceforge.net/userguide/unicodeSet.html\n"
401              "\n"
402              "Examples:\n"
403              "   [:Punctuation:] Any-Remove\n"
404              "   [:Cased-Letter:] Any-Upper\n"
405              "   [:Control:] Any-Remove\n"
406              "   [:Decimal_Number:] Any-Remove\n"
407              "   [:Final_Punctuation:] Any-Remove\n"
408              "   [:Georgian:] Any-Upper\n"
409              "   [:Katakana:] Any-Remove\n"
410              "   [:Arabic:] Any-Remove\n"
411              "   [:Punctuation:] Remove\n"
412              "   [[:Punctuation:]-[.,]] Remove\n"
413              "   [:Line_Separator:] Any-Remove\n"
414              "   [:Math_Symbol:] Any-Remove\n"
415              "   Lower; [:^Letter:] Remove (word tokenization)\n"
416              "   [:^Number:] Remove (numeric tokenization)\n"
417              "   [:^Katagana:] Remove (remove everything except Katagana)\n"
418              "   Lower;[[:WhiteSpace:][:Punctuation:]] Remove (word tokenization)\n"
419              "   NFD; [:Nonspacing Mark:] Remove; NFC   (removes accents from characters)\n"
420              "   [A-Za-z]; Lower(); Latin-Katakana; Katakana-Hiragana (transforms latin and katagana to hiragana)\n"
421              "   [[:separator:][:start punctuation:][:initial punctuation:]] Remove \n"
422              "\n"
423              "see http://icu.sourceforge.net/userguide/Transform.html\n"
424              "    http://www.unicode.org/Public/UNIDATA/UCD.html\n"
425              "    http://icu.sourceforge.net/userguide/Transform.html\n"
426              "    http://icu.sourceforge.net/userguide/TransformRule.html\n"
427              );
428 #endif
429
430
431 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
432
433 void test_icu_I18N_transliterator(int argc, char **argv)
434 {
435
436     YAZ_CHECK(test_icu_transliterator("[:Punctuation:] Any-Remove",
437                                       "Don't shoot!",
438                                       "Dont shoot"));
439     
440     YAZ_CHECK(test_icu_transliterator("[:Control:] Any-Remove",
441                                       "Don't\n shoot!",
442                                       "Don't shoot!"));
443
444     YAZ_CHECK(test_icu_transliterator("[:Decimal_Number:] Any-Remove",
445                                       "This is 4 you!",
446                                       "This is  you!"));
447
448     YAZ_CHECK(test_icu_transliterator("Lower; [:^Letter:] Remove",
449                                       "Don't shoot!",
450                                       "dontshoot"));
451     
452     YAZ_CHECK(test_icu_transliterator("[:^Number:] Remove",
453                                       "Monday 15th of April",
454                                       "15"));
455
456     YAZ_CHECK(test_icu_transliterator("Lower;"
457                                       "[[:WhiteSpace:][:Punctuation:]] Remove",
458                                       " word4you? ",
459                                       "word4you"));
460
461
462     YAZ_CHECK(test_icu_transliterator("NFD; [:Nonspacing Mark:] Remove; NFC",
463                                       "à côté de l'alcôve ovoïde",
464                                       "a cote de l'alcove ovoide"));
465
466 }
467
468
469 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
470
471 int test_icu_tokenizer(const char * locale, char action,
472                      const char * src8cstr, int count)
473 {
474     int success = 1;
475
476     UErrorCode status = U_ZERO_ERROR;
477     struct icu_buf_utf16 * src16 = icu_buf_utf16_create(0);
478     struct icu_buf_utf16 * tkn16 = icu_buf_utf16_create(0);
479     struct icu_buf_utf8 * tkn8 = icu_buf_utf8_create(0);
480
481     //printf("Input:  '%s'\n", src8cstr);
482
483     // transforming to UTF16
484     icu_utf16_from_utf8_cstr(src16, src8cstr, &status);
485     icu_check_status(status);
486
487     // set up tokenizer
488     struct icu_tokenizer * tokenizer 
489         = icu_tokenizer_create(locale, action, &status);
490     icu_check_status(status);
491     YAZ_CHECK(tokenizer);
492
493     // attach text buffer to tokenizer
494     icu_tokenizer_attach(tokenizer, src16, &status);    
495     icu_check_status(status);
496     YAZ_CHECK(tokenizer->bi);
497
498     // perform work on tokens
499     //printf("Tokens: ");
500     while(icu_tokenizer_next_token(tokenizer, tkn16, &status)){
501         icu_check_status(status);
502
503         // converting to UTF8
504         icu_utf16_to_utf8(tkn8, tkn16, &status);
505
506         //printf("(%d)'%s' ", icu_tokenizer_token_id(tokenizer), tkn8->utf8);
507         
508         //printf("token %d %d %d %d '%s'\n",
509         //       
510         //       icu_tokenizer_token_start(tokenizer),
511         //       icu_tokenizer_token_end(tokenizer),
512         //       icu_tokenizer_token_length(tokenizer),
513         //       tkn8->utf8);
514     }
515     //printf("\nTokens: %d\n", icu_tokenizer_token_count(tokenizer));
516
517
518     if (count != icu_tokenizer_token_count(tokenizer)){
519         success = 0;
520         printf("\nTokenizer '%s:%c' Error: \n", locale, action);
521         printf("Input:  '%s'\n", src8cstr);
522         printf("Tokens: %d", icu_tokenizer_token_count(tokenizer));
523         printf(", expected: %d\n", count);
524     }
525
526     icu_tokenizer_destroy(tokenizer);
527     icu_buf_utf16_destroy(src16);
528     icu_buf_utf16_destroy(tkn16);
529     icu_buf_utf8_destroy(tkn8);
530         
531     return success;
532 }
533
534
535 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
536
537 void test_icu_I18N_tokenizer(int argc, char **argv)
538 {
539
540
541     const char * en_str 
542         = "O Romeo, Romeo! wherefore art thou Romeo?";
543     
544     YAZ_CHECK(test_icu_tokenizer("en", 's', en_str, 2));
545     YAZ_CHECK(test_icu_tokenizer("en", 'l', en_str, 7));
546     YAZ_CHECK(test_icu_tokenizer("en", 'w', en_str, 16));
547     YAZ_CHECK(test_icu_tokenizer("en", 'c', en_str, 41));
548
549
550
551     const char * da_str 
552         = "Blåbærtærte. Denne kage stammer fra Finland. "
553         "Den er med blåbær, men alle sommerens forskellige bær kan bruges.";
554     
555     YAZ_CHECK(test_icu_tokenizer("da", 's', da_str, 3));
556     YAZ_CHECK(test_icu_tokenizer("dar", 'l', da_str, 17));
557     YAZ_CHECK(test_icu_tokenizer("da", 'w', da_str, 37));
558     YAZ_CHECK(test_icu_tokenizer("da", 'c', da_str, 110));
559
560 }
561
562
563
564
565
566 #endif // HAVE_ICU
567
568 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
569
570 int main(int argc, char **argv)
571 {
572
573     YAZ_CHECK_INIT(argc, argv); 
574     YAZ_CHECK_LOG();
575
576 #ifdef HAVE_ICU
577
578     //test_icu_I18N_casemap_failures(argc, argv);
579     test_icu_I18N_casemap(argc, argv);
580     test_icu_I18N_sortmap(argc, argv);
581     test_icu_I18N_transliterator(argc, argv);
582     test_icu_I18N_tokenizer(argc, argv);
583
584 #else // HAVE_ICU
585
586     printf("ICU unit tests omitted.\n"
587            "Please install libicu36-dev and icu-doc or similar\n");
588     YAZ_CHECK(0 == 0);
589
590 #endif // HAVE_ICU
591    
592     YAZ_CHECK_TERM;
593 }
594
595
596 // DO NOT EDIT THIS FILE IF YOUR EDITOR DOES NOT SUPPORT UTF-8
597
598
599
600 /*
601  * Local variables:
602  * c-basic-offset: 4
603  * indent-tabs-mode: nil
604  * End:
605  * vim: shiftwidth=4 tabstop=8 expandtab
606  */