]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
1. wxStopWatch tests in console
[wxWidgets.git] / samples / console / console.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 04.10.99
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 #include <stdio.h>
21
22 #include <wx/string.h>
23 #include <wx/file.h>
24 #include <wx/app.h>
25
26 // without this pragma, the stupid compiler precompiles #defines below so that
27 // changing them doesn't "take place" later!
28 #ifdef __VISUALC__
29 #pragma hdrstop
30 #endif
31
32 // ----------------------------------------------------------------------------
33 // conditional compilation
34 // ----------------------------------------------------------------------------
35
36 // what to test (in alphabetic order)?
37
38 //#define TEST_ARRAYS
39 //#define TEST_CMDLINE
40 //#define TEST_DATETIME
41 //#define TEST_DIR
42 //#define TEST_EXECUTE
43 //#define TEST_FILECONF
44 //#define TEST_HASH
45 //#define TEST_LOG
46 //#define TEST_LONGLONG
47 //#define TEST_MIME
48 //#define TEST_SOCKETS
49 //#define TEST_STRINGS
50 //#define TEST_THREADS
51 #define TEST_TIMER
52
53 // ============================================================================
54 // implementation
55 // ============================================================================
56
57 // ----------------------------------------------------------------------------
58 // wxCmdLineParser
59 // ----------------------------------------------------------------------------
60
61 #ifdef TEST_CMDLINE
62
63 #include <wx/cmdline.h>
64 #include <wx/datetime.h>
65
66 static void ShowCmdLine(const wxCmdLineParser& parser)
67 {
68 wxString s = "Input files: ";
69
70 size_t count = parser.GetParamCount();
71 for ( size_t param = 0; param < count; param++ )
72 {
73 s << parser.GetParam(param) << ' ';
74 }
75
76 s << '\n'
77 << "Verbose:\t" << (parser.Found("v") ? "yes" : "no") << '\n'
78 << "Quiet:\t" << (parser.Found("q") ? "yes" : "no") << '\n';
79
80 wxString strVal;
81 long lVal;
82 wxDateTime dt;
83 if ( parser.Found("o", &strVal) )
84 s << "Output file:\t" << strVal << '\n';
85 if ( parser.Found("i", &strVal) )
86 s << "Input dir:\t" << strVal << '\n';
87 if ( parser.Found("s", &lVal) )
88 s << "Size:\t" << lVal << '\n';
89 if ( parser.Found("d", &dt) )
90 s << "Date:\t" << dt.FormatISODate() << '\n';
91
92 wxLogMessage(s);
93 }
94
95 #endif // TEST_CMDLINE
96
97 // ----------------------------------------------------------------------------
98 // wxDir
99 // ----------------------------------------------------------------------------
100
101 #ifdef TEST_DIR
102
103 #include <wx/dir.h>
104
105 static void TestDirEnumHelper(wxDir& dir,
106 int flags = wxDIR_DEFAULT,
107 const wxString& filespec = wxEmptyString)
108 {
109 wxString filename;
110
111 if ( !dir.IsOpened() )
112 return;
113
114 bool cont = dir.GetFirst(&filename, filespec, flags);
115 while ( cont )
116 {
117 printf("\t%s\n", filename.c_str());
118
119 cont = dir.GetNext(&filename);
120 }
121
122 puts("");
123 }
124
125 static void TestDirEnum()
126 {
127 wxDir dir(wxGetCwd());
128
129 puts("Enumerating everything in current directory:");
130 TestDirEnumHelper(dir);
131
132 puts("Enumerating really everything in current directory:");
133 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
134
135 puts("Enumerating object files in current directory:");
136 TestDirEnumHelper(dir, wxDIR_DEFAULT, "*.o");
137
138 puts("Enumerating directories in current directory:");
139 TestDirEnumHelper(dir, wxDIR_DIRS);
140
141 puts("Enumerating files in current directory:");
142 TestDirEnumHelper(dir, wxDIR_FILES);
143
144 puts("Enumerating files including hidden in current directory:");
145 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
146
147 #ifdef __UNIX__
148 dir.Open("/");
149 #elif defined(__WXMSW__)
150 dir.Open("c:\\");
151 #else
152 #error "don't know where the root directory is"
153 #endif
154
155 puts("Enumerating everything in root directory:");
156 TestDirEnumHelper(dir, wxDIR_DEFAULT);
157
158 puts("Enumerating directories in root directory:");
159 TestDirEnumHelper(dir, wxDIR_DIRS);
160
161 puts("Enumerating files in root directory:");
162 TestDirEnumHelper(dir, wxDIR_FILES);
163
164 puts("Enumerating files including hidden in root directory:");
165 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
166
167 puts("Enumerating files in non existing directory:");
168 wxDir dirNo("nosuchdir");
169 TestDirEnumHelper(dirNo);
170 }
171
172 #endif // TEST_DIR
173
174 // ----------------------------------------------------------------------------
175 // wxExecute
176 // ----------------------------------------------------------------------------
177
178 #ifdef TEST_EXECUTE
179
180 #include <wx/utils.h>
181
182 static void TestExecute()
183 {
184 puts("*** testing wxExecute ***");
185
186 #ifdef __UNIX__
187 #define COMMAND "echo hi"
188 #define SHELL_COMMAND "echo hi from shell"
189 #define REDIRECT_COMMAND "date"
190 #elif defined(__WXMSW__)
191 #define COMMAND "command.com -c 'echo hi'"
192 #define SHELL_COMMAND "echo hi"
193 #define REDIRECT_COMMAND COMMAND
194 #else
195 #error "no command to exec"
196 #endif // OS
197
198 printf("Testing wxShell: ");
199 fflush(stdout);
200 if ( wxShell(SHELL_COMMAND) )
201 puts("Ok.");
202 else
203 puts("ERROR.");
204
205 printf("Testing wxExecute: ");
206 fflush(stdout);
207 if ( wxExecute(COMMAND, TRUE /* sync */) == 0 )
208 puts("Ok.");
209 else
210 puts("ERROR.");
211
212 #if 0 // no, it doesn't work (yet?)
213 printf("Testing async wxExecute: ");
214 fflush(stdout);
215 if ( wxExecute(COMMAND) != 0 )
216 puts("Ok (command launched).");
217 else
218 puts("ERROR.");
219 #endif // 0
220
221 printf("Testing wxExecute with redirection:\n");
222 wxArrayString output;
223 if ( wxExecute(REDIRECT_COMMAND, output) != 0 )
224 {
225 puts("ERROR.");
226 }
227 else
228 {
229 size_t count = output.GetCount();
230 for ( size_t n = 0; n < count; n++ )
231 {
232 printf("\t%s\n", output[n].c_str());
233 }
234
235 puts("Ok.");
236 }
237 }
238
239 #endif // TEST_EXECUTE
240
241 // ----------------------------------------------------------------------------
242 // wxFileConfig
243 // ----------------------------------------------------------------------------
244
245 #ifdef TEST_FILECONF
246
247 #include <wx/confbase.h>
248 #include <wx/fileconf.h>
249
250 static const struct FileConfTestData
251 {
252 const wxChar *name; // value name
253 const wxChar *value; // the value from the file
254 } fcTestData[] =
255 {
256 { _T("value1"), _T("one") },
257 { _T("value2"), _T("two") },
258 { _T("novalue"), _T("default") },
259 };
260
261 static void TestFileConfRead()
262 {
263 puts("*** testing wxFileConfig loading/reading ***");
264
265 wxFileConfig fileconf(_T("test"), wxEmptyString,
266 _T("testdata.fc"), wxEmptyString,
267 wxCONFIG_USE_RELATIVE_PATH);
268
269 // test simple reading
270 puts("\nReading config file:");
271 wxString defValue(_T("default")), value;
272 for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
273 {
274 const FileConfTestData& data = fcTestData[n];
275 value = fileconf.Read(data.name, defValue);
276 printf("\t%s = %s ", data.name, value.c_str());
277 if ( value == data.value )
278 {
279 puts("(ok)");
280 }
281 else
282 {
283 printf("(ERROR: should be %s)\n", data.value);
284 }
285 }
286
287 // test enumerating the entries
288 puts("\nEnumerating all root entries:");
289 long dummy;
290 wxString name;
291 bool cont = fileconf.GetFirstEntry(name, dummy);
292 while ( cont )
293 {
294 printf("\t%s = %s\n",
295 name.c_str(),
296 fileconf.Read(name.c_str(), _T("ERROR")).c_str());
297
298 cont = fileconf.GetNextEntry(name, dummy);
299 }
300 }
301
302 #endif // TEST_FILECONF
303
304 // ----------------------------------------------------------------------------
305 // wxHashTable
306 // ----------------------------------------------------------------------------
307
308 #ifdef TEST_HASH
309
310 #include <wx/hash.h>
311
312 struct Foo
313 {
314 Foo(int n_) { n = n_; count++; }
315 ~Foo() { count--; }
316
317 int n;
318
319 static size_t count;
320 };
321
322 size_t Foo::count = 0;
323
324 WX_DECLARE_LIST(Foo, wxListFoos);
325 WX_DECLARE_HASH(Foo, wxListFoos, wxHashFoos);
326
327 #include <wx/listimpl.cpp>
328
329 WX_DEFINE_LIST(wxListFoos);
330
331 static void TestHash()
332 {
333 puts("*** Testing wxHashTable ***\n");
334
335 {
336 wxHashFoos hash;
337 hash.DeleteContents(TRUE);
338
339 printf("Hash created: %u foos in hash, %u foos totally\n",
340 hash.GetCount(), Foo::count);
341
342 static const int hashTestData[] =
343 {
344 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
345 };
346
347 size_t n;
348 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
349 {
350 hash.Put(hashTestData[n], n, new Foo(n));
351 }
352
353 printf("Hash filled: %u foos in hash, %u foos totally\n",
354 hash.GetCount(), Foo::count);
355
356 puts("Hash access test:");
357 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
358 {
359 printf("\tGetting element with key %d, value %d: ",
360 hashTestData[n], n);
361 Foo *foo = hash.Get(hashTestData[n], n);
362 if ( !foo )
363 {
364 printf("ERROR, not found.\n");
365 }
366 else
367 {
368 printf("%d (%s)\n", foo->n,
369 (size_t)foo->n == n ? "ok" : "ERROR");
370 }
371 }
372
373 printf("\nTrying to get an element not in hash: ");
374
375 if ( hash.Get(1234) || hash.Get(1, 0) )
376 {
377 puts("ERROR: found!");
378 }
379 else
380 {
381 puts("ok (not found)");
382 }
383 }
384
385 printf("Hash destroyed: %u foos left\n", Foo::count);
386 }
387
388 #endif // TEST_HASH
389
390 // ----------------------------------------------------------------------------
391 // MIME types
392 // ----------------------------------------------------------------------------
393
394 #ifdef TEST_MIME
395
396 #include <wx/mimetype.h>
397
398 static void TestMimeEnum()
399 {
400 wxMimeTypesManager mimeTM;
401 wxArrayString mimetypes;
402
403 size_t count = mimeTM.EnumAllFileTypes(mimetypes);
404
405 printf("*** All %u known filetypes: ***\n", count);
406
407 wxArrayString exts;
408 wxString desc;
409
410 for ( size_t n = 0; n < count; n++ )
411 {
412 wxFileType *filetype = mimeTM.GetFileTypeFromMimeType(mimetypes[n]);
413 if ( !filetype )
414 {
415 printf("nothing known about the filetype '%s'!\n",
416 mimetypes[n].c_str());
417 continue;
418 }
419
420 filetype->GetDescription(&desc);
421 filetype->GetExtensions(exts);
422
423 filetype->GetIcon(NULL);
424
425 wxString extsAll;
426 for ( size_t e = 0; e < exts.GetCount(); e++ )
427 {
428 if ( e > 0 )
429 extsAll << _T(", ");
430 extsAll += exts[e];
431 }
432
433 printf("\t%s: %s (%s)\n",
434 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
435 }
436 }
437
438 #endif // TEST_MIME
439
440 // ----------------------------------------------------------------------------
441 // long long
442 // ----------------------------------------------------------------------------
443
444 #ifdef TEST_LONGLONG
445
446 #include <wx/longlong.h>
447 #include <wx/timer.h>
448
449 // make a 64 bit number from 4 16 bit ones
450 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
451
452 // get a random 64 bit number
453 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
454
455 #if wxUSE_LONGLONG_WX
456 inline bool operator==(const wxLongLongWx& a, const wxLongLongNative& b)
457 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
458 inline bool operator==(const wxLongLongNative& a, const wxLongLongWx& b)
459 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
460 #endif // wxUSE_LONGLONG_WX
461
462 static void TestSpeed()
463 {
464 static const long max = 100000000;
465 long n;
466
467 {
468 wxStopWatch sw;
469
470 long l = 0;
471 for ( n = 0; n < max; n++ )
472 {
473 l += n;
474 }
475
476 printf("Summing longs took %ld milliseconds.\n", sw.Time());
477 }
478
479 #if wxUSE_LONGLONG_NATIVE
480 {
481 wxStopWatch sw;
482
483 wxLongLong_t l = 0;
484 for ( n = 0; n < max; n++ )
485 {
486 l += n;
487 }
488
489 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw.Time());
490 }
491 #endif // wxUSE_LONGLONG_NATIVE
492
493 {
494 wxStopWatch sw;
495
496 wxLongLong l;
497 for ( n = 0; n < max; n++ )
498 {
499 l += n;
500 }
501
502 printf("Summing wxLongLongs took %ld milliseconds.\n", sw.Time());
503 }
504 }
505
506 static void TestLongLongConversion()
507 {
508 puts("*** Testing wxLongLong conversions ***\n");
509
510 wxLongLong a;
511 size_t nTested = 0;
512 for ( size_t n = 0; n < 100000; n++ )
513 {
514 a = RAND_LL();
515
516 #if wxUSE_LONGLONG_NATIVE
517 wxLongLongNative b(a.GetHi(), a.GetLo());
518
519 wxASSERT_MSG( a == b, "conversions failure" );
520 #else
521 puts("Can't do it without native long long type, test skipped.");
522
523 return;
524 #endif // wxUSE_LONGLONG_NATIVE
525
526 if ( !(nTested % 1000) )
527 {
528 putchar('.');
529 fflush(stdout);
530 }
531
532 nTested++;
533 }
534
535 puts(" done!");
536 }
537
538 static void TestMultiplication()
539 {
540 puts("*** Testing wxLongLong multiplication ***\n");
541
542 wxLongLong a, b;
543 size_t nTested = 0;
544 for ( size_t n = 0; n < 100000; n++ )
545 {
546 a = RAND_LL();
547 b = RAND_LL();
548
549 #if wxUSE_LONGLONG_NATIVE
550 wxLongLongNative aa(a.GetHi(), a.GetLo());
551 wxLongLongNative bb(b.GetHi(), b.GetLo());
552
553 wxASSERT_MSG( a*b == aa*bb, "multiplication failure" );
554 #else // !wxUSE_LONGLONG_NATIVE
555 puts("Can't do it without native long long type, test skipped.");
556
557 return;
558 #endif // wxUSE_LONGLONG_NATIVE
559
560 if ( !(nTested % 1000) )
561 {
562 putchar('.');
563 fflush(stdout);
564 }
565
566 nTested++;
567 }
568
569 puts(" done!");
570 }
571
572 static void TestDivision()
573 {
574 puts("*** Testing wxLongLong division ***\n");
575
576 wxLongLong q, r;
577 size_t nTested = 0;
578 for ( size_t n = 0; n < 100000; n++ )
579 {
580 // get a random wxLongLong (shifting by 12 the MSB ensures that the
581 // multiplication will not overflow)
582 wxLongLong ll = MAKE_LL((rand() >> 12), rand(), rand(), rand());
583
584 // get a random long (not wxLongLong for now) to divide it with
585 long l = rand();
586 q = ll / l;
587 r = ll % l;
588
589 #if wxUSE_LONGLONG_NATIVE
590 wxLongLongNative m(ll.GetHi(), ll.GetLo());
591
592 wxLongLongNative p = m / l, s = m % l;
593 wxASSERT_MSG( q == p && r == s, "division failure" );
594 #else // !wxUSE_LONGLONG_NATIVE
595 // verify the result
596 wxASSERT_MSG( ll == q*l + r, "division failure" );
597 #endif // wxUSE_LONGLONG_NATIVE
598
599 if ( !(nTested % 1000) )
600 {
601 putchar('.');
602 fflush(stdout);
603 }
604
605 nTested++;
606 }
607
608 puts(" done!");
609 }
610
611 static void TestAddition()
612 {
613 puts("*** Testing wxLongLong addition ***\n");
614
615 wxLongLong a, b, c;
616 size_t nTested = 0;
617 for ( size_t n = 0; n < 100000; n++ )
618 {
619 a = RAND_LL();
620 b = RAND_LL();
621 c = a + b;
622
623 #if wxUSE_LONGLONG_NATIVE
624 wxASSERT_MSG( c == wxLongLongNative(a.GetHi(), a.GetLo()) +
625 wxLongLongNative(b.GetHi(), b.GetLo()),
626 "addition failure" );
627 #else // !wxUSE_LONGLONG_NATIVE
628 wxASSERT_MSG( c - b == a, "addition failure" );
629 #endif // wxUSE_LONGLONG_NATIVE
630
631 if ( !(nTested % 1000) )
632 {
633 putchar('.');
634 fflush(stdout);
635 }
636
637 nTested++;
638 }
639
640 puts(" done!");
641 }
642
643 static void TestBitOperations()
644 {
645 puts("*** Testing wxLongLong bit operation ***\n");
646
647 wxLongLong a, c;
648 size_t nTested = 0;
649 for ( size_t n = 0; n < 100000; n++ )
650 {
651 a = RAND_LL();
652
653 #if wxUSE_LONGLONG_NATIVE
654 for ( size_t n = 0; n < 33; n++ )
655 {
656 wxLongLongNative b(a.GetHi(), a.GetLo());
657
658 b >>= n;
659 c = a >> n;
660
661 wxASSERT_MSG( b == c, "bit shift failure" );
662
663 b = wxLongLongNative(a.GetHi(), a.GetLo()) << n;
664 c = a << n;
665
666 wxASSERT_MSG( b == c, "bit shift failure" );
667 }
668
669 #else // !wxUSE_LONGLONG_NATIVE
670 puts("Can't do it without native long long type, test skipped.");
671
672 return;
673 #endif // wxUSE_LONGLONG_NATIVE
674
675 if ( !(nTested % 1000) )
676 {
677 putchar('.');
678 fflush(stdout);
679 }
680
681 nTested++;
682 }
683
684 puts(" done!");
685 }
686
687 #undef MAKE_LL
688 #undef RAND_LL
689
690 #endif // TEST_LONGLONG
691
692 // ----------------------------------------------------------------------------
693 // sockets
694 // ----------------------------------------------------------------------------
695
696 #ifdef TEST_SOCKETS
697
698 #include <wx/socket.h>
699
700 static void TestSocketClient()
701 {
702 puts("*** Testing wxSocketClient ***\n");
703
704 wxIPV4address addrDst;
705 addrDst.Hostname("www.wxwindows.org");
706 addrDst.Service(80);
707
708 wxSocketClient client;
709 if ( !client.Connect(addrDst) )
710 {
711 printf("ERROR: failed to connect to %s\n", addrDst.Hostname().c_str());
712 }
713 else
714 {
715 char buf[8192];
716
717 client.Write("get /front.htm\n", 17);
718 client.Read(buf, WXSIZEOF(buf));
719 printf("Server replied:\n%s", buf);
720 }
721 }
722
723 #endif // TEST_SOCKETS
724
725 // ----------------------------------------------------------------------------
726 // timers
727 // ----------------------------------------------------------------------------
728
729 #ifdef TEST_TIMER
730
731 #include <wx/timer.h>
732 #include <wx/utils.h>
733
734 static void TestStopWatch()
735 {
736 puts("*** Testing wxStopWatch ***\n");
737
738 wxStopWatch sw;
739 printf("Sleeping 3 seconds...");
740 wxSleep(3);
741 printf("\telapsed time: %ld\n", sw.Time());
742
743 sw.Pause();
744 printf("Sleeping 2 more seconds...");
745 wxSleep(2);
746 printf("\telapsed time: %ld\n", sw.Time());
747
748 sw.Resume();
749 printf("And 3 more seconds...");
750 wxSleep(3);
751 printf("\telapsed time: %ld\n", sw.Time());
752 }
753
754 #endif // TEST_TIMER
755
756 // ----------------------------------------------------------------------------
757 // date time
758 // ----------------------------------------------------------------------------
759
760 #ifdef TEST_DATETIME
761
762 #include <wx/date.h>
763
764 #include <wx/datetime.h>
765
766 // the test data
767 struct Date
768 {
769 wxDateTime::wxDateTime_t day;
770 wxDateTime::Month month;
771 int year;
772 wxDateTime::wxDateTime_t hour, min, sec;
773 double jdn;
774 wxDateTime::WeekDay wday;
775 time_t gmticks, ticks;
776
777 void Init(const wxDateTime::Tm& tm)
778 {
779 day = tm.mday;
780 month = tm.mon;
781 year = tm.year;
782 hour = tm.hour;
783 min = tm.min;
784 sec = tm.sec;
785 jdn = 0.0;
786 gmticks = ticks = -1;
787 }
788
789 wxDateTime DT() const
790 { return wxDateTime(day, month, year, hour, min, sec); }
791
792 bool SameDay(const wxDateTime::Tm& tm) const
793 {
794 return day == tm.mday && month == tm.mon && year == tm.year;
795 }
796
797 wxString Format() const
798 {
799 wxString s;
800 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
801 hour, min, sec,
802 wxDateTime::GetMonthName(month).c_str(),
803 day,
804 abs(wxDateTime::ConvertYearToBC(year)),
805 year > 0 ? "AD" : "BC");
806 return s;
807 }
808
809 wxString FormatDate() const
810 {
811 wxString s;
812 s.Printf("%02d-%s-%4d%s",
813 day,
814 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
815 abs(wxDateTime::ConvertYearToBC(year)),
816 year > 0 ? "AD" : "BC");
817 return s;
818 }
819 };
820
821 static const Date testDates[] =
822 {
823 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
824 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
825 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
826 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
827 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
828 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
829 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
830 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
831 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
832 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
833 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
834 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
835 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
836 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
837 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
838 };
839
840 // this test miscellaneous static wxDateTime functions
841 static void TestTimeStatic()
842 {
843 puts("\n*** wxDateTime static methods test ***");
844
845 // some info about the current date
846 int year = wxDateTime::GetCurrentYear();
847 printf("Current year %d is %sa leap one and has %d days.\n",
848 year,
849 wxDateTime::IsLeapYear(year) ? "" : "not ",
850 wxDateTime::GetNumberOfDays(year));
851
852 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
853 printf("Current month is '%s' ('%s') and it has %d days\n",
854 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
855 wxDateTime::GetMonthName(month).c_str(),
856 wxDateTime::GetNumberOfDays(month));
857
858 // leap year logic
859 static const size_t nYears = 5;
860 static const size_t years[2][nYears] =
861 {
862 // first line: the years to test
863 { 1990, 1976, 2000, 2030, 1984, },
864
865 // second line: TRUE if leap, FALSE otherwise
866 { FALSE, TRUE, TRUE, FALSE, TRUE }
867 };
868
869 for ( size_t n = 0; n < nYears; n++ )
870 {
871 int year = years[0][n];
872 bool should = years[1][n] != 0,
873 is = wxDateTime::IsLeapYear(year);
874
875 printf("Year %d is %sa leap year (%s)\n",
876 year,
877 is ? "" : "not ",
878 should == is ? "ok" : "ERROR");
879
880 wxASSERT( should == wxDateTime::IsLeapYear(year) );
881 }
882 }
883
884 // test constructing wxDateTime objects
885 static void TestTimeSet()
886 {
887 puts("\n*** wxDateTime construction test ***");
888
889 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
890 {
891 const Date& d1 = testDates[n];
892 wxDateTime dt = d1.DT();
893
894 Date d2;
895 d2.Init(dt.GetTm());
896
897 wxString s1 = d1.Format(),
898 s2 = d2.Format();
899
900 printf("Date: %s == %s (%s)\n",
901 s1.c_str(), s2.c_str(),
902 s1 == s2 ? "ok" : "ERROR");
903 }
904 }
905
906 // test time zones stuff
907 static void TestTimeZones()
908 {
909 puts("\n*** wxDateTime timezone test ***");
910
911 wxDateTime now = wxDateTime::Now();
912
913 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
914 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
915 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
916 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
917 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
918 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
919
920 wxDateTime::Tm tm = now.GetTm();
921 if ( wxDateTime(tm) != now )
922 {
923 printf("ERROR: got %s instead of %s\n",
924 wxDateTime(tm).Format().c_str(), now.Format().c_str());
925 }
926 }
927
928 // test some minimal support for the dates outside the standard range
929 static void TestTimeRange()
930 {
931 puts("\n*** wxDateTime out-of-standard-range dates test ***");
932
933 static const char *fmt = "%d-%b-%Y %H:%M:%S";
934
935 printf("Unix epoch:\t%s\n",
936 wxDateTime(2440587.5).Format(fmt).c_str());
937 printf("Feb 29, 0: \t%s\n",
938 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
939 printf("JDN 0: \t%s\n",
940 wxDateTime(0.0).Format(fmt).c_str());
941 printf("Jan 1, 1AD:\t%s\n",
942 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
943 printf("May 29, 2099:\t%s\n",
944 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
945 }
946
947 static void TestTimeTicks()
948 {
949 puts("\n*** wxDateTime ticks test ***");
950
951 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
952 {
953 const Date& d = testDates[n];
954 if ( d.ticks == -1 )
955 continue;
956
957 wxDateTime dt = d.DT();
958 long ticks = (dt.GetValue() / 1000).ToLong();
959 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
960 if ( ticks == d.ticks )
961 {
962 puts(" (ok)");
963 }
964 else
965 {
966 printf(" (ERROR: should be %ld, delta = %ld)\n",
967 d.ticks, ticks - d.ticks);
968 }
969
970 dt = d.DT().ToTimezone(wxDateTime::GMT0);
971 ticks = (dt.GetValue() / 1000).ToLong();
972 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
973 if ( ticks == d.gmticks )
974 {
975 puts(" (ok)");
976 }
977 else
978 {
979 printf(" (ERROR: should be %ld, delta = %ld)\n",
980 d.gmticks, ticks - d.gmticks);
981 }
982 }
983
984 puts("");
985 }
986
987 // test conversions to JDN &c
988 static void TestTimeJDN()
989 {
990 puts("\n*** wxDateTime to JDN test ***");
991
992 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
993 {
994 const Date& d = testDates[n];
995 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
996 double jdn = dt.GetJulianDayNumber();
997
998 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
999 if ( jdn == d.jdn )
1000 {
1001 puts(" (ok)");
1002 }
1003 else
1004 {
1005 printf(" (ERROR: should be %f, delta = %f)\n",
1006 d.jdn, jdn - d.jdn);
1007 }
1008 }
1009 }
1010
1011 // test week days computation
1012 static void TestTimeWDays()
1013 {
1014 puts("\n*** wxDateTime weekday test ***");
1015
1016 // test GetWeekDay()
1017 size_t n;
1018 for ( n = 0; n < WXSIZEOF(testDates); n++ )
1019 {
1020 const Date& d = testDates[n];
1021 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1022
1023 wxDateTime::WeekDay wday = dt.GetWeekDay();
1024 printf("%s is: %s",
1025 d.Format().c_str(),
1026 wxDateTime::GetWeekDayName(wday).c_str());
1027 if ( wday == d.wday )
1028 {
1029 puts(" (ok)");
1030 }
1031 else
1032 {
1033 printf(" (ERROR: should be %s)\n",
1034 wxDateTime::GetWeekDayName(d.wday).c_str());
1035 }
1036 }
1037
1038 puts("");
1039
1040 // test SetToWeekDay()
1041 struct WeekDateTestData
1042 {
1043 Date date; // the real date (precomputed)
1044 int nWeek; // its week index in the month
1045 wxDateTime::WeekDay wday; // the weekday
1046 wxDateTime::Month month; // the month
1047 int year; // and the year
1048
1049 wxString Format() const
1050 {
1051 wxString s, which;
1052 switch ( nWeek < -1 ? -nWeek : nWeek )
1053 {
1054 case 1: which = "first"; break;
1055 case 2: which = "second"; break;
1056 case 3: which = "third"; break;
1057 case 4: which = "fourth"; break;
1058 case 5: which = "fifth"; break;
1059
1060 case -1: which = "last"; break;
1061 }
1062
1063 if ( nWeek < -1 )
1064 {
1065 which += " from end";
1066 }
1067
1068 s.Printf("The %s %s of %s in %d",
1069 which.c_str(),
1070 wxDateTime::GetWeekDayName(wday).c_str(),
1071 wxDateTime::GetMonthName(month).c_str(),
1072 year);
1073
1074 return s;
1075 }
1076 };
1077
1078 // the array data was generated by the following python program
1079 /*
1080 from DateTime import *
1081 from whrandom import *
1082 from string import *
1083
1084 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1085 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1086
1087 week = DateTimeDelta(7)
1088
1089 for n in range(20):
1090 year = randint(1900, 2100)
1091 month = randint(1, 12)
1092 day = randint(1, 28)
1093 dt = DateTime(year, month, day)
1094 wday = dt.day_of_week
1095
1096 countFromEnd = choice([-1, 1])
1097 weekNum = 0;
1098
1099 while dt.month is month:
1100 dt = dt - countFromEnd * week
1101 weekNum = weekNum + countFromEnd
1102
1103 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1104
1105 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1106 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1107 */
1108
1109 static const WeekDateTestData weekDatesTestData[] =
1110 {
1111 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
1112 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
1113 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
1114 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
1115 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
1116 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
1117 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
1118 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
1119 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
1120 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
1121 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
1122 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
1123 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
1124 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
1125 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
1126 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
1127 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
1128 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
1129 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
1130 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
1131 };
1132
1133 static const char *fmt = "%d-%b-%Y";
1134
1135 wxDateTime dt;
1136 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
1137 {
1138 const WeekDateTestData& wd = weekDatesTestData[n];
1139
1140 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
1141
1142 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
1143
1144 const Date& d = wd.date;
1145 if ( d.SameDay(dt.GetTm()) )
1146 {
1147 puts(" (ok)");
1148 }
1149 else
1150 {
1151 dt.Set(d.day, d.month, d.year);
1152
1153 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
1154 }
1155 }
1156 }
1157
1158 // test the computation of (ISO) week numbers
1159 static void TestTimeWNumber()
1160 {
1161 puts("\n*** wxDateTime week number test ***");
1162
1163 struct WeekNumberTestData
1164 {
1165 Date date; // the date
1166 wxDateTime::wxDateTime_t week; // the week number in the year
1167 wxDateTime::wxDateTime_t wmon; // the week number in the month
1168 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
1169 wxDateTime::wxDateTime_t dnum; // day number in the year
1170 };
1171
1172 // data generated with the following python script:
1173 /*
1174 from DateTime import *
1175 from whrandom import *
1176 from string import *
1177
1178 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1179 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1180
1181 def GetMonthWeek(dt):
1182 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1183 if weekNumMonth < 0:
1184 weekNumMonth = weekNumMonth + 53
1185 return weekNumMonth
1186
1187 def GetLastSundayBefore(dt):
1188 if dt.iso_week[2] == 7:
1189 return dt
1190 else:
1191 return dt - DateTimeDelta(dt.iso_week[2])
1192
1193 for n in range(20):
1194 year = randint(1900, 2100)
1195 month = randint(1, 12)
1196 day = randint(1, 28)
1197 dt = DateTime(year, month, day)
1198 dayNum = dt.day_of_year
1199 weekNum = dt.iso_week[1]
1200 weekNumMonth = GetMonthWeek(dt)
1201
1202 weekNumMonth2 = 0
1203 dtSunday = GetLastSundayBefore(dt)
1204
1205 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1206 weekNumMonth2 = weekNumMonth2 + 1
1207 dtSunday = dtSunday - DateTimeDelta(7)
1208
1209 data = { 'day': rjust(`day`, 2), \
1210 'month': monthNames[month - 1], \
1211 'year': year, \
1212 'weekNum': rjust(`weekNum`, 2), \
1213 'weekNumMonth': weekNumMonth, \
1214 'weekNumMonth2': weekNumMonth2, \
1215 'dayNum': rjust(`dayNum`, 3) }
1216
1217 print " { { %(day)s, "\
1218 "wxDateTime::%(month)s, "\
1219 "%(year)d }, "\
1220 "%(weekNum)s, "\
1221 "%(weekNumMonth)s, "\
1222 "%(weekNumMonth2)s, "\
1223 "%(dayNum)s }," % data
1224
1225 */
1226 static const WeekNumberTestData weekNumberTestDates[] =
1227 {
1228 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
1229 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
1230 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
1231 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
1232 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
1233 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
1234 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
1235 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
1236 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
1237 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
1238 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
1239 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
1240 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
1241 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
1242 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
1243 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
1244 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
1245 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
1246 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
1247 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
1248 };
1249
1250 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
1251 {
1252 const WeekNumberTestData& wn = weekNumberTestDates[n];
1253 const Date& d = wn.date;
1254
1255 wxDateTime dt = d.DT();
1256
1257 wxDateTime::wxDateTime_t
1258 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
1259 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
1260 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1261 dnum = dt.GetDayOfYear();
1262
1263 printf("%s: the day number is %d",
1264 d.FormatDate().c_str(), dnum);
1265 if ( dnum == wn.dnum )
1266 {
1267 printf(" (ok)");
1268 }
1269 else
1270 {
1271 printf(" (ERROR: should be %d)", wn.dnum);
1272 }
1273
1274 printf(", week in month is %d", wmon);
1275 if ( wmon == wn.wmon )
1276 {
1277 printf(" (ok)");
1278 }
1279 else
1280 {
1281 printf(" (ERROR: should be %d)", wn.wmon);
1282 }
1283
1284 printf(" or %d", wmon2);
1285 if ( wmon2 == wn.wmon2 )
1286 {
1287 printf(" (ok)");
1288 }
1289 else
1290 {
1291 printf(" (ERROR: should be %d)", wn.wmon2);
1292 }
1293
1294 printf(", week in year is %d", week);
1295 if ( week == wn.week )
1296 {
1297 puts(" (ok)");
1298 }
1299 else
1300 {
1301 printf(" (ERROR: should be %d)\n", wn.week);
1302 }
1303 }
1304 }
1305
1306 // test DST calculations
1307 static void TestTimeDST()
1308 {
1309 puts("\n*** wxDateTime DST test ***");
1310
1311 printf("DST is%s in effect now.\n\n",
1312 wxDateTime::Now().IsDST() ? "" : " not");
1313
1314 // taken from http://www.energy.ca.gov/daylightsaving.html
1315 static const Date datesDST[2][2004 - 1900 + 1] =
1316 {
1317 {
1318 { 1, wxDateTime::Apr, 1990 },
1319 { 7, wxDateTime::Apr, 1991 },
1320 { 5, wxDateTime::Apr, 1992 },
1321 { 4, wxDateTime::Apr, 1993 },
1322 { 3, wxDateTime::Apr, 1994 },
1323 { 2, wxDateTime::Apr, 1995 },
1324 { 7, wxDateTime::Apr, 1996 },
1325 { 6, wxDateTime::Apr, 1997 },
1326 { 5, wxDateTime::Apr, 1998 },
1327 { 4, wxDateTime::Apr, 1999 },
1328 { 2, wxDateTime::Apr, 2000 },
1329 { 1, wxDateTime::Apr, 2001 },
1330 { 7, wxDateTime::Apr, 2002 },
1331 { 6, wxDateTime::Apr, 2003 },
1332 { 4, wxDateTime::Apr, 2004 },
1333 },
1334 {
1335 { 28, wxDateTime::Oct, 1990 },
1336 { 27, wxDateTime::Oct, 1991 },
1337 { 25, wxDateTime::Oct, 1992 },
1338 { 31, wxDateTime::Oct, 1993 },
1339 { 30, wxDateTime::Oct, 1994 },
1340 { 29, wxDateTime::Oct, 1995 },
1341 { 27, wxDateTime::Oct, 1996 },
1342 { 26, wxDateTime::Oct, 1997 },
1343 { 25, wxDateTime::Oct, 1998 },
1344 { 31, wxDateTime::Oct, 1999 },
1345 { 29, wxDateTime::Oct, 2000 },
1346 { 28, wxDateTime::Oct, 2001 },
1347 { 27, wxDateTime::Oct, 2002 },
1348 { 26, wxDateTime::Oct, 2003 },
1349 { 31, wxDateTime::Oct, 2004 },
1350 }
1351 };
1352
1353 int year;
1354 for ( year = 1990; year < 2005; year++ )
1355 {
1356 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
1357 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
1358
1359 printf("DST period in the US for year %d: from %s to %s",
1360 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
1361
1362 size_t n = year - 1990;
1363 const Date& dBegin = datesDST[0][n];
1364 const Date& dEnd = datesDST[1][n];
1365
1366 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
1367 {
1368 puts(" (ok)");
1369 }
1370 else
1371 {
1372 printf(" (ERROR: should be %s %d to %s %d)\n",
1373 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
1374 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
1375 }
1376 }
1377
1378 puts("");
1379
1380 for ( year = 1990; year < 2005; year++ )
1381 {
1382 printf("DST period in Europe for year %d: from %s to %s\n",
1383 year,
1384 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
1385 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
1386 }
1387 }
1388
1389 // test wxDateTime -> text conversion
1390 static void TestTimeFormat()
1391 {
1392 puts("\n*** wxDateTime formatting test ***");
1393
1394 // some information may be lost during conversion, so store what kind
1395 // of info should we recover after a round trip
1396 enum CompareKind
1397 {
1398 CompareNone, // don't try comparing
1399 CompareBoth, // dates and times should be identical
1400 CompareDate, // dates only
1401 CompareTime // time only
1402 };
1403
1404 static const struct
1405 {
1406 CompareKind compareKind;
1407 const char *format;
1408 } formatTestFormats[] =
1409 {
1410 { CompareBoth, "---> %c" },
1411 { CompareDate, "Date is %A, %d of %B, in year %Y" },
1412 { CompareBoth, "Date is %x, time is %X" },
1413 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
1414 { CompareNone, "The day of year: %j, the week of year: %W" },
1415 };
1416
1417 static const Date formatTestDates[] =
1418 {
1419 { 29, wxDateTime::May, 1976, 18, 30, 00 },
1420 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
1421 #if 0
1422 // this test can't work for other centuries because it uses two digit
1423 // years in formats, so don't even try it
1424 { 29, wxDateTime::May, 2076, 18, 30, 00 },
1425 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
1426 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
1427 #endif
1428 };
1429
1430 // an extra test (as it doesn't depend on date, don't do it in the loop)
1431 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1432
1433 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
1434 {
1435 puts("");
1436
1437 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
1438 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
1439 {
1440 wxString s = dt.Format(formatTestFormats[n].format);
1441 printf("%s", s.c_str());
1442
1443 // what can we recover?
1444 int kind = formatTestFormats[n].compareKind;
1445
1446 // convert back
1447 wxDateTime dt2;
1448 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
1449 if ( !result )
1450 {
1451 // converion failed - should it have?
1452 if ( kind == CompareNone )
1453 puts(" (ok)");
1454 else
1455 puts(" (ERROR: conversion back failed)");
1456 }
1457 else if ( *result )
1458 {
1459 // should have parsed the entire string
1460 puts(" (ERROR: conversion back stopped too soon)");
1461 }
1462 else
1463 {
1464 bool equal = FALSE; // suppress compilaer warning
1465 switch ( kind )
1466 {
1467 case CompareBoth:
1468 equal = dt2 == dt;
1469 break;
1470
1471 case CompareDate:
1472 equal = dt.IsSameDate(dt2);
1473 break;
1474
1475 case CompareTime:
1476 equal = dt.IsSameTime(dt2);
1477 break;
1478 }
1479
1480 if ( !equal )
1481 {
1482 printf(" (ERROR: got back '%s' instead of '%s')\n",
1483 dt2.Format().c_str(), dt.Format().c_str());
1484 }
1485 else
1486 {
1487 puts(" (ok)");
1488 }
1489 }
1490 }
1491 }
1492 }
1493
1494 // test text -> wxDateTime conversion
1495 static void TestTimeParse()
1496 {
1497 puts("\n*** wxDateTime parse test ***");
1498
1499 struct ParseTestData
1500 {
1501 const char *format;
1502 Date date;
1503 bool good;
1504 };
1505
1506 static const ParseTestData parseTestDates[] =
1507 {
1508 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
1509 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
1510 };
1511
1512 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
1513 {
1514 const char *format = parseTestDates[n].format;
1515
1516 printf("%s => ", format);
1517
1518 wxDateTime dt;
1519 if ( dt.ParseRfc822Date(format) )
1520 {
1521 printf("%s ", dt.Format().c_str());
1522
1523 if ( parseTestDates[n].good )
1524 {
1525 wxDateTime dtReal = parseTestDates[n].date.DT();
1526 if ( dt == dtReal )
1527 {
1528 puts("(ok)");
1529 }
1530 else
1531 {
1532 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
1533 }
1534 }
1535 else
1536 {
1537 puts("(ERROR: bad format)");
1538 }
1539 }
1540 else
1541 {
1542 printf("bad format (%s)\n",
1543 parseTestDates[n].good ? "ERROR" : "ok");
1544 }
1545 }
1546 }
1547
1548 static void TestInteractive()
1549 {
1550 puts("\n*** interactive wxDateTime tests ***");
1551
1552 char buf[128];
1553
1554 for ( ;; )
1555 {
1556 printf("Enter a date: ");
1557 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
1558 break;
1559
1560 wxDateTime dt;
1561 if ( !dt.ParseDate(buf) )
1562 {
1563 puts("failed to parse the date");
1564
1565 continue;
1566 }
1567
1568 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1569 dt.FormatISODate().c_str(),
1570 dt.GetDayOfYear(),
1571 dt.GetWeekOfMonth(wxDateTime::Monday_First),
1572 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1573 dt.GetWeekOfYear(wxDateTime::Monday_First));
1574 }
1575
1576 puts("\n*** done ***");
1577 }
1578
1579 static void TestTimeArithmetics()
1580 {
1581 puts("\n*** testing arithmetic operations on wxDateTime ***");
1582
1583 static const struct
1584 {
1585 wxDateSpan span;
1586 const char *name;
1587 } testArithmData[] =
1588 {
1589 { wxDateSpan::Day(), "day" },
1590 { wxDateSpan::Week(), "week" },
1591 { wxDateSpan::Month(), "month" },
1592 { wxDateSpan::Year(), "year" },
1593 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1594 };
1595
1596 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
1597
1598 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
1599 {
1600 wxDateSpan span = testArithmData[n].span;
1601 dt1 = dt + span;
1602 dt2 = dt - span;
1603
1604 const char *name = testArithmData[n].name;
1605 printf("%s + %s = %s, %s - %s = %s\n",
1606 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
1607 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
1608
1609 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
1610 if ( dt1 - span == dt )
1611 {
1612 puts(" (ok)");
1613 }
1614 else
1615 {
1616 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
1617 }
1618
1619 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
1620 if ( dt2 + span == dt )
1621 {
1622 puts(" (ok)");
1623 }
1624 else
1625 {
1626 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
1627 }
1628
1629 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
1630 if ( dt2 + 2*span == dt1 )
1631 {
1632 puts(" (ok)");
1633 }
1634 else
1635 {
1636 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
1637 }
1638
1639 puts("");
1640 }
1641 }
1642
1643 static void TestTimeHolidays()
1644 {
1645 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1646
1647 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
1648 wxDateTime dtStart(1, tm.mon, tm.year),
1649 dtEnd = dtStart.GetLastMonthDay();
1650
1651 wxDateTimeArray hol;
1652 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
1653
1654 const wxChar *format = "%d-%b-%Y (%a)";
1655
1656 printf("All holidays between %s and %s:\n",
1657 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
1658
1659 size_t count = hol.GetCount();
1660 for ( size_t n = 0; n < count; n++ )
1661 {
1662 printf("\t%s\n", hol[n].Format(format).c_str());
1663 }
1664
1665 puts("");
1666 }
1667
1668 #if 0
1669
1670 // test compatibility with the old wxDate/wxTime classes
1671 static void TestTimeCompatibility()
1672 {
1673 puts("\n*** wxDateTime compatibility test ***");
1674
1675 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1676 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1677
1678 double jdnNow = wxDateTime::Now().GetJDN();
1679 long jdnMidnight = (long)(jdnNow - 0.5);
1680 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
1681
1682 jdnMidnight = wxDate().Set().GetJulianDate();
1683 printf("wxDateTime for today: %s\n",
1684 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
1685
1686 int flags = wxEUROPEAN;//wxFULL;
1687 wxDate date;
1688 date.Set();
1689 printf("Today is %s\n", date.FormatDate(flags).c_str());
1690 for ( int n = 0; n < 7; n++ )
1691 {
1692 printf("Previous %s is %s\n",
1693 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
1694 date.Previous(n + 1).FormatDate(flags).c_str());
1695 }
1696 }
1697
1698 #endif // 0
1699
1700 #endif // TEST_DATETIME
1701
1702 // ----------------------------------------------------------------------------
1703 // threads
1704 // ----------------------------------------------------------------------------
1705
1706 #ifdef TEST_THREADS
1707
1708 #include <wx/thread.h>
1709
1710 static size_t gs_counter = (size_t)-1;
1711 static wxCriticalSection gs_critsect;
1712 static wxCondition gs_cond;
1713
1714 class MyJoinableThread : public wxThread
1715 {
1716 public:
1717 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
1718 { m_n = n; Create(); }
1719
1720 // thread execution starts here
1721 virtual ExitCode Entry();
1722
1723 private:
1724 size_t m_n;
1725 };
1726
1727 wxThread::ExitCode MyJoinableThread::Entry()
1728 {
1729 unsigned long res = 1;
1730 for ( size_t n = 1; n < m_n; n++ )
1731 {
1732 res *= n;
1733
1734 // it's a loooong calculation :-)
1735 Sleep(100);
1736 }
1737
1738 return (ExitCode)res;
1739 }
1740
1741 class MyDetachedThread : public wxThread
1742 {
1743 public:
1744 MyDetachedThread(size_t n, char ch)
1745 {
1746 m_n = n;
1747 m_ch = ch;
1748 m_cancelled = FALSE;
1749
1750 Create();
1751 }
1752
1753 // thread execution starts here
1754 virtual ExitCode Entry();
1755
1756 // and stops here
1757 virtual void OnExit();
1758
1759 private:
1760 size_t m_n; // number of characters to write
1761 char m_ch; // character to write
1762
1763 bool m_cancelled; // FALSE if we exit normally
1764 };
1765
1766 wxThread::ExitCode MyDetachedThread::Entry()
1767 {
1768 {
1769 wxCriticalSectionLocker lock(gs_critsect);
1770 if ( gs_counter == (size_t)-1 )
1771 gs_counter = 1;
1772 else
1773 gs_counter++;
1774 }
1775
1776 for ( size_t n = 0; n < m_n; n++ )
1777 {
1778 if ( TestDestroy() )
1779 {
1780 m_cancelled = TRUE;
1781
1782 break;
1783 }
1784
1785 putchar(m_ch);
1786 fflush(stdout);
1787
1788 wxThread::Sleep(100);
1789 }
1790
1791 return 0;
1792 }
1793
1794 void MyDetachedThread::OnExit()
1795 {
1796 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
1797
1798 wxCriticalSectionLocker lock(gs_critsect);
1799 if ( !--gs_counter && !m_cancelled )
1800 gs_cond.Signal();
1801 }
1802
1803 void TestDetachedThreads()
1804 {
1805 puts("\n*** Testing detached threads ***");
1806
1807 static const size_t nThreads = 3;
1808 MyDetachedThread *threads[nThreads];
1809 size_t n;
1810 for ( n = 0; n < nThreads; n++ )
1811 {
1812 threads[n] = new MyDetachedThread(10, 'A' + n);
1813 }
1814
1815 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
1816 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
1817
1818 for ( n = 0; n < nThreads; n++ )
1819 {
1820 threads[n]->Run();
1821 }
1822
1823 // wait until all threads terminate
1824 gs_cond.Wait();
1825
1826 puts("");
1827 }
1828
1829 void TestJoinableThreads()
1830 {
1831 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
1832
1833 // calc 10! in the background
1834 MyJoinableThread thread(10);
1835 thread.Run();
1836
1837 printf("\nThread terminated with exit code %lu.\n",
1838 (unsigned long)thread.Wait());
1839 }
1840
1841 void TestThreadSuspend()
1842 {
1843 puts("\n*** Testing thread suspend/resume functions ***");
1844
1845 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
1846
1847 thread->Run();
1848
1849 // this is for this demo only, in a real life program we'd use another
1850 // condition variable which would be signaled from wxThread::Entry() to
1851 // tell us that the thread really started running - but here just wait a
1852 // bit and hope that it will be enough (the problem is, of course, that
1853 // the thread might still not run when we call Pause() which will result
1854 // in an error)
1855 wxThread::Sleep(300);
1856
1857 for ( size_t n = 0; n < 3; n++ )
1858 {
1859 thread->Pause();
1860
1861 puts("\nThread suspended");
1862 if ( n > 0 )
1863 {
1864 // don't sleep but resume immediately the first time
1865 wxThread::Sleep(300);
1866 }
1867 puts("Going to resume the thread");
1868
1869 thread->Resume();
1870 }
1871
1872 puts("Waiting until it terminates now");
1873
1874 // wait until the thread terminates
1875 gs_cond.Wait();
1876
1877 puts("");
1878 }
1879
1880 void TestThreadDelete()
1881 {
1882 // As above, using Sleep() is only for testing here - we must use some
1883 // synchronisation object instead to ensure that the thread is still
1884 // running when we delete it - deleting a detached thread which already
1885 // terminated will lead to a crash!
1886
1887 puts("\n*** Testing thread delete function ***");
1888
1889 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
1890
1891 thread0->Delete();
1892
1893 puts("\nDeleted a thread which didn't start to run yet.");
1894
1895 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
1896
1897 thread1->Run();
1898
1899 wxThread::Sleep(300);
1900
1901 thread1->Delete();
1902
1903 puts("\nDeleted a running thread.");
1904
1905 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
1906
1907 thread2->Run();
1908
1909 wxThread::Sleep(300);
1910
1911 thread2->Pause();
1912
1913 thread2->Delete();
1914
1915 puts("\nDeleted a sleeping thread.");
1916
1917 MyJoinableThread thread3(20);
1918 thread3.Run();
1919
1920 thread3.Delete();
1921
1922 puts("\nDeleted a joinable thread.");
1923
1924 MyJoinableThread thread4(2);
1925 thread4.Run();
1926
1927 wxThread::Sleep(300);
1928
1929 thread4.Delete();
1930
1931 puts("\nDeleted a joinable thread which already terminated.");
1932
1933 puts("");
1934 }
1935
1936 #endif // TEST_THREADS
1937
1938 // ----------------------------------------------------------------------------
1939 // arrays
1940 // ----------------------------------------------------------------------------
1941
1942 #ifdef TEST_ARRAYS
1943
1944 void PrintArray(const char* name, const wxArrayString& array)
1945 {
1946 printf("Dump of the array '%s'\n", name);
1947
1948 size_t nCount = array.GetCount();
1949 for ( size_t n = 0; n < nCount; n++ )
1950 {
1951 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
1952 }
1953 }
1954
1955 #endif // TEST_ARRAYS
1956
1957 // ----------------------------------------------------------------------------
1958 // strings
1959 // ----------------------------------------------------------------------------
1960
1961 #ifdef TEST_STRINGS
1962
1963 #include "wx/timer.h"
1964 #include "wx/tokenzr.h"
1965
1966 static void TestStringConstruction()
1967 {
1968 puts("*** Testing wxString constructores ***");
1969
1970 #define TEST_CTOR(args, res) \
1971 { \
1972 wxString s args ; \
1973 printf("wxString%s = %s ", #args, s.c_str()); \
1974 if ( s == res ) \
1975 { \
1976 puts("(ok)"); \
1977 } \
1978 else \
1979 { \
1980 printf("(ERROR: should be %s)\n", res); \
1981 } \
1982 }
1983
1984 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
1985 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
1986 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
1987 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
1988
1989 static const wxChar *s = _T("?really!");
1990 const wxChar *start = wxStrchr(s, _T('r'));
1991 const wxChar *end = wxStrchr(s, _T('!'));
1992 TEST_CTOR((start, end), _T("really"));
1993
1994 puts("");
1995 }
1996
1997 static void TestString()
1998 {
1999 wxStopWatch sw;
2000
2001 wxString a, b, c;
2002
2003 a.reserve (128);
2004 b.reserve (128);
2005 c.reserve (128);
2006
2007 for (int i = 0; i < 1000000; ++i)
2008 {
2009 a = "Hello";
2010 b = " world";
2011 c = "! How'ya doin'?";
2012 a += b;
2013 a += c;
2014 c = "Hello world! What's up?";
2015 if (c != a)
2016 c = "Doh!";
2017 }
2018
2019 printf ("TestString elapsed time: %ld\n", sw.Time());
2020 }
2021
2022 static void TestPChar()
2023 {
2024 wxStopWatch sw;
2025
2026 char a [128];
2027 char b [128];
2028 char c [128];
2029
2030 for (int i = 0; i < 1000000; ++i)
2031 {
2032 strcpy (a, "Hello");
2033 strcpy (b, " world");
2034 strcpy (c, "! How'ya doin'?");
2035 strcat (a, b);
2036 strcat (a, c);
2037 strcpy (c, "Hello world! What's up?");
2038 if (strcmp (c, a) == 0)
2039 strcpy (c, "Doh!");
2040 }
2041
2042 printf ("TestPChar elapsed time: %ld\n", sw.Time());
2043 }
2044
2045 static void TestStringSub()
2046 {
2047 wxString s("Hello, world!");
2048
2049 puts("*** Testing wxString substring extraction ***");
2050
2051 printf("String = '%s'\n", s.c_str());
2052 printf("Left(5) = '%s'\n", s.Left(5).c_str());
2053 printf("Right(6) = '%s'\n", s.Right(6).c_str());
2054 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2055 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
2056 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
2057 printf("substr(3) = '%s'\n", s.substr(3).c_str());
2058
2059 puts("");
2060 }
2061
2062 static void TestStringFormat()
2063 {
2064 puts("*** Testing wxString formatting ***");
2065
2066 wxString s;
2067 s.Printf("%03d", 18);
2068
2069 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2070 printf("Number 18: %s\n", s.c_str());
2071
2072 puts("");
2073 }
2074
2075 // returns "not found" for npos, value for all others
2076 static wxString PosToString(size_t res)
2077 {
2078 wxString s = res == wxString::npos ? wxString(_T("not found"))
2079 : wxString::Format(_T("%u"), res);
2080 return s;
2081 }
2082
2083 static void TestStringFind()
2084 {
2085 puts("*** Testing wxString find() functions ***");
2086
2087 static const wxChar *strToFind = _T("ell");
2088 static const struct StringFindTest
2089 {
2090 const wxChar *str;
2091 size_t start,
2092 result; // of searching "ell" in str
2093 } findTestData[] =
2094 {
2095 { _T("Well, hello world"), 0, 1 },
2096 { _T("Well, hello world"), 6, 7 },
2097 { _T("Well, hello world"), 9, wxString::npos },
2098 };
2099
2100 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
2101 {
2102 const StringFindTest& ft = findTestData[n];
2103 size_t res = wxString(ft.str).find(strToFind, ft.start);
2104
2105 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2106 strToFind, ft.str, ft.start, PosToString(res).c_str());
2107
2108 size_t resTrue = ft.result;
2109 if ( res == resTrue )
2110 {
2111 puts(_T("(ok)"));
2112 }
2113 else
2114 {
2115 printf(_T("(ERROR: should be %s)\n"),
2116 PosToString(resTrue).c_str());
2117 }
2118 }
2119
2120 puts("");
2121 }
2122
2123 // replace TABs with \t and CRs with \n
2124 static wxString MakePrintable(const wxChar *s)
2125 {
2126 wxString str(s);
2127 (void)str.Replace(_T("\t"), _T("\\t"));
2128 (void)str.Replace(_T("\n"), _T("\\n"));
2129 (void)str.Replace(_T("\r"), _T("\\r"));
2130
2131 return str;
2132 }
2133
2134 static void TestStringTokenizer()
2135 {
2136 puts("*** Testing wxStringTokenizer ***");
2137
2138 static const wxChar *modeNames[] =
2139 {
2140 _T("default"),
2141 _T("return empty"),
2142 _T("return all empty"),
2143 _T("with delims"),
2144 _T("like strtok"),
2145 };
2146
2147 static const struct StringTokenizerTest
2148 {
2149 const wxChar *str; // string to tokenize
2150 const wxChar *delims; // delimiters to use
2151 size_t count; // count of token
2152 wxStringTokenizerMode mode; // how should we tokenize it
2153 } tokenizerTestData[] =
2154 {
2155 { _T(""), _T(" "), 0 },
2156 { _T("Hello, world"), _T(" "), 2 },
2157 { _T("Hello, world "), _T(" "), 2 },
2158 { _T("Hello, world"), _T(","), 2 },
2159 { _T("Hello, world!"), _T(",!"), 2 },
2160 { _T("Hello,, world!"), _T(",!"), 3 },
2161 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
2162 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2163 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
2164 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
2165 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
2166 { _T("01/02/99"), _T("/-"), 3 },
2167 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
2168 };
2169
2170 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
2171 {
2172 const StringTokenizerTest& tt = tokenizerTestData[n];
2173 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
2174
2175 size_t count = tkz.CountTokens();
2176 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2177 MakePrintable(tt.str).c_str(),
2178 count,
2179 MakePrintable(tt.delims).c_str(),
2180 modeNames[tkz.GetMode()]);
2181 if ( count == tt.count )
2182 {
2183 puts(_T("(ok)"));
2184 }
2185 else
2186 {
2187 printf(_T("(ERROR: should be %u)\n"), tt.count);
2188
2189 continue;
2190 }
2191
2192 // if we emulate strtok(), check that we do it correctly
2193 wxChar *buf, *s, *last;
2194
2195 if ( tkz.GetMode() == wxTOKEN_STRTOK )
2196 {
2197 buf = new wxChar[wxStrlen(tt.str) + 1];
2198 wxStrcpy(buf, tt.str);
2199
2200 s = wxStrtok(buf, tt.delims, &last);
2201 }
2202 else
2203 {
2204 buf = NULL;
2205 }
2206
2207 // now show the tokens themselves
2208 size_t count2 = 0;
2209 while ( tkz.HasMoreTokens() )
2210 {
2211 wxString token = tkz.GetNextToken();
2212
2213 printf(_T("\ttoken %u: '%s'"),
2214 ++count2,
2215 MakePrintable(token).c_str());
2216
2217 if ( buf )
2218 {
2219 if ( token == s )
2220 {
2221 puts(" (ok)");
2222 }
2223 else
2224 {
2225 printf(" (ERROR: should be %s)\n", s);
2226 }
2227
2228 s = wxStrtok(NULL, tt.delims, &last);
2229 }
2230 else
2231 {
2232 // nothing to compare with
2233 puts("");
2234 }
2235 }
2236
2237 if ( count2 != count )
2238 {
2239 puts(_T("\tERROR: token count mismatch"));
2240 }
2241
2242 delete [] buf;
2243 }
2244
2245 puts("");
2246 }
2247
2248 #endif // TEST_STRINGS
2249
2250 // ----------------------------------------------------------------------------
2251 // entry point
2252 // ----------------------------------------------------------------------------
2253
2254 int main(int argc, char **argv)
2255 {
2256 if ( !wxInitialize() )
2257 {
2258 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
2259 }
2260
2261 #ifdef TEST_USLEEP
2262 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2263 wxUsleep(3000);
2264 #endif // TEST_USLEEP
2265
2266 #ifdef TEST_CMDLINE
2267 static const wxCmdLineEntryDesc cmdLineDesc[] =
2268 {
2269 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
2270 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
2271
2272 { wxCMD_LINE_OPTION, "o", "output", "output file" },
2273 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
2274 { wxCMD_LINE_OPTION, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER },
2275 { wxCMD_LINE_OPTION, "d", "date", "output file date", wxCMD_LINE_VAL_DATE },
2276
2277 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
2278 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
2279
2280 { wxCMD_LINE_NONE }
2281 };
2282
2283 wxCmdLineParser parser(cmdLineDesc, argc, argv);
2284
2285 switch ( parser.Parse() )
2286 {
2287 case -1:
2288 wxLogMessage("Help was given, terminating.");
2289 break;
2290
2291 case 0:
2292 ShowCmdLine(parser);
2293 break;
2294
2295 default:
2296 wxLogMessage("Syntax error detected, aborting.");
2297 break;
2298 }
2299 #endif // TEST_CMDLINE
2300
2301 #ifdef TEST_STRINGS
2302 if ( 0 )
2303 {
2304 TestPChar();
2305 TestString();
2306 }
2307 if ( 0 )
2308 {
2309 TestStringConstruction();
2310 TestStringSub();
2311 TestStringFormat();
2312 TestStringFind();
2313 TestStringTokenizer();
2314 }
2315 #endif // TEST_STRINGS
2316
2317 #ifdef TEST_ARRAYS
2318 wxArrayString a1;
2319 a1.Add("tiger");
2320 a1.Add("cat");
2321 a1.Add("lion");
2322 a1.Add("dog");
2323 a1.Add("human");
2324 a1.Add("ape");
2325
2326 puts("*** Initially:");
2327
2328 PrintArray("a1", a1);
2329
2330 wxArrayString a2(a1);
2331 PrintArray("a2", a2);
2332
2333 wxSortedArrayString a3(a1);
2334 PrintArray("a3", a3);
2335
2336 puts("*** After deleting a string from a1");
2337 a1.Remove(2);
2338
2339 PrintArray("a1", a1);
2340 PrintArray("a2", a2);
2341 PrintArray("a3", a3);
2342
2343 puts("*** After reassigning a1 to a2 and a3");
2344 a3 = a2 = a1;
2345 PrintArray("a2", a2);
2346 PrintArray("a3", a3);
2347 #endif // TEST_ARRAYS
2348
2349 #ifdef TEST_DIR
2350 TestDirEnum();
2351 #endif // TEST_DIR
2352
2353 #ifdef TEST_EXECUTE
2354 TestExecute();
2355 #endif // TEST_EXECUTE
2356
2357 #ifdef TEST_FILECONF
2358 TestFileConfRead();
2359 #endif // TEST_FILECONF
2360
2361 #ifdef TEST_LOG
2362 wxString s;
2363 for ( size_t n = 0; n < 8000; n++ )
2364 {
2365 s << (char)('A' + (n % 26));
2366 }
2367
2368 wxString msg;
2369 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
2370
2371 // this one shouldn't be truncated
2372 printf(msg);
2373
2374 // but this one will because log functions use fixed size buffer
2375 // (note that it doesn't need '\n' at the end neither - will be added
2376 // by wxLog anyhow)
2377 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
2378 #endif // TEST_LOG
2379
2380 #ifdef TEST_THREADS
2381 int nCPUs = wxThread::GetCPUCount();
2382 printf("This system has %d CPUs\n", nCPUs);
2383 if ( nCPUs != -1 )
2384 wxThread::SetConcurrency(nCPUs);
2385
2386 if ( argc > 1 && argv[1][0] == 't' )
2387 wxLog::AddTraceMask("thread");
2388
2389 if ( 1 )
2390 TestDetachedThreads();
2391 if ( 1 )
2392 TestJoinableThreads();
2393 if ( 1 )
2394 TestThreadSuspend();
2395 if ( 1 )
2396 TestThreadDelete();
2397
2398 #endif // TEST_THREADS
2399
2400 #ifdef TEST_LONGLONG
2401 // seed pseudo random generator
2402 srand((unsigned)time(NULL));
2403
2404 if ( 0 )
2405 {
2406 TestSpeed();
2407 }
2408 TestMultiplication();
2409 if ( 0 )
2410 {
2411 TestDivision();
2412 TestAddition();
2413 TestLongLongConversion();
2414 TestBitOperations();
2415 }
2416 #endif // TEST_LONGLONG
2417
2418 #ifdef TEST_HASH
2419 TestHash();
2420 #endif // TEST_HASH
2421
2422 #ifdef TEST_MIME
2423 TestMimeEnum();
2424 #endif // TEST_MIME
2425
2426 #ifdef TEST_SOCKETS
2427 TestSocketClient();
2428 #endif // TEST_SOCKETS
2429
2430 #ifdef TEST_TIMER
2431 TestStopWatch();
2432 #endif // TEST_TIMER
2433
2434 #ifdef TEST_DATETIME
2435 if ( 0 )
2436 {
2437 TestTimeSet();
2438 TestTimeStatic();
2439 TestTimeRange();
2440 TestTimeZones();
2441 TestTimeTicks();
2442 TestTimeJDN();
2443 TestTimeDST();
2444 TestTimeWDays();
2445 TestTimeWNumber();
2446 TestTimeParse();
2447 TestTimeFormat();
2448 TestTimeArithmetics();
2449 }
2450 TestTimeHolidays();
2451 if ( 0 )
2452 TestInteractive();
2453 #endif // TEST_DATETIME
2454
2455 wxUninitialize();
2456
2457 return 0;
2458 }