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