]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
better 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 static const int PORT = 3000;
727
728 wxIPV4address addr;
729 addr.Service(PORT);
730
731 wxSocketServer *server = new wxSocketServer(addr);
732 if ( !server->Ok() )
733 {
734 puts("ERROR: failed to bind");
735
736 return;
737 }
738
739 for ( ;; )
740 {
741 printf("Server: waiting for connection on port %d...\n", PORT);
742
743 wxSocketBase *socket = server->Accept();
744 if ( !socket )
745 {
746 puts("ERROR: wxSocketServer::Accept() failed.");
747 break;
748 }
749
750 puts("Server: got a client.");
751
752 server->SetTimeout(60); // 1 min
753
754 while ( socket->IsConnected() )
755 {
756 wxString s;
757 char ch = '\0';
758 for ( ;; )
759 {
760 if ( socket->Read(&ch, sizeof(ch)).Error() )
761 {
762 // don't log error if the client just close the connection
763 if ( socket->IsConnected() )
764 {
765 puts("ERROR: in wxSocket::Read.");
766 }
767
768 break;
769 }
770
771 if ( ch == '\r' )
772 continue;
773
774 if ( ch == '\n' )
775 break;
776
777 s += ch;
778 }
779
780 if ( ch != '\n' )
781 {
782 break;
783 }
784
785 printf("Server: got '%s'.\n", s.c_str());
786 if ( s == _T("bye") )
787 {
788 delete socket;
789
790 break;
791 }
792
793 socket->Write(s.MakeUpper().c_str(), s.length());
794 socket->Write("\r\n", 2);
795 printf("Server: wrote '%s'.\n", s.c_str());
796 }
797
798 puts("Server: lost a client.");
799
800 socket->Destroy();
801 }
802
803 // same as "delete server" but is consistent with GUI programs
804 server->Destroy();
805 }
806
807 static void TestSocketClient()
808 {
809 puts("*** Testing wxSocketClient ***\n");
810
811 static const char *hostname = "www.wxwindows.org";
812
813 wxIPV4address addr;
814 addr.Hostname(hostname);
815 addr.Service(80);
816
817 printf("--- Attempting to connect to %s:80...\n", hostname);
818
819 wxSocketClient client;
820 if ( !client.Connect(addr) )
821 {
822 printf("ERROR: failed to connect to %s\n", hostname);
823 }
824 else
825 {
826 printf("--- Connected to %s:%u...\n",
827 addr.Hostname().c_str(), addr.Service());
828
829 char buf[8192];
830
831 // could use simply "GET" here I suppose
832 wxString cmdGet =
833 wxString::Format("GET http://%s/\r\n", hostname);
834 client.Write(cmdGet, cmdGet.length());
835 printf("--- Sent command '%s' to the server\n",
836 MakePrintable(cmdGet).c_str());
837 client.Read(buf, WXSIZEOF(buf));
838 printf("--- Server replied:\n%s", buf);
839 }
840 }
841
842 static void TestProtocolFtp()
843 {
844 puts("*** Testing wxFTP ***\n");
845
846 wxLog::AddTraceMask(_T("ftp"));
847
848 static const char *hostname = "ftp.wxwindows.org";
849
850 printf("--- Attempting to connect to %s:21...\n", hostname);
851
852 wxFTP ftp;
853 if ( !ftp.Connect(hostname) )
854 {
855 printf("ERROR: failed to connect to %s\n", hostname);
856 }
857 else
858 {
859 printf("--- Connected to %s, current directory is '%s'\n",
860 hostname, ftp.Pwd().c_str());
861 if ( !ftp.ChDir(_T("pub")) )
862 {
863 puts("ERROR: failed to cd to pub");
864 }
865
866 wxArrayString files;
867 if ( !ftp.GetList(files) )
868 {
869 puts("ERROR: failed to get list of files");
870 }
871 else
872 {
873 printf("List of files under '%s':\n", ftp.Pwd().c_str());
874 size_t count = files.GetCount();
875 for ( size_t n = 0; n < count; n++ )
876 {
877 printf("\t%s\n", files[n].c_str());
878 }
879 puts("End of the file list");
880 }
881
882 if ( !ftp.ChDir(_T("..")) )
883 {
884 puts("ERROR: failed to cd to ..");
885 }
886
887 static const char *filename = "welcome.msg";
888 wxInputStream *in = ftp.GetInputStream(filename);
889 if ( !in )
890 {
891 puts("ERROR: couldn't get input stream");
892 }
893 else
894 {
895 size_t size = in->StreamSize();
896 printf("Reading file %s (%u bytes)...", filename, size);
897
898 char *data = new char[size];
899 if ( !in->Read(data, size) )
900 {
901 puts("ERROR: read error");
902 }
903 else
904 {
905 printf("\nContents of %s:\n%s\n", filename, data);
906 }
907
908 delete [] data;
909 delete in;
910 }
911 }
912 }
913
914 #endif // TEST_SOCKETS
915
916 // ----------------------------------------------------------------------------
917 // timers
918 // ----------------------------------------------------------------------------
919
920 #ifdef TEST_TIMER
921
922 #include <wx/timer.h>
923 #include <wx/utils.h>
924
925 static void TestStopWatch()
926 {
927 puts("*** Testing wxStopWatch ***\n");
928
929 wxStopWatch sw;
930 printf("Sleeping 3 seconds...");
931 wxSleep(3);
932 printf("\telapsed time: %ldms\n", sw.Time());
933
934 sw.Pause();
935 printf("Sleeping 2 more seconds...");
936 wxSleep(2);
937 printf("\telapsed time: %ldms\n", sw.Time());
938
939 sw.Resume();
940 printf("And 3 more seconds...");
941 wxSleep(3);
942 printf("\telapsed time: %ldms\n", sw.Time());
943
944 wxStopWatch sw2;
945 puts("\nChecking for 'backwards clock' bug...");
946 for ( size_t n = 0; n < 70; n++ )
947 {
948 sw2.Start();
949
950 for ( size_t m = 0; m < 100000; m++ )
951 {
952 if ( sw.Time() < 0 || sw2.Time() < 0 )
953 {
954 puts("\ntime is negative - ERROR!");
955 }
956 }
957
958 putchar('.');
959 }
960
961 puts(", ok.");
962 }
963
964 #endif // TEST_TIMER
965
966 // ----------------------------------------------------------------------------
967 // date time
968 // ----------------------------------------------------------------------------
969
970 #ifdef TEST_DATETIME
971
972 #include <wx/date.h>
973
974 #include <wx/datetime.h>
975
976 // the test data
977 struct Date
978 {
979 wxDateTime::wxDateTime_t day;
980 wxDateTime::Month month;
981 int year;
982 wxDateTime::wxDateTime_t hour, min, sec;
983 double jdn;
984 wxDateTime::WeekDay wday;
985 time_t gmticks, ticks;
986
987 void Init(const wxDateTime::Tm& tm)
988 {
989 day = tm.mday;
990 month = tm.mon;
991 year = tm.year;
992 hour = tm.hour;
993 min = tm.min;
994 sec = tm.sec;
995 jdn = 0.0;
996 gmticks = ticks = -1;
997 }
998
999 wxDateTime DT() const
1000 { return wxDateTime(day, month, year, hour, min, sec); }
1001
1002 bool SameDay(const wxDateTime::Tm& tm) const
1003 {
1004 return day == tm.mday && month == tm.mon && year == tm.year;
1005 }
1006
1007 wxString Format() const
1008 {
1009 wxString s;
1010 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
1011 hour, min, sec,
1012 wxDateTime::GetMonthName(month).c_str(),
1013 day,
1014 abs(wxDateTime::ConvertYearToBC(year)),
1015 year > 0 ? "AD" : "BC");
1016 return s;
1017 }
1018
1019 wxString FormatDate() const
1020 {
1021 wxString s;
1022 s.Printf("%02d-%s-%4d%s",
1023 day,
1024 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
1025 abs(wxDateTime::ConvertYearToBC(year)),
1026 year > 0 ? "AD" : "BC");
1027 return s;
1028 }
1029 };
1030
1031 static const Date testDates[] =
1032 {
1033 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
1034 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
1035 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
1036 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
1037 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
1038 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
1039 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
1040 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
1041 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
1042 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
1043 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
1044 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
1045 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
1046 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
1047 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
1048 };
1049
1050 // this test miscellaneous static wxDateTime functions
1051 static void TestTimeStatic()
1052 {
1053 puts("\n*** wxDateTime static methods test ***");
1054
1055 // some info about the current date
1056 int year = wxDateTime::GetCurrentYear();
1057 printf("Current year %d is %sa leap one and has %d days.\n",
1058 year,
1059 wxDateTime::IsLeapYear(year) ? "" : "not ",
1060 wxDateTime::GetNumberOfDays(year));
1061
1062 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
1063 printf("Current month is '%s' ('%s') and it has %d days\n",
1064 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
1065 wxDateTime::GetMonthName(month).c_str(),
1066 wxDateTime::GetNumberOfDays(month));
1067
1068 // leap year logic
1069 static const size_t nYears = 5;
1070 static const size_t years[2][nYears] =
1071 {
1072 // first line: the years to test
1073 { 1990, 1976, 2000, 2030, 1984, },
1074
1075 // second line: TRUE if leap, FALSE otherwise
1076 { FALSE, TRUE, TRUE, FALSE, TRUE }
1077 };
1078
1079 for ( size_t n = 0; n < nYears; n++ )
1080 {
1081 int year = years[0][n];
1082 bool should = years[1][n] != 0,
1083 is = wxDateTime::IsLeapYear(year);
1084
1085 printf("Year %d is %sa leap year (%s)\n",
1086 year,
1087 is ? "" : "not ",
1088 should == is ? "ok" : "ERROR");
1089
1090 wxASSERT( should == wxDateTime::IsLeapYear(year) );
1091 }
1092 }
1093
1094 // test constructing wxDateTime objects
1095 static void TestTimeSet()
1096 {
1097 puts("\n*** wxDateTime construction test ***");
1098
1099 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1100 {
1101 const Date& d1 = testDates[n];
1102 wxDateTime dt = d1.DT();
1103
1104 Date d2;
1105 d2.Init(dt.GetTm());
1106
1107 wxString s1 = d1.Format(),
1108 s2 = d2.Format();
1109
1110 printf("Date: %s == %s (%s)\n",
1111 s1.c_str(), s2.c_str(),
1112 s1 == s2 ? "ok" : "ERROR");
1113 }
1114 }
1115
1116 // test time zones stuff
1117 static void TestTimeZones()
1118 {
1119 puts("\n*** wxDateTime timezone test ***");
1120
1121 wxDateTime now = wxDateTime::Now();
1122
1123 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
1124 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
1125 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
1126 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
1127 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
1128 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
1129
1130 wxDateTime::Tm tm = now.GetTm();
1131 if ( wxDateTime(tm) != now )
1132 {
1133 printf("ERROR: got %s instead of %s\n",
1134 wxDateTime(tm).Format().c_str(), now.Format().c_str());
1135 }
1136 }
1137
1138 // test some minimal support for the dates outside the standard range
1139 static void TestTimeRange()
1140 {
1141 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1142
1143 static const char *fmt = "%d-%b-%Y %H:%M:%S";
1144
1145 printf("Unix epoch:\t%s\n",
1146 wxDateTime(2440587.5).Format(fmt).c_str());
1147 printf("Feb 29, 0: \t%s\n",
1148 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
1149 printf("JDN 0: \t%s\n",
1150 wxDateTime(0.0).Format(fmt).c_str());
1151 printf("Jan 1, 1AD:\t%s\n",
1152 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
1153 printf("May 29, 2099:\t%s\n",
1154 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
1155 }
1156
1157 static void TestTimeTicks()
1158 {
1159 puts("\n*** wxDateTime ticks test ***");
1160
1161 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1162 {
1163 const Date& d = testDates[n];
1164 if ( d.ticks == -1 )
1165 continue;
1166
1167 wxDateTime dt = d.DT();
1168 long ticks = (dt.GetValue() / 1000).ToLong();
1169 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
1170 if ( ticks == d.ticks )
1171 {
1172 puts(" (ok)");
1173 }
1174 else
1175 {
1176 printf(" (ERROR: should be %ld, delta = %ld)\n",
1177 d.ticks, ticks - d.ticks);
1178 }
1179
1180 dt = d.DT().ToTimezone(wxDateTime::GMT0);
1181 ticks = (dt.GetValue() / 1000).ToLong();
1182 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
1183 if ( ticks == d.gmticks )
1184 {
1185 puts(" (ok)");
1186 }
1187 else
1188 {
1189 printf(" (ERROR: should be %ld, delta = %ld)\n",
1190 d.gmticks, ticks - d.gmticks);
1191 }
1192 }
1193
1194 puts("");
1195 }
1196
1197 // test conversions to JDN &c
1198 static void TestTimeJDN()
1199 {
1200 puts("\n*** wxDateTime to JDN test ***");
1201
1202 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
1203 {
1204 const Date& d = testDates[n];
1205 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1206 double jdn = dt.GetJulianDayNumber();
1207
1208 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
1209 if ( jdn == d.jdn )
1210 {
1211 puts(" (ok)");
1212 }
1213 else
1214 {
1215 printf(" (ERROR: should be %f, delta = %f)\n",
1216 d.jdn, jdn - d.jdn);
1217 }
1218 }
1219 }
1220
1221 // test week days computation
1222 static void TestTimeWDays()
1223 {
1224 puts("\n*** wxDateTime weekday test ***");
1225
1226 // test GetWeekDay()
1227 size_t n;
1228 for ( n = 0; n < WXSIZEOF(testDates); n++ )
1229 {
1230 const Date& d = testDates[n];
1231 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
1232
1233 wxDateTime::WeekDay wday = dt.GetWeekDay();
1234 printf("%s is: %s",
1235 d.Format().c_str(),
1236 wxDateTime::GetWeekDayName(wday).c_str());
1237 if ( wday == d.wday )
1238 {
1239 puts(" (ok)");
1240 }
1241 else
1242 {
1243 printf(" (ERROR: should be %s)\n",
1244 wxDateTime::GetWeekDayName(d.wday).c_str());
1245 }
1246 }
1247
1248 puts("");
1249
1250 // test SetToWeekDay()
1251 struct WeekDateTestData
1252 {
1253 Date date; // the real date (precomputed)
1254 int nWeek; // its week index in the month
1255 wxDateTime::WeekDay wday; // the weekday
1256 wxDateTime::Month month; // the month
1257 int year; // and the year
1258
1259 wxString Format() const
1260 {
1261 wxString s, which;
1262 switch ( nWeek < -1 ? -nWeek : nWeek )
1263 {
1264 case 1: which = "first"; break;
1265 case 2: which = "second"; break;
1266 case 3: which = "third"; break;
1267 case 4: which = "fourth"; break;
1268 case 5: which = "fifth"; break;
1269
1270 case -1: which = "last"; break;
1271 }
1272
1273 if ( nWeek < -1 )
1274 {
1275 which += " from end";
1276 }
1277
1278 s.Printf("The %s %s of %s in %d",
1279 which.c_str(),
1280 wxDateTime::GetWeekDayName(wday).c_str(),
1281 wxDateTime::GetMonthName(month).c_str(),
1282 year);
1283
1284 return s;
1285 }
1286 };
1287
1288 // the array data was generated by the following python program
1289 /*
1290 from DateTime import *
1291 from whrandom import *
1292 from string import *
1293
1294 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1295 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1296
1297 week = DateTimeDelta(7)
1298
1299 for n in range(20):
1300 year = randint(1900, 2100)
1301 month = randint(1, 12)
1302 day = randint(1, 28)
1303 dt = DateTime(year, month, day)
1304 wday = dt.day_of_week
1305
1306 countFromEnd = choice([-1, 1])
1307 weekNum = 0;
1308
1309 while dt.month is month:
1310 dt = dt - countFromEnd * week
1311 weekNum = weekNum + countFromEnd
1312
1313 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1314
1315 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1316 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1317 */
1318
1319 static const WeekDateTestData weekDatesTestData[] =
1320 {
1321 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
1322 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
1323 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
1324 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
1325 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
1326 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
1327 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
1328 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
1329 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
1330 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
1331 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
1332 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
1333 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
1334 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
1335 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
1336 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
1337 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
1338 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
1339 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
1340 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
1341 };
1342
1343 static const char *fmt = "%d-%b-%Y";
1344
1345 wxDateTime dt;
1346 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
1347 {
1348 const WeekDateTestData& wd = weekDatesTestData[n];
1349
1350 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
1351
1352 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
1353
1354 const Date& d = wd.date;
1355 if ( d.SameDay(dt.GetTm()) )
1356 {
1357 puts(" (ok)");
1358 }
1359 else
1360 {
1361 dt.Set(d.day, d.month, d.year);
1362
1363 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
1364 }
1365 }
1366 }
1367
1368 // test the computation of (ISO) week numbers
1369 static void TestTimeWNumber()
1370 {
1371 puts("\n*** wxDateTime week number test ***");
1372
1373 struct WeekNumberTestData
1374 {
1375 Date date; // the date
1376 wxDateTime::wxDateTime_t week; // the week number in the year
1377 wxDateTime::wxDateTime_t wmon; // the week number in the month
1378 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
1379 wxDateTime::wxDateTime_t dnum; // day number in the year
1380 };
1381
1382 // data generated with the following python script:
1383 /*
1384 from DateTime import *
1385 from whrandom import *
1386 from string import *
1387
1388 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1389 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1390
1391 def GetMonthWeek(dt):
1392 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1393 if weekNumMonth < 0:
1394 weekNumMonth = weekNumMonth + 53
1395 return weekNumMonth
1396
1397 def GetLastSundayBefore(dt):
1398 if dt.iso_week[2] == 7:
1399 return dt
1400 else:
1401 return dt - DateTimeDelta(dt.iso_week[2])
1402
1403 for n in range(20):
1404 year = randint(1900, 2100)
1405 month = randint(1, 12)
1406 day = randint(1, 28)
1407 dt = DateTime(year, month, day)
1408 dayNum = dt.day_of_year
1409 weekNum = dt.iso_week[1]
1410 weekNumMonth = GetMonthWeek(dt)
1411
1412 weekNumMonth2 = 0
1413 dtSunday = GetLastSundayBefore(dt)
1414
1415 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1416 weekNumMonth2 = weekNumMonth2 + 1
1417 dtSunday = dtSunday - DateTimeDelta(7)
1418
1419 data = { 'day': rjust(`day`, 2), \
1420 'month': monthNames[month - 1], \
1421 'year': year, \
1422 'weekNum': rjust(`weekNum`, 2), \
1423 'weekNumMonth': weekNumMonth, \
1424 'weekNumMonth2': weekNumMonth2, \
1425 'dayNum': rjust(`dayNum`, 3) }
1426
1427 print " { { %(day)s, "\
1428 "wxDateTime::%(month)s, "\
1429 "%(year)d }, "\
1430 "%(weekNum)s, "\
1431 "%(weekNumMonth)s, "\
1432 "%(weekNumMonth2)s, "\
1433 "%(dayNum)s }," % data
1434
1435 */
1436 static const WeekNumberTestData weekNumberTestDates[] =
1437 {
1438 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
1439 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
1440 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
1441 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
1442 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
1443 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
1444 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
1445 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
1446 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
1447 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
1448 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
1449 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
1450 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
1451 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
1452 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
1453 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
1454 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
1455 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
1456 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
1457 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
1458 };
1459
1460 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
1461 {
1462 const WeekNumberTestData& wn = weekNumberTestDates[n];
1463 const Date& d = wn.date;
1464
1465 wxDateTime dt = d.DT();
1466
1467 wxDateTime::wxDateTime_t
1468 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
1469 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
1470 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1471 dnum = dt.GetDayOfYear();
1472
1473 printf("%s: the day number is %d",
1474 d.FormatDate().c_str(), dnum);
1475 if ( dnum == wn.dnum )
1476 {
1477 printf(" (ok)");
1478 }
1479 else
1480 {
1481 printf(" (ERROR: should be %d)", wn.dnum);
1482 }
1483
1484 printf(", week in month is %d", wmon);
1485 if ( wmon == wn.wmon )
1486 {
1487 printf(" (ok)");
1488 }
1489 else
1490 {
1491 printf(" (ERROR: should be %d)", wn.wmon);
1492 }
1493
1494 printf(" or %d", wmon2);
1495 if ( wmon2 == wn.wmon2 )
1496 {
1497 printf(" (ok)");
1498 }
1499 else
1500 {
1501 printf(" (ERROR: should be %d)", wn.wmon2);
1502 }
1503
1504 printf(", week in year is %d", week);
1505 if ( week == wn.week )
1506 {
1507 puts(" (ok)");
1508 }
1509 else
1510 {
1511 printf(" (ERROR: should be %d)\n", wn.week);
1512 }
1513 }
1514 }
1515
1516 // test DST calculations
1517 static void TestTimeDST()
1518 {
1519 puts("\n*** wxDateTime DST test ***");
1520
1521 printf("DST is%s in effect now.\n\n",
1522 wxDateTime::Now().IsDST() ? "" : " not");
1523
1524 // taken from http://www.energy.ca.gov/daylightsaving.html
1525 static const Date datesDST[2][2004 - 1900 + 1] =
1526 {
1527 {
1528 { 1, wxDateTime::Apr, 1990 },
1529 { 7, wxDateTime::Apr, 1991 },
1530 { 5, wxDateTime::Apr, 1992 },
1531 { 4, wxDateTime::Apr, 1993 },
1532 { 3, wxDateTime::Apr, 1994 },
1533 { 2, wxDateTime::Apr, 1995 },
1534 { 7, wxDateTime::Apr, 1996 },
1535 { 6, wxDateTime::Apr, 1997 },
1536 { 5, wxDateTime::Apr, 1998 },
1537 { 4, wxDateTime::Apr, 1999 },
1538 { 2, wxDateTime::Apr, 2000 },
1539 { 1, wxDateTime::Apr, 2001 },
1540 { 7, wxDateTime::Apr, 2002 },
1541 { 6, wxDateTime::Apr, 2003 },
1542 { 4, wxDateTime::Apr, 2004 },
1543 },
1544 {
1545 { 28, wxDateTime::Oct, 1990 },
1546 { 27, wxDateTime::Oct, 1991 },
1547 { 25, wxDateTime::Oct, 1992 },
1548 { 31, wxDateTime::Oct, 1993 },
1549 { 30, wxDateTime::Oct, 1994 },
1550 { 29, wxDateTime::Oct, 1995 },
1551 { 27, wxDateTime::Oct, 1996 },
1552 { 26, wxDateTime::Oct, 1997 },
1553 { 25, wxDateTime::Oct, 1998 },
1554 { 31, wxDateTime::Oct, 1999 },
1555 { 29, wxDateTime::Oct, 2000 },
1556 { 28, wxDateTime::Oct, 2001 },
1557 { 27, wxDateTime::Oct, 2002 },
1558 { 26, wxDateTime::Oct, 2003 },
1559 { 31, wxDateTime::Oct, 2004 },
1560 }
1561 };
1562
1563 int year;
1564 for ( year = 1990; year < 2005; year++ )
1565 {
1566 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
1567 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
1568
1569 printf("DST period in the US for year %d: from %s to %s",
1570 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
1571
1572 size_t n = year - 1990;
1573 const Date& dBegin = datesDST[0][n];
1574 const Date& dEnd = datesDST[1][n];
1575
1576 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
1577 {
1578 puts(" (ok)");
1579 }
1580 else
1581 {
1582 printf(" (ERROR: should be %s %d to %s %d)\n",
1583 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
1584 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
1585 }
1586 }
1587
1588 puts("");
1589
1590 for ( year = 1990; year < 2005; year++ )
1591 {
1592 printf("DST period in Europe for year %d: from %s to %s\n",
1593 year,
1594 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
1595 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
1596 }
1597 }
1598
1599 // test wxDateTime -> text conversion
1600 static void TestTimeFormat()
1601 {
1602 puts("\n*** wxDateTime formatting test ***");
1603
1604 // some information may be lost during conversion, so store what kind
1605 // of info should we recover after a round trip
1606 enum CompareKind
1607 {
1608 CompareNone, // don't try comparing
1609 CompareBoth, // dates and times should be identical
1610 CompareDate, // dates only
1611 CompareTime // time only
1612 };
1613
1614 static const struct
1615 {
1616 CompareKind compareKind;
1617 const char *format;
1618 } formatTestFormats[] =
1619 {
1620 { CompareBoth, "---> %c" },
1621 { CompareDate, "Date is %A, %d of %B, in year %Y" },
1622 { CompareBoth, "Date is %x, time is %X" },
1623 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
1624 { CompareNone, "The day of year: %j, the week of year: %W" },
1625 };
1626
1627 static const Date formatTestDates[] =
1628 {
1629 { 29, wxDateTime::May, 1976, 18, 30, 00 },
1630 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
1631 #if 0
1632 // this test can't work for other centuries because it uses two digit
1633 // years in formats, so don't even try it
1634 { 29, wxDateTime::May, 2076, 18, 30, 00 },
1635 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
1636 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
1637 #endif
1638 };
1639
1640 // an extra test (as it doesn't depend on date, don't do it in the loop)
1641 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1642
1643 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
1644 {
1645 puts("");
1646
1647 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
1648 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
1649 {
1650 wxString s = dt.Format(formatTestFormats[n].format);
1651 printf("%s", s.c_str());
1652
1653 // what can we recover?
1654 int kind = formatTestFormats[n].compareKind;
1655
1656 // convert back
1657 wxDateTime dt2;
1658 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
1659 if ( !result )
1660 {
1661 // converion failed - should it have?
1662 if ( kind == CompareNone )
1663 puts(" (ok)");
1664 else
1665 puts(" (ERROR: conversion back failed)");
1666 }
1667 else if ( *result )
1668 {
1669 // should have parsed the entire string
1670 puts(" (ERROR: conversion back stopped too soon)");
1671 }
1672 else
1673 {
1674 bool equal = FALSE; // suppress compilaer warning
1675 switch ( kind )
1676 {
1677 case CompareBoth:
1678 equal = dt2 == dt;
1679 break;
1680
1681 case CompareDate:
1682 equal = dt.IsSameDate(dt2);
1683 break;
1684
1685 case CompareTime:
1686 equal = dt.IsSameTime(dt2);
1687 break;
1688 }
1689
1690 if ( !equal )
1691 {
1692 printf(" (ERROR: got back '%s' instead of '%s')\n",
1693 dt2.Format().c_str(), dt.Format().c_str());
1694 }
1695 else
1696 {
1697 puts(" (ok)");
1698 }
1699 }
1700 }
1701 }
1702 }
1703
1704 // test text -> wxDateTime conversion
1705 static void TestTimeParse()
1706 {
1707 puts("\n*** wxDateTime parse test ***");
1708
1709 struct ParseTestData
1710 {
1711 const char *format;
1712 Date date;
1713 bool good;
1714 };
1715
1716 static const ParseTestData parseTestDates[] =
1717 {
1718 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
1719 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
1720 };
1721
1722 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
1723 {
1724 const char *format = parseTestDates[n].format;
1725
1726 printf("%s => ", format);
1727
1728 wxDateTime dt;
1729 if ( dt.ParseRfc822Date(format) )
1730 {
1731 printf("%s ", dt.Format().c_str());
1732
1733 if ( parseTestDates[n].good )
1734 {
1735 wxDateTime dtReal = parseTestDates[n].date.DT();
1736 if ( dt == dtReal )
1737 {
1738 puts("(ok)");
1739 }
1740 else
1741 {
1742 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
1743 }
1744 }
1745 else
1746 {
1747 puts("(ERROR: bad format)");
1748 }
1749 }
1750 else
1751 {
1752 printf("bad format (%s)\n",
1753 parseTestDates[n].good ? "ERROR" : "ok");
1754 }
1755 }
1756 }
1757
1758 static void TestInteractive()
1759 {
1760 puts("\n*** interactive wxDateTime tests ***");
1761
1762 char buf[128];
1763
1764 for ( ;; )
1765 {
1766 printf("Enter a date: ");
1767 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
1768 break;
1769
1770 wxDateTime dt;
1771 if ( !dt.ParseDate(buf) )
1772 {
1773 puts("failed to parse the date");
1774
1775 continue;
1776 }
1777
1778 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1779 dt.FormatISODate().c_str(),
1780 dt.GetDayOfYear(),
1781 dt.GetWeekOfMonth(wxDateTime::Monday_First),
1782 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
1783 dt.GetWeekOfYear(wxDateTime::Monday_First));
1784 }
1785
1786 puts("\n*** done ***");
1787 }
1788
1789 static void TestTimeArithmetics()
1790 {
1791 puts("\n*** testing arithmetic operations on wxDateTime ***");
1792
1793 static const struct
1794 {
1795 wxDateSpan span;
1796 const char *name;
1797 } testArithmData[] =
1798 {
1799 { wxDateSpan::Day(), "day" },
1800 { wxDateSpan::Week(), "week" },
1801 { wxDateSpan::Month(), "month" },
1802 { wxDateSpan::Year(), "year" },
1803 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1804 };
1805
1806 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
1807
1808 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
1809 {
1810 wxDateSpan span = testArithmData[n].span;
1811 dt1 = dt + span;
1812 dt2 = dt - span;
1813
1814 const char *name = testArithmData[n].name;
1815 printf("%s + %s = %s, %s - %s = %s\n",
1816 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
1817 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
1818
1819 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
1820 if ( dt1 - span == dt )
1821 {
1822 puts(" (ok)");
1823 }
1824 else
1825 {
1826 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
1827 }
1828
1829 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
1830 if ( dt2 + span == dt )
1831 {
1832 puts(" (ok)");
1833 }
1834 else
1835 {
1836 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
1837 }
1838
1839 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
1840 if ( dt2 + 2*span == dt1 )
1841 {
1842 puts(" (ok)");
1843 }
1844 else
1845 {
1846 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
1847 }
1848
1849 puts("");
1850 }
1851 }
1852
1853 static void TestTimeHolidays()
1854 {
1855 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1856
1857 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
1858 wxDateTime dtStart(1, tm.mon, tm.year),
1859 dtEnd = dtStart.GetLastMonthDay();
1860
1861 wxDateTimeArray hol;
1862 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
1863
1864 const wxChar *format = "%d-%b-%Y (%a)";
1865
1866 printf("All holidays between %s and %s:\n",
1867 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
1868
1869 size_t count = hol.GetCount();
1870 for ( size_t n = 0; n < count; n++ )
1871 {
1872 printf("\t%s\n", hol[n].Format(format).c_str());
1873 }
1874
1875 puts("");
1876 }
1877
1878 #if 0
1879
1880 // test compatibility with the old wxDate/wxTime classes
1881 static void TestTimeCompatibility()
1882 {
1883 puts("\n*** wxDateTime compatibility test ***");
1884
1885 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1886 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1887
1888 double jdnNow = wxDateTime::Now().GetJDN();
1889 long jdnMidnight = (long)(jdnNow - 0.5);
1890 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
1891
1892 jdnMidnight = wxDate().Set().GetJulianDate();
1893 printf("wxDateTime for today: %s\n",
1894 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
1895
1896 int flags = wxEUROPEAN;//wxFULL;
1897 wxDate date;
1898 date.Set();
1899 printf("Today is %s\n", date.FormatDate(flags).c_str());
1900 for ( int n = 0; n < 7; n++ )
1901 {
1902 printf("Previous %s is %s\n",
1903 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
1904 date.Previous(n + 1).FormatDate(flags).c_str());
1905 }
1906 }
1907
1908 #endif // 0
1909
1910 #endif // TEST_DATETIME
1911
1912 // ----------------------------------------------------------------------------
1913 // threads
1914 // ----------------------------------------------------------------------------
1915
1916 #ifdef TEST_THREADS
1917
1918 #include <wx/thread.h>
1919
1920 static size_t gs_counter = (size_t)-1;
1921 static wxCriticalSection gs_critsect;
1922 static wxCondition gs_cond;
1923
1924 class MyJoinableThread : public wxThread
1925 {
1926 public:
1927 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
1928 { m_n = n; Create(); }
1929
1930 // thread execution starts here
1931 virtual ExitCode Entry();
1932
1933 private:
1934 size_t m_n;
1935 };
1936
1937 wxThread::ExitCode MyJoinableThread::Entry()
1938 {
1939 unsigned long res = 1;
1940 for ( size_t n = 1; n < m_n; n++ )
1941 {
1942 res *= n;
1943
1944 // it's a loooong calculation :-)
1945 Sleep(100);
1946 }
1947
1948 return (ExitCode)res;
1949 }
1950
1951 class MyDetachedThread : public wxThread
1952 {
1953 public:
1954 MyDetachedThread(size_t n, char ch)
1955 {
1956 m_n = n;
1957 m_ch = ch;
1958 m_cancelled = FALSE;
1959
1960 Create();
1961 }
1962
1963 // thread execution starts here
1964 virtual ExitCode Entry();
1965
1966 // and stops here
1967 virtual void OnExit();
1968
1969 private:
1970 size_t m_n; // number of characters to write
1971 char m_ch; // character to write
1972
1973 bool m_cancelled; // FALSE if we exit normally
1974 };
1975
1976 wxThread::ExitCode MyDetachedThread::Entry()
1977 {
1978 {
1979 wxCriticalSectionLocker lock(gs_critsect);
1980 if ( gs_counter == (size_t)-1 )
1981 gs_counter = 1;
1982 else
1983 gs_counter++;
1984 }
1985
1986 for ( size_t n = 0; n < m_n; n++ )
1987 {
1988 if ( TestDestroy() )
1989 {
1990 m_cancelled = TRUE;
1991
1992 break;
1993 }
1994
1995 putchar(m_ch);
1996 fflush(stdout);
1997
1998 wxThread::Sleep(100);
1999 }
2000
2001 return 0;
2002 }
2003
2004 void MyDetachedThread::OnExit()
2005 {
2006 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
2007
2008 wxCriticalSectionLocker lock(gs_critsect);
2009 if ( !--gs_counter && !m_cancelled )
2010 gs_cond.Signal();
2011 }
2012
2013 void TestDetachedThreads()
2014 {
2015 puts("\n*** Testing detached threads ***");
2016
2017 static const size_t nThreads = 3;
2018 MyDetachedThread *threads[nThreads];
2019 size_t n;
2020 for ( n = 0; n < nThreads; n++ )
2021 {
2022 threads[n] = new MyDetachedThread(10, 'A' + n);
2023 }
2024
2025 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
2026 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
2027
2028 for ( n = 0; n < nThreads; n++ )
2029 {
2030 threads[n]->Run();
2031 }
2032
2033 // wait until all threads terminate
2034 gs_cond.Wait();
2035
2036 puts("");
2037 }
2038
2039 void TestJoinableThreads()
2040 {
2041 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2042
2043 // calc 10! in the background
2044 MyJoinableThread thread(10);
2045 thread.Run();
2046
2047 printf("\nThread terminated with exit code %lu.\n",
2048 (unsigned long)thread.Wait());
2049 }
2050
2051 void TestThreadSuspend()
2052 {
2053 puts("\n*** Testing thread suspend/resume functions ***");
2054
2055 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
2056
2057 thread->Run();
2058
2059 // this is for this demo only, in a real life program we'd use another
2060 // condition variable which would be signaled from wxThread::Entry() to
2061 // tell us that the thread really started running - but here just wait a
2062 // bit and hope that it will be enough (the problem is, of course, that
2063 // the thread might still not run when we call Pause() which will result
2064 // in an error)
2065 wxThread::Sleep(300);
2066
2067 for ( size_t n = 0; n < 3; n++ )
2068 {
2069 thread->Pause();
2070
2071 puts("\nThread suspended");
2072 if ( n > 0 )
2073 {
2074 // don't sleep but resume immediately the first time
2075 wxThread::Sleep(300);
2076 }
2077 puts("Going to resume the thread");
2078
2079 thread->Resume();
2080 }
2081
2082 puts("Waiting until it terminates now");
2083
2084 // wait until the thread terminates
2085 gs_cond.Wait();
2086
2087 puts("");
2088 }
2089
2090 void TestThreadDelete()
2091 {
2092 // As above, using Sleep() is only for testing here - we must use some
2093 // synchronisation object instead to ensure that the thread is still
2094 // running when we delete it - deleting a detached thread which already
2095 // terminated will lead to a crash!
2096
2097 puts("\n*** Testing thread delete function ***");
2098
2099 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
2100
2101 thread0->Delete();
2102
2103 puts("\nDeleted a thread which didn't start to run yet.");
2104
2105 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
2106
2107 thread1->Run();
2108
2109 wxThread::Sleep(300);
2110
2111 thread1->Delete();
2112
2113 puts("\nDeleted a running thread.");
2114
2115 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
2116
2117 thread2->Run();
2118
2119 wxThread::Sleep(300);
2120
2121 thread2->Pause();
2122
2123 thread2->Delete();
2124
2125 puts("\nDeleted a sleeping thread.");
2126
2127 MyJoinableThread thread3(20);
2128 thread3.Run();
2129
2130 thread3.Delete();
2131
2132 puts("\nDeleted a joinable thread.");
2133
2134 MyJoinableThread thread4(2);
2135 thread4.Run();
2136
2137 wxThread::Sleep(300);
2138
2139 thread4.Delete();
2140
2141 puts("\nDeleted a joinable thread which already terminated.");
2142
2143 puts("");
2144 }
2145
2146 #endif // TEST_THREADS
2147
2148 // ----------------------------------------------------------------------------
2149 // arrays
2150 // ----------------------------------------------------------------------------
2151
2152 #ifdef TEST_ARRAYS
2153
2154 void PrintArray(const char* name, const wxArrayString& array)
2155 {
2156 printf("Dump of the array '%s'\n", name);
2157
2158 size_t nCount = array.GetCount();
2159 for ( size_t n = 0; n < nCount; n++ )
2160 {
2161 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
2162 }
2163 }
2164
2165 #endif // TEST_ARRAYS
2166
2167 // ----------------------------------------------------------------------------
2168 // strings
2169 // ----------------------------------------------------------------------------
2170
2171 #ifdef TEST_STRINGS
2172
2173 #include "wx/timer.h"
2174 #include "wx/tokenzr.h"
2175
2176 static void TestStringConstruction()
2177 {
2178 puts("*** Testing wxString constructores ***");
2179
2180 #define TEST_CTOR(args, res) \
2181 { \
2182 wxString s args ; \
2183 printf("wxString%s = %s ", #args, s.c_str()); \
2184 if ( s == res ) \
2185 { \
2186 puts("(ok)"); \
2187 } \
2188 else \
2189 { \
2190 printf("(ERROR: should be %s)\n", res); \
2191 } \
2192 }
2193
2194 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2195 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2196 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2197 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2198
2199 static const wxChar *s = _T("?really!");
2200 const wxChar *start = wxStrchr(s, _T('r'));
2201 const wxChar *end = wxStrchr(s, _T('!'));
2202 TEST_CTOR((start, end), _T("really"));
2203
2204 puts("");
2205 }
2206
2207 static void TestString()
2208 {
2209 wxStopWatch sw;
2210
2211 wxString a, b, c;
2212
2213 a.reserve (128);
2214 b.reserve (128);
2215 c.reserve (128);
2216
2217 for (int i = 0; i < 1000000; ++i)
2218 {
2219 a = "Hello";
2220 b = " world";
2221 c = "! How'ya doin'?";
2222 a += b;
2223 a += c;
2224 c = "Hello world! What's up?";
2225 if (c != a)
2226 c = "Doh!";
2227 }
2228
2229 printf ("TestString elapsed time: %ld\n", sw.Time());
2230 }
2231
2232 static void TestPChar()
2233 {
2234 wxStopWatch sw;
2235
2236 char a [128];
2237 char b [128];
2238 char c [128];
2239
2240 for (int i = 0; i < 1000000; ++i)
2241 {
2242 strcpy (a, "Hello");
2243 strcpy (b, " world");
2244 strcpy (c, "! How'ya doin'?");
2245 strcat (a, b);
2246 strcat (a, c);
2247 strcpy (c, "Hello world! What's up?");
2248 if (strcmp (c, a) == 0)
2249 strcpy (c, "Doh!");
2250 }
2251
2252 printf ("TestPChar elapsed time: %ld\n", sw.Time());
2253 }
2254
2255 static void TestStringSub()
2256 {
2257 wxString s("Hello, world!");
2258
2259 puts("*** Testing wxString substring extraction ***");
2260
2261 printf("String = '%s'\n", s.c_str());
2262 printf("Left(5) = '%s'\n", s.Left(5).c_str());
2263 printf("Right(6) = '%s'\n", s.Right(6).c_str());
2264 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2265 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
2266 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
2267 printf("substr(3) = '%s'\n", s.substr(3).c_str());
2268
2269 puts("");
2270 }
2271
2272 static void TestStringFormat()
2273 {
2274 puts("*** Testing wxString formatting ***");
2275
2276 wxString s;
2277 s.Printf("%03d", 18);
2278
2279 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2280 printf("Number 18: %s\n", s.c_str());
2281
2282 puts("");
2283 }
2284
2285 // returns "not found" for npos, value for all others
2286 static wxString PosToString(size_t res)
2287 {
2288 wxString s = res == wxString::npos ? wxString(_T("not found"))
2289 : wxString::Format(_T("%u"), res);
2290 return s;
2291 }
2292
2293 static void TestStringFind()
2294 {
2295 puts("*** Testing wxString find() functions ***");
2296
2297 static const wxChar *strToFind = _T("ell");
2298 static const struct StringFindTest
2299 {
2300 const wxChar *str;
2301 size_t start,
2302 result; // of searching "ell" in str
2303 } findTestData[] =
2304 {
2305 { _T("Well, hello world"), 0, 1 },
2306 { _T("Well, hello world"), 6, 7 },
2307 { _T("Well, hello world"), 9, wxString::npos },
2308 };
2309
2310 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
2311 {
2312 const StringFindTest& ft = findTestData[n];
2313 size_t res = wxString(ft.str).find(strToFind, ft.start);
2314
2315 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2316 strToFind, ft.str, ft.start, PosToString(res).c_str());
2317
2318 size_t resTrue = ft.result;
2319 if ( res == resTrue )
2320 {
2321 puts(_T("(ok)"));
2322 }
2323 else
2324 {
2325 printf(_T("(ERROR: should be %s)\n"),
2326 PosToString(resTrue).c_str());
2327 }
2328 }
2329
2330 puts("");
2331 }
2332
2333 static void TestStringTokenizer()
2334 {
2335 puts("*** Testing wxStringTokenizer ***");
2336
2337 static const wxChar *modeNames[] =
2338 {
2339 _T("default"),
2340 _T("return empty"),
2341 _T("return all empty"),
2342 _T("with delims"),
2343 _T("like strtok"),
2344 };
2345
2346 static const struct StringTokenizerTest
2347 {
2348 const wxChar *str; // string to tokenize
2349 const wxChar *delims; // delimiters to use
2350 size_t count; // count of token
2351 wxStringTokenizerMode mode; // how should we tokenize it
2352 } tokenizerTestData[] =
2353 {
2354 { _T(""), _T(" "), 0 },
2355 { _T("Hello, world"), _T(" "), 2 },
2356 { _T("Hello, world "), _T(" "), 2 },
2357 { _T("Hello, world"), _T(","), 2 },
2358 { _T("Hello, world!"), _T(",!"), 2 },
2359 { _T("Hello,, world!"), _T(",!"), 3 },
2360 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
2361 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2362 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
2363 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
2364 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
2365 { _T("01/02/99"), _T("/-"), 3 },
2366 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
2367 };
2368
2369 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
2370 {
2371 const StringTokenizerTest& tt = tokenizerTestData[n];
2372 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
2373
2374 size_t count = tkz.CountTokens();
2375 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2376 MakePrintable(tt.str).c_str(),
2377 count,
2378 MakePrintable(tt.delims).c_str(),
2379 modeNames[tkz.GetMode()]);
2380 if ( count == tt.count )
2381 {
2382 puts(_T("(ok)"));
2383 }
2384 else
2385 {
2386 printf(_T("(ERROR: should be %u)\n"), tt.count);
2387
2388 continue;
2389 }
2390
2391 // if we emulate strtok(), check that we do it correctly
2392 wxChar *buf, *s, *last;
2393
2394 if ( tkz.GetMode() == wxTOKEN_STRTOK )
2395 {
2396 buf = new wxChar[wxStrlen(tt.str) + 1];
2397 wxStrcpy(buf, tt.str);
2398
2399 s = wxStrtok(buf, tt.delims, &last);
2400 }
2401 else
2402 {
2403 buf = NULL;
2404 }
2405
2406 // now show the tokens themselves
2407 size_t count2 = 0;
2408 while ( tkz.HasMoreTokens() )
2409 {
2410 wxString token = tkz.GetNextToken();
2411
2412 printf(_T("\ttoken %u: '%s'"),
2413 ++count2,
2414 MakePrintable(token).c_str());
2415
2416 if ( buf )
2417 {
2418 if ( token == s )
2419 {
2420 puts(" (ok)");
2421 }
2422 else
2423 {
2424 printf(" (ERROR: should be %s)\n", s);
2425 }
2426
2427 s = wxStrtok(NULL, tt.delims, &last);
2428 }
2429 else
2430 {
2431 // nothing to compare with
2432 puts("");
2433 }
2434 }
2435
2436 if ( count2 != count )
2437 {
2438 puts(_T("\tERROR: token count mismatch"));
2439 }
2440
2441 delete [] buf;
2442 }
2443
2444 puts("");
2445 }
2446
2447 #endif // TEST_STRINGS
2448
2449 // ----------------------------------------------------------------------------
2450 // entry point
2451 // ----------------------------------------------------------------------------
2452
2453 int main(int argc, char **argv)
2454 {
2455 if ( !wxInitialize() )
2456 {
2457 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
2458 }
2459
2460 #ifdef TEST_USLEEP
2461 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2462 wxUsleep(3000);
2463 #endif // TEST_USLEEP
2464
2465 #ifdef TEST_CMDLINE
2466 static const wxCmdLineEntryDesc cmdLineDesc[] =
2467 {
2468 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
2469 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
2470
2471 { wxCMD_LINE_OPTION, "o", "output", "output file" },
2472 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
2473 { wxCMD_LINE_OPTION, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER },
2474 { wxCMD_LINE_OPTION, "d", "date", "output file date", wxCMD_LINE_VAL_DATE },
2475
2476 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
2477 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
2478
2479 { wxCMD_LINE_NONE }
2480 };
2481
2482 wxCmdLineParser parser(cmdLineDesc, argc, argv);
2483
2484 switch ( parser.Parse() )
2485 {
2486 case -1:
2487 wxLogMessage("Help was given, terminating.");
2488 break;
2489
2490 case 0:
2491 ShowCmdLine(parser);
2492 break;
2493
2494 default:
2495 wxLogMessage("Syntax error detected, aborting.");
2496 break;
2497 }
2498 #endif // TEST_CMDLINE
2499
2500 #ifdef TEST_STRINGS
2501 if ( 0 )
2502 {
2503 TestPChar();
2504 TestString();
2505 }
2506 if ( 0 )
2507 {
2508 TestStringConstruction();
2509 TestStringSub();
2510 TestStringFormat();
2511 TestStringFind();
2512 TestStringTokenizer();
2513 }
2514 #endif // TEST_STRINGS
2515
2516 #ifdef TEST_ARRAYS
2517 wxArrayString a1;
2518 a1.Add("tiger");
2519 a1.Add("cat");
2520 a1.Add("lion");
2521 a1.Add("dog");
2522 a1.Add("human");
2523 a1.Add("ape");
2524
2525 puts("*** Initially:");
2526
2527 PrintArray("a1", a1);
2528
2529 wxArrayString a2(a1);
2530 PrintArray("a2", a2);
2531
2532 wxSortedArrayString a3(a1);
2533 PrintArray("a3", a3);
2534
2535 puts("*** After deleting a string from a1");
2536 a1.Remove(2);
2537
2538 PrintArray("a1", a1);
2539 PrintArray("a2", a2);
2540 PrintArray("a3", a3);
2541
2542 puts("*** After reassigning a1 to a2 and a3");
2543 a3 = a2 = a1;
2544 PrintArray("a2", a2);
2545 PrintArray("a3", a3);
2546 #endif // TEST_ARRAYS
2547
2548 #ifdef TEST_DIR
2549 TestDirEnum();
2550 #endif // TEST_DIR
2551
2552 #ifdef TEST_EXECUTE
2553 TestExecute();
2554 #endif // TEST_EXECUTE
2555
2556 #ifdef TEST_FILECONF
2557 TestFileConfRead();
2558 #endif // TEST_FILECONF
2559
2560 #ifdef TEST_LOG
2561 wxString s;
2562 for ( size_t n = 0; n < 8000; n++ )
2563 {
2564 s << (char)('A' + (n % 26));
2565 }
2566
2567 wxString msg;
2568 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
2569
2570 // this one shouldn't be truncated
2571 printf(msg);
2572
2573 // but this one will because log functions use fixed size buffer
2574 // (note that it doesn't need '\n' at the end neither - will be added
2575 // by wxLog anyhow)
2576 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
2577 #endif // TEST_LOG
2578
2579 #ifdef TEST_THREADS
2580 int nCPUs = wxThread::GetCPUCount();
2581 printf("This system has %d CPUs\n", nCPUs);
2582 if ( nCPUs != -1 )
2583 wxThread::SetConcurrency(nCPUs);
2584
2585 if ( argc > 1 && argv[1][0] == 't' )
2586 wxLog::AddTraceMask("thread");
2587
2588 if ( 1 )
2589 TestDetachedThreads();
2590 if ( 1 )
2591 TestJoinableThreads();
2592 if ( 1 )
2593 TestThreadSuspend();
2594 if ( 1 )
2595 TestThreadDelete();
2596
2597 #endif // TEST_THREADS
2598
2599 #ifdef TEST_LONGLONG
2600 // seed pseudo random generator
2601 srand((unsigned)time(NULL));
2602
2603 if ( 0 )
2604 {
2605 TestSpeed();
2606 }
2607 TestMultiplication();
2608 if ( 0 )
2609 {
2610 TestDivision();
2611 TestAddition();
2612 TestLongLongConversion();
2613 TestBitOperations();
2614 }
2615 #endif // TEST_LONGLONG
2616
2617 #ifdef TEST_HASH
2618 TestHash();
2619 #endif // TEST_HASH
2620
2621 #ifdef TEST_MIME
2622 TestMimeEnum();
2623 #endif // TEST_MIME
2624
2625 #ifdef TEST_SOCKETS
2626 if ( 1 )
2627 TestSocketServer();
2628 if ( 0 )
2629 {
2630 TestSocketClient();
2631 TestProtocolFtp();
2632 }
2633 #endif // TEST_SOCKETS
2634
2635 #ifdef TEST_TIMER
2636 TestStopWatch();
2637 #endif // TEST_TIMER
2638
2639 #ifdef TEST_DATETIME
2640 if ( 0 )
2641 {
2642 TestTimeSet();
2643 TestTimeStatic();
2644 TestTimeRange();
2645 TestTimeZones();
2646 TestTimeTicks();
2647 TestTimeJDN();
2648 TestTimeDST();
2649 TestTimeWDays();
2650 TestTimeWNumber();
2651 TestTimeParse();
2652 TestTimeFormat();
2653 TestTimeArithmetics();
2654 }
2655 TestTimeHolidays();
2656 if ( 0 )
2657 TestInteractive();
2658 #endif // TEST_DATETIME
2659
2660 wxUninitialize();
2661
2662 return 0;
2663 }