]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
891c05f4e79342cf899b2514556e19453f5eacb2
[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 <wx/defs.h>
21
22 #if wxUSE_GUI
23 #error "This sample can't be compiled in GUI mode."
24 #endif // wxUSE_GUI
25
26 #include <stdio.h>
27
28 #include <wx/string.h>
29 #include <wx/file.h>
30 #include <wx/app.h>
31
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
34 #ifdef __VISUALC__
35 #pragma hdrstop
36 #endif
37
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
41
42 // what to test (in alphabetic order)?
43
44 //#define TEST_ARRAYS
45 //#define TEST_CHARSET
46 //#define TEST_CMDLINE
47 //#define TEST_DATETIME
48 //#define TEST_DIR
49 //#define TEST_DLLLOADER
50 //#define TEST_ENVIRON
51 //#define TEST_EXECUTE
52 //#define TEST_FILE
53 //#define TEST_FILECONF
54 //#define TEST_FILENAME
55 #define TEST_FILETIME
56 //#define TEST_FTP
57 //#define TEST_HASH
58 //#define TEST_INFO_FUNCTIONS
59 //#define TEST_LIST
60 //#define TEST_LOCALE
61 //#define TEST_LOG
62 //#define TEST_LONGLONG
63 //#define TEST_MIME
64 //#define TEST_PATHLIST
65 //#define TEST_REGCONF
66 //#define TEST_REGEX
67 //#define TEST_REGISTRY
68 //#define TEST_SNGLINST
69 //#define TEST_SOCKETS
70 //#define TEST_STREAMS
71 //#define TEST_STRINGS
72 //#define TEST_THREADS
73 //#define TEST_TIMER
74 //#define TEST_VCARD -- don't enable this (VZ)
75 //#define TEST_WCHAR
76 //#define TEST_ZIP
77 //#define TEST_ZLIB
78
79 #ifdef TEST_SNGLINST
80 #include <wx/snglinst.h>
81 #endif // TEST_SNGLINST
82
83 // ----------------------------------------------------------------------------
84 // test class for container objects
85 // ----------------------------------------------------------------------------
86
87 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
88
89 class Bar // Foo is already taken in the hash test
90 {
91 public:
92 Bar(const wxString& name) : m_name(name) { ms_bars++; }
93 ~Bar() { ms_bars--; }
94
95 static size_t GetNumber() { return ms_bars; }
96
97 const char *GetName() const { return m_name; }
98
99 private:
100 wxString m_name;
101
102 static size_t ms_bars;
103 };
104
105 size_t Bar::ms_bars = 0;
106
107 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
108
109 // ============================================================================
110 // implementation
111 // ============================================================================
112
113 // ----------------------------------------------------------------------------
114 // helper functions
115 // ----------------------------------------------------------------------------
116
117 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
118
119 // replace TABs with \t and CRs with \n
120 static wxString MakePrintable(const wxChar *s)
121 {
122 wxString str(s);
123 (void)str.Replace(_T("\t"), _T("\\t"));
124 (void)str.Replace(_T("\n"), _T("\\n"));
125 (void)str.Replace(_T("\r"), _T("\\r"));
126
127 return str;
128 }
129
130 #endif // MakePrintable() is used
131
132 // ----------------------------------------------------------------------------
133 // wxFontMapper::CharsetToEncoding
134 // ----------------------------------------------------------------------------
135
136 #ifdef TEST_CHARSET
137
138 #include <wx/fontmap.h>
139
140 static void TestCharset()
141 {
142 static const wxChar *charsets[] =
143 {
144 // some vali charsets
145 _T("us-ascii "),
146 _T("iso8859-1 "),
147 _T("iso-8859-12 "),
148 _T("koi8-r "),
149 _T("utf-7 "),
150 _T("cp1250 "),
151 _T("windows-1252"),
152
153 // and now some bogus ones
154 _T(" "),
155 _T("cp1249 "),
156 _T("iso--8859-1 "),
157 _T("iso-8859-19 "),
158 };
159
160 for ( size_t n = 0; n < WXSIZEOF(charsets); n++ )
161 {
162 wxFontEncoding enc = wxTheFontMapper->CharsetToEncoding(charsets[n]);
163 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
164 charsets[n],
165 wxTheFontMapper->GetEncodingName(enc).c_str(),
166 wxTheFontMapper->GetEncodingDescription(enc).c_str());
167 }
168 }
169
170 #endif // TEST_CHARSET
171
172 // ----------------------------------------------------------------------------
173 // wxCmdLineParser
174 // ----------------------------------------------------------------------------
175
176 #ifdef TEST_CMDLINE
177
178 #include <wx/cmdline.h>
179 #include <wx/datetime.h>
180
181 static void ShowCmdLine(const wxCmdLineParser& parser)
182 {
183 wxString s = "Input files: ";
184
185 size_t count = parser.GetParamCount();
186 for ( size_t param = 0; param < count; param++ )
187 {
188 s << parser.GetParam(param) << ' ';
189 }
190
191 s << '\n'
192 << "Verbose:\t" << (parser.Found("v") ? "yes" : "no") << '\n'
193 << "Quiet:\t" << (parser.Found("q") ? "yes" : "no") << '\n';
194
195 wxString strVal;
196 long lVal;
197 wxDateTime dt;
198 if ( parser.Found("o", &strVal) )
199 s << "Output file:\t" << strVal << '\n';
200 if ( parser.Found("i", &strVal) )
201 s << "Input dir:\t" << strVal << '\n';
202 if ( parser.Found("s", &lVal) )
203 s << "Size:\t" << lVal << '\n';
204 if ( parser.Found("d", &dt) )
205 s << "Date:\t" << dt.FormatISODate() << '\n';
206 if ( parser.Found("project_name", &strVal) )
207 s << "Project:\t" << strVal << '\n';
208
209 wxLogMessage(s);
210 }
211
212 #endif // TEST_CMDLINE
213
214 // ----------------------------------------------------------------------------
215 // wxDir
216 // ----------------------------------------------------------------------------
217
218 #ifdef TEST_DIR
219
220 #include <wx/dir.h>
221
222 #ifdef __UNIX__
223 static const wxChar *ROOTDIR = _T("/");
224 static const wxChar *TESTDIR = _T("/usr");
225 #elif defined(__WXMSW__)
226 static const wxChar *ROOTDIR = _T("c:\\");
227 static const wxChar *TESTDIR = _T("d:\\");
228 #else
229 #error "don't know where the root directory is"
230 #endif
231
232 static void TestDirEnumHelper(wxDir& dir,
233 int flags = wxDIR_DEFAULT,
234 const wxString& filespec = wxEmptyString)
235 {
236 wxString filename;
237
238 if ( !dir.IsOpened() )
239 return;
240
241 bool cont = dir.GetFirst(&filename, filespec, flags);
242 while ( cont )
243 {
244 printf("\t%s\n", filename.c_str());
245
246 cont = dir.GetNext(&filename);
247 }
248
249 puts("");
250 }
251
252 static void TestDirEnum()
253 {
254 puts("*** Testing wxDir::GetFirst/GetNext ***");
255
256 wxDir dir(wxGetCwd());
257
258 puts("Enumerating everything in current directory:");
259 TestDirEnumHelper(dir);
260
261 puts("Enumerating really everything in current directory:");
262 TestDirEnumHelper(dir, wxDIR_DEFAULT | wxDIR_DOTDOT);
263
264 puts("Enumerating object files in current directory:");
265 TestDirEnumHelper(dir, wxDIR_DEFAULT, "*.o");
266
267 puts("Enumerating directories in current directory:");
268 TestDirEnumHelper(dir, wxDIR_DIRS);
269
270 puts("Enumerating files in current directory:");
271 TestDirEnumHelper(dir, wxDIR_FILES);
272
273 puts("Enumerating files including hidden in current directory:");
274 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
275
276 dir.Open(ROOTDIR);
277
278 puts("Enumerating everything in root directory:");
279 TestDirEnumHelper(dir, wxDIR_DEFAULT);
280
281 puts("Enumerating directories in root directory:");
282 TestDirEnumHelper(dir, wxDIR_DIRS);
283
284 puts("Enumerating files in root directory:");
285 TestDirEnumHelper(dir, wxDIR_FILES);
286
287 puts("Enumerating files including hidden in root directory:");
288 TestDirEnumHelper(dir, wxDIR_FILES | wxDIR_HIDDEN);
289
290 puts("Enumerating files in non existing directory:");
291 wxDir dirNo("nosuchdir");
292 TestDirEnumHelper(dirNo);
293 }
294
295 class DirPrintTraverser : public wxDirTraverser
296 {
297 public:
298 virtual wxDirTraverseResult OnFile(const wxString& filename)
299 {
300 return wxDIR_CONTINUE;
301 }
302
303 virtual wxDirTraverseResult OnDir(const wxString& dirname)
304 {
305 wxString path, name, ext;
306 wxSplitPath(dirname, &path, &name, &ext);
307
308 if ( !ext.empty() )
309 name << _T('.') << ext;
310
311 wxString indent;
312 for ( const wxChar *p = path.c_str(); *p; p++ )
313 {
314 if ( wxIsPathSeparator(*p) )
315 indent += _T(" ");
316 }
317
318 printf("%s%s\n", indent.c_str(), name.c_str());
319
320 return wxDIR_CONTINUE;
321 }
322 };
323
324 static void TestDirTraverse()
325 {
326 puts("*** Testing wxDir::Traverse() ***");
327
328 // enum all files
329 wxArrayString files;
330 size_t n = wxDir::GetAllFiles(TESTDIR, &files);
331 printf("There are %u files under '%s'\n", n, TESTDIR);
332 if ( n > 1 )
333 {
334 printf("First one is '%s'\n", files[0u].c_str());
335 printf(" last one is '%s'\n", files[n - 1].c_str());
336 }
337
338 // enum again with custom traverser
339 wxDir dir(TESTDIR);
340 DirPrintTraverser traverser;
341 dir.Traverse(traverser, _T(""), wxDIR_DIRS | wxDIR_HIDDEN);
342 }
343
344 #endif // TEST_DIR
345
346 // ----------------------------------------------------------------------------
347 // wxDllLoader
348 // ----------------------------------------------------------------------------
349
350 #ifdef TEST_DLLLOADER
351
352 #include <wx/dynlib.h>
353
354 static void TestDllLoad()
355 {
356 #if defined(__WXMSW__)
357 static const wxChar *LIB_NAME = _T("kernel32.dll");
358 static const wxChar *FUNC_NAME = _T("lstrlenA");
359 #elif defined(__UNIX__)
360 // weird: using just libc.so does *not* work!
361 static const wxChar *LIB_NAME = _T("/lib/libc-2.0.7.so");
362 static const wxChar *FUNC_NAME = _T("strlen");
363 #else
364 #error "don't know how to test wxDllLoader on this platform"
365 #endif
366
367 puts("*** testing wxDllLoader ***\n");
368
369 wxDllType dllHandle = wxDllLoader::LoadLibrary(LIB_NAME);
370 if ( !dllHandle )
371 {
372 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME);
373 }
374 else
375 {
376 typedef int (*strlenType)(char *);
377 strlenType pfnStrlen = (strlenType)wxDllLoader::GetSymbol(dllHandle, FUNC_NAME);
378 if ( !pfnStrlen )
379 {
380 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
381 FUNC_NAME, LIB_NAME);
382 }
383 else
384 {
385 if ( pfnStrlen("foo") != 3 )
386 {
387 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
388 }
389 else
390 {
391 puts("... ok");
392 }
393 }
394
395 wxDllLoader::UnloadLibrary(dllHandle);
396 }
397 }
398
399 #endif // TEST_DLLLOADER
400
401 // ----------------------------------------------------------------------------
402 // wxGet/SetEnv
403 // ----------------------------------------------------------------------------
404
405 #ifdef TEST_ENVIRON
406
407 #include <wx/utils.h>
408
409 static wxString MyGetEnv(const wxString& var)
410 {
411 wxString val;
412 if ( !wxGetEnv(var, &val) )
413 val = _T("<empty>");
414 else
415 val = wxString(_T('\'')) + val + _T('\'');
416
417 return val;
418 }
419
420 static void TestEnvironment()
421 {
422 const wxChar *var = _T("wxTestVar");
423
424 puts("*** testing environment access functions ***");
425
426 printf("Initially getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
427 wxSetEnv(var, _T("value for wxTestVar"));
428 printf("After wxSetEnv: getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
429 wxSetEnv(var, _T("another value"));
430 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
431 wxUnsetEnv(var);
432 printf("After wxUnsetEnv: getenv(%s) = %s\n", var, MyGetEnv(var).c_str());
433 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
434 }
435
436 #endif // TEST_ENVIRON
437
438 // ----------------------------------------------------------------------------
439 // wxExecute
440 // ----------------------------------------------------------------------------
441
442 #ifdef TEST_EXECUTE
443
444 #include <wx/utils.h>
445
446 static void TestExecute()
447 {
448 puts("*** testing wxExecute ***");
449
450 #ifdef __UNIX__
451 #define COMMAND "cat -n ../../Makefile" // "echo hi"
452 #define SHELL_COMMAND "echo hi from shell"
453 #define REDIRECT_COMMAND COMMAND // "date"
454 #elif defined(__WXMSW__)
455 #define COMMAND "command.com -c 'echo hi'"
456 #define SHELL_COMMAND "echo hi"
457 #define REDIRECT_COMMAND COMMAND
458 #else
459 #error "no command to exec"
460 #endif // OS
461
462 printf("Testing wxShell: ");
463 fflush(stdout);
464 if ( wxShell(SHELL_COMMAND) )
465 puts("Ok.");
466 else
467 puts("ERROR.");
468
469 printf("Testing wxExecute: ");
470 fflush(stdout);
471 if ( wxExecute(COMMAND, TRUE /* sync */) == 0 )
472 puts("Ok.");
473 else
474 puts("ERROR.");
475
476 #if 0 // no, it doesn't work (yet?)
477 printf("Testing async wxExecute: ");
478 fflush(stdout);
479 if ( wxExecute(COMMAND) != 0 )
480 puts("Ok (command launched).");
481 else
482 puts("ERROR.");
483 #endif // 0
484
485 printf("Testing wxExecute with redirection:\n");
486 wxArrayString output;
487 if ( wxExecute(REDIRECT_COMMAND, output) != 0 )
488 {
489 puts("ERROR.");
490 }
491 else
492 {
493 size_t count = output.GetCount();
494 for ( size_t n = 0; n < count; n++ )
495 {
496 printf("\t%s\n", output[n].c_str());
497 }
498
499 puts("Ok.");
500 }
501 }
502
503 #endif // TEST_EXECUTE
504
505 // ----------------------------------------------------------------------------
506 // file
507 // ----------------------------------------------------------------------------
508
509 #ifdef TEST_FILE
510
511 #include <wx/file.h>
512 #include <wx/ffile.h>
513 #include <wx/textfile.h>
514
515 static void TestFileRead()
516 {
517 puts("*** wxFile read test ***");
518
519 wxFile file(_T("testdata.fc"));
520 if ( file.IsOpened() )
521 {
522 printf("File length: %lu\n", file.Length());
523
524 puts("File dump:\n----------");
525
526 static const off_t len = 1024;
527 char buf[len];
528 for ( ;; )
529 {
530 off_t nRead = file.Read(buf, len);
531 if ( nRead == wxInvalidOffset )
532 {
533 printf("Failed to read the file.");
534 break;
535 }
536
537 fwrite(buf, nRead, 1, stdout);
538
539 if ( nRead < len )
540 break;
541 }
542
543 puts("----------");
544 }
545 else
546 {
547 printf("ERROR: can't open test file.\n");
548 }
549
550 puts("");
551 }
552
553 static void TestTextFileRead()
554 {
555 puts("*** wxTextFile read test ***");
556
557 wxTextFile file(_T("testdata.fc"));
558 if ( file.Open() )
559 {
560 printf("Number of lines: %u\n", file.GetLineCount());
561 printf("Last line: '%s'\n", file.GetLastLine().c_str());
562
563 wxString s;
564
565 puts("\nDumping the entire file:");
566 for ( s = file.GetFirstLine(); !file.Eof(); s = file.GetNextLine() )
567 {
568 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
569 }
570 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
571
572 puts("\nAnd now backwards:");
573 for ( s = file.GetLastLine();
574 file.GetCurrentLine() != 0;
575 s = file.GetPrevLine() )
576 {
577 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
578 }
579 printf("%6u: %s\n", file.GetCurrentLine() + 1, s.c_str());
580 }
581 else
582 {
583 printf("ERROR: can't open '%s'\n", file.GetName());
584 }
585
586 puts("");
587 }
588
589 static void TestFileCopy()
590 {
591 puts("*** Testing wxCopyFile ***");
592
593 static const wxChar *filename1 = _T("testdata.fc");
594 static const wxChar *filename2 = _T("test2");
595 if ( !wxCopyFile(filename1, filename2) )
596 {
597 puts("ERROR: failed to copy file");
598 }
599 else
600 {
601 wxFFile f1(filename1, "rb"),
602 f2(filename2, "rb");
603
604 if ( !f1.IsOpened() || !f2.IsOpened() )
605 {
606 puts("ERROR: failed to open file(s)");
607 }
608 else
609 {
610 wxString s1, s2;
611 if ( !f1.ReadAll(&s1) || !f2.ReadAll(&s2) )
612 {
613 puts("ERROR: failed to read file(s)");
614 }
615 else
616 {
617 if ( (s1.length() != s2.length()) ||
618 (memcmp(s1.c_str(), s2.c_str(), s1.length()) != 0) )
619 {
620 puts("ERROR: copy error!");
621 }
622 else
623 {
624 puts("File was copied ok.");
625 }
626 }
627 }
628 }
629
630 if ( !wxRemoveFile(filename2) )
631 {
632 puts("ERROR: failed to remove the file");
633 }
634
635 puts("");
636 }
637
638 #endif // TEST_FILE
639
640 // ----------------------------------------------------------------------------
641 // wxFileConfig
642 // ----------------------------------------------------------------------------
643
644 #ifdef TEST_FILECONF
645
646 #include <wx/confbase.h>
647 #include <wx/fileconf.h>
648
649 static const struct FileConfTestData
650 {
651 const wxChar *name; // value name
652 const wxChar *value; // the value from the file
653 } fcTestData[] =
654 {
655 { _T("value1"), _T("one") },
656 { _T("value2"), _T("two") },
657 { _T("novalue"), _T("default") },
658 };
659
660 static void TestFileConfRead()
661 {
662 puts("*** testing wxFileConfig loading/reading ***");
663
664 wxFileConfig fileconf(_T("test"), wxEmptyString,
665 _T("testdata.fc"), wxEmptyString,
666 wxCONFIG_USE_RELATIVE_PATH);
667
668 // test simple reading
669 puts("\nReading config file:");
670 wxString defValue(_T("default")), value;
671 for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
672 {
673 const FileConfTestData& data = fcTestData[n];
674 value = fileconf.Read(data.name, defValue);
675 printf("\t%s = %s ", data.name, value.c_str());
676 if ( value == data.value )
677 {
678 puts("(ok)");
679 }
680 else
681 {
682 printf("(ERROR: should be %s)\n", data.value);
683 }
684 }
685
686 // test enumerating the entries
687 puts("\nEnumerating all root entries:");
688 long dummy;
689 wxString name;
690 bool cont = fileconf.GetFirstEntry(name, dummy);
691 while ( cont )
692 {
693 printf("\t%s = %s\n",
694 name.c_str(),
695 fileconf.Read(name.c_str(), _T("ERROR")).c_str());
696
697 cont = fileconf.GetNextEntry(name, dummy);
698 }
699 }
700
701 #endif // TEST_FILECONF
702
703 // ----------------------------------------------------------------------------
704 // wxFileName
705 // ----------------------------------------------------------------------------
706
707 #ifdef TEST_FILENAME
708
709 #include <wx/filename.h>
710
711 static struct FileNameInfo
712 {
713 const wxChar *fullname;
714 const wxChar *path;
715 const wxChar *name;
716 const wxChar *ext;
717 } filenames[] =
718 {
719 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
720 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
721 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
722 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
723 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
724 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
725 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
726 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
727 };
728
729 static void TestFileNameConstruction()
730 {
731 puts("*** testing wxFileName construction ***");
732
733 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
734 {
735 wxFileName fn(filenames[n].fullname, wxPATH_UNIX);
736
737 printf("Filename: '%s'\t", fn.GetFullPath().c_str());
738 if ( !fn.Normalize(wxPATH_NORM_ALL, _T(""), wxPATH_UNIX) )
739 {
740 puts("ERROR (couldn't be normalized)");
741 }
742 else
743 {
744 printf("normalized: '%s'\n", fn.GetFullPath().c_str());
745 }
746 }
747
748 puts("");
749 }
750
751 static void TestFileNameSplit()
752 {
753 puts("*** testing wxFileName splitting ***");
754
755 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
756 {
757 const FileNameInfo &fni = filenames[n];
758 wxString path, name, ext;
759 wxFileName::SplitPath(fni.fullname, &path, &name, &ext);
760
761 printf("%s -> path = '%s', name = '%s', ext = '%s'",
762 fni.fullname, path.c_str(), name.c_str(), ext.c_str());
763 if ( path != fni.path )
764 printf(" (ERROR: path = '%s')", fni.path);
765 if ( name != fni.name )
766 printf(" (ERROR: name = '%s')", fni.name);
767 if ( ext != fni.ext )
768 printf(" (ERROR: ext = '%s')", fni.ext);
769 puts("");
770 }
771
772 puts("");
773 }
774
775 static void TestFileNameComparison()
776 {
777 // TODO!
778 }
779
780 static void TestFileNameOperations()
781 {
782 // TODO!
783 }
784
785 static void TestFileNameCwd()
786 {
787 // TODO!
788 }
789
790 #endif // TEST_FILENAME
791
792 // ----------------------------------------------------------------------------
793 // wxFileName time functions
794 // ----------------------------------------------------------------------------
795
796 #ifdef TEST_FILETIME
797
798 #include <wx/filename.h>
799 #include <wx/datetime.h>
800
801 static void TestFileGetTimes()
802 {
803 wxFileName fn(_T("testdata.fc"));
804
805 wxDateTime dtAccess, dtMod, dtChange;
806 if ( !fn.GetTimes(&dtAccess, &dtMod, &dtChange) )
807 {
808 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
809 }
810 else
811 {
812 static const wxChar *fmt = _T("%Y-%b-%d %H:%M:%S");
813
814 wxPrintf(_T("File times for '%s':\n"), fn.GetFullPath().c_str());
815 wxPrintf(_T("Access: \t%s\n"), dtAccess.Format(fmt).c_str());
816 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod.Format(fmt).c_str());
817 wxPrintf(_T("Change: \t%s\n"), dtChange.Format(fmt).c_str());
818 }
819 }
820
821 static void TestFileSetTimes()
822 {
823 wxFileName fn(_T("testdata.fc"));
824
825 wxDateTime dtAccess, dtMod, dtChange;
826 if ( !fn.Touch() )
827 {
828 wxPrintf(_T("ERROR: Touch() failed.\n"));
829 }
830 }
831
832 #endif // TEST_FILETIME
833
834 // ----------------------------------------------------------------------------
835 // wxHashTable
836 // ----------------------------------------------------------------------------
837
838 #ifdef TEST_HASH
839
840 #include <wx/hash.h>
841
842 struct Foo
843 {
844 Foo(int n_) { n = n_; count++; }
845 ~Foo() { count--; }
846
847 int n;
848
849 static size_t count;
850 };
851
852 size_t Foo::count = 0;
853
854 WX_DECLARE_LIST(Foo, wxListFoos);
855 WX_DECLARE_HASH(Foo, wxListFoos, wxHashFoos);
856
857 #include <wx/listimpl.cpp>
858
859 WX_DEFINE_LIST(wxListFoos);
860
861 static void TestHash()
862 {
863 puts("*** Testing wxHashTable ***\n");
864
865 {
866 wxHashFoos hash;
867 hash.DeleteContents(TRUE);
868
869 printf("Hash created: %u foos in hash, %u foos totally\n",
870 hash.GetCount(), Foo::count);
871
872 static const int hashTestData[] =
873 {
874 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
875 };
876
877 size_t n;
878 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
879 {
880 hash.Put(hashTestData[n], n, new Foo(n));
881 }
882
883 printf("Hash filled: %u foos in hash, %u foos totally\n",
884 hash.GetCount(), Foo::count);
885
886 puts("Hash access test:");
887 for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
888 {
889 printf("\tGetting element with key %d, value %d: ",
890 hashTestData[n], n);
891 Foo *foo = hash.Get(hashTestData[n], n);
892 if ( !foo )
893 {
894 printf("ERROR, not found.\n");
895 }
896 else
897 {
898 printf("%d (%s)\n", foo->n,
899 (size_t)foo->n == n ? "ok" : "ERROR");
900 }
901 }
902
903 printf("\nTrying to get an element not in hash: ");
904
905 if ( hash.Get(1234) || hash.Get(1, 0) )
906 {
907 puts("ERROR: found!");
908 }
909 else
910 {
911 puts("ok (not found)");
912 }
913 }
914
915 printf("Hash destroyed: %u foos left\n", Foo::count);
916 }
917
918 #endif // TEST_HASH
919
920 // ----------------------------------------------------------------------------
921 // wxList
922 // ----------------------------------------------------------------------------
923
924 #ifdef TEST_LIST
925
926 #include <wx/list.h>
927
928 WX_DECLARE_LIST(Bar, wxListBars);
929 #include <wx/listimpl.cpp>
930 WX_DEFINE_LIST(wxListBars);
931
932 static void TestListCtor()
933 {
934 puts("*** Testing wxList construction ***\n");
935
936 {
937 wxListBars list1;
938 list1.Append(new Bar(_T("first")));
939 list1.Append(new Bar(_T("second")));
940
941 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
942 list1.GetCount(), Bar::GetNumber());
943
944 wxListBars list2;
945 list2 = list1;
946
947 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
948 list1.GetCount(), list2.GetCount(), Bar::GetNumber());
949
950 list1.DeleteContents(TRUE);
951 }
952
953 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
954 }
955
956 #endif // TEST_LIST
957
958 // ----------------------------------------------------------------------------
959 // wxLocale
960 // ----------------------------------------------------------------------------
961
962 #ifdef TEST_LOCALE
963
964 #include "wx/intl.h"
965 #include "wx/utils.h" // for wxSetEnv
966
967 static wxLocale gs_localeDefault(wxLANGUAGE_ENGLISH);
968
969 // find the name of the language from its value
970 static const char *GetLangName(int lang)
971 {
972 static const char *languageNames[] =
973 {
974 "DEFAULT",
975 "UNKNOWN",
976 "ABKHAZIAN",
977 "AFAR",
978 "AFRIKAANS",
979 "ALBANIAN",
980 "AMHARIC",
981 "ARABIC",
982 "ARABIC_ALGERIA",
983 "ARABIC_BAHRAIN",
984 "ARABIC_EGYPT",
985 "ARABIC_IRAQ",
986 "ARABIC_JORDAN",
987 "ARABIC_KUWAIT",
988 "ARABIC_LEBANON",
989 "ARABIC_LIBYA",
990 "ARABIC_MOROCCO",
991 "ARABIC_OMAN",
992 "ARABIC_QATAR",
993 "ARABIC_SAUDI_ARABIA",
994 "ARABIC_SUDAN",
995 "ARABIC_SYRIA",
996 "ARABIC_TUNISIA",
997 "ARABIC_UAE",
998 "ARABIC_YEMEN",
999 "ARMENIAN",
1000 "ASSAMESE",
1001 "AYMARA",
1002 "AZERI",
1003 "AZERI_CYRILLIC",
1004 "AZERI_LATIN",
1005 "BASHKIR",
1006 "BASQUE",
1007 "BELARUSIAN",
1008 "BENGALI",
1009 "BHUTANI",
1010 "BIHARI",
1011 "BISLAMA",
1012 "BRETON",
1013 "BULGARIAN",
1014 "BURMESE",
1015 "CAMBODIAN",
1016 "CATALAN",
1017 "CHINESE",
1018 "CHINESE_SIMPLIFIED",
1019 "CHINESE_TRADITIONAL",
1020 "CHINESE_HONGKONG",
1021 "CHINESE_MACAU",
1022 "CHINESE_SINGAPORE",
1023 "CHINESE_TAIWAN",
1024 "CORSICAN",
1025 "CROATIAN",
1026 "CZECH",
1027 "DANISH",
1028 "DUTCH",
1029 "DUTCH_BELGIAN",
1030 "ENGLISH",
1031 "ENGLISH_UK",
1032 "ENGLISH_US",
1033 "ENGLISH_AUSTRALIA",
1034 "ENGLISH_BELIZE",
1035 "ENGLISH_BOTSWANA",
1036 "ENGLISH_CANADA",
1037 "ENGLISH_CARIBBEAN",
1038 "ENGLISH_DENMARK",
1039 "ENGLISH_EIRE",
1040 "ENGLISH_JAMAICA",
1041 "ENGLISH_NEW_ZEALAND",
1042 "ENGLISH_PHILIPPINES",
1043 "ENGLISH_SOUTH_AFRICA",
1044 "ENGLISH_TRINIDAD",
1045 "ENGLISH_ZIMBABWE",
1046 "ESPERANTO",
1047 "ESTONIAN",
1048 "FAEROESE",
1049 "FARSI",
1050 "FIJI",
1051 "FINNISH",
1052 "FRENCH",
1053 "FRENCH_BELGIAN",
1054 "FRENCH_CANADIAN",
1055 "FRENCH_LUXEMBOURG",
1056 "FRENCH_MONACO",
1057 "FRENCH_SWISS",
1058 "FRISIAN",
1059 "GALICIAN",
1060 "GEORGIAN",
1061 "GERMAN",
1062 "GERMAN_AUSTRIAN",
1063 "GERMAN_BELGIUM",
1064 "GERMAN_LIECHTENSTEIN",
1065 "GERMAN_LUXEMBOURG",
1066 "GERMAN_SWISS",
1067 "GREEK",
1068 "GREENLANDIC",
1069 "GUARANI",
1070 "GUJARATI",
1071 "HAUSA",
1072 "HEBREW",
1073 "HINDI",
1074 "HUNGARIAN",
1075 "ICELANDIC",
1076 "INDONESIAN",
1077 "INTERLINGUA",
1078 "INTERLINGUE",
1079 "INUKTITUT",
1080 "INUPIAK",
1081 "IRISH",
1082 "ITALIAN",
1083 "ITALIAN_SWISS",
1084 "JAPANESE",
1085 "JAVANESE",
1086 "KANNADA",
1087 "KASHMIRI",
1088 "KASHMIRI_INDIA",
1089 "KAZAKH",
1090 "KERNEWEK",
1091 "KINYARWANDA",
1092 "KIRGHIZ",
1093 "KIRUNDI",
1094 "KONKANI",
1095 "KOREAN",
1096 "KURDISH",
1097 "LAOTHIAN",
1098 "LATIN",
1099 "LATVIAN",
1100 "LINGALA",
1101 "LITHUANIAN",
1102 "MACEDONIAN",
1103 "MALAGASY",
1104 "MALAY",
1105 "MALAYALAM",
1106 "MALAY_BRUNEI_DARUSSALAM",
1107 "MALAY_MALAYSIA",
1108 "MALTESE",
1109 "MANIPURI",
1110 "MAORI",
1111 "MARATHI",
1112 "MOLDAVIAN",
1113 "MONGOLIAN",
1114 "NAURU",
1115 "NEPALI",
1116 "NEPALI_INDIA",
1117 "NORWEGIAN_BOKMAL",
1118 "NORWEGIAN_NYNORSK",
1119 "OCCITAN",
1120 "ORIYA",
1121 "OROMO",
1122 "PASHTO",
1123 "POLISH",
1124 "PORTUGUESE",
1125 "PORTUGUESE_BRAZILIAN",
1126 "PUNJABI",
1127 "QUECHUA",
1128 "RHAETO_ROMANCE",
1129 "ROMANIAN",
1130 "RUSSIAN",
1131 "RUSSIAN_UKRAINE",
1132 "SAMOAN",
1133 "SANGHO",
1134 "SANSKRIT",
1135 "SCOTS_GAELIC",
1136 "SERBIAN",
1137 "SERBIAN_CYRILLIC",
1138 "SERBIAN_LATIN",
1139 "SERBO_CROATIAN",
1140 "SESOTHO",
1141 "SETSWANA",
1142 "SHONA",
1143 "SINDHI",
1144 "SINHALESE",
1145 "SISWATI",
1146 "SLOVAK",
1147 "SLOVENIAN",
1148 "SOMALI",
1149 "SPANISH",
1150 "SPANISH_ARGENTINA",
1151 "SPANISH_BOLIVIA",
1152 "SPANISH_CHILE",
1153 "SPANISH_COLOMBIA",
1154 "SPANISH_COSTA_RICA",
1155 "SPANISH_DOMINICAN_REPUBLIC",
1156 "SPANISH_ECUADOR",
1157 "SPANISH_EL_SALVADOR",
1158 "SPANISH_GUATEMALA",
1159 "SPANISH_HONDURAS",
1160 "SPANISH_MEXICAN",
1161 "SPANISH_MODERN",
1162 "SPANISH_NICARAGUA",
1163 "SPANISH_PANAMA",
1164 "SPANISH_PARAGUAY",
1165 "SPANISH_PERU",
1166 "SPANISH_PUERTO_RICO",
1167 "SPANISH_URUGUAY",
1168 "SPANISH_US",
1169 "SPANISH_VENEZUELA",
1170 "SUNDANESE",
1171 "SWAHILI",
1172 "SWEDISH",
1173 "SWEDISH_FINLAND",
1174 "TAGALOG",
1175 "TAJIK",
1176 "TAMIL",
1177 "TATAR",
1178 "TELUGU",
1179 "THAI",
1180 "TIBETAN",
1181 "TIGRINYA",
1182 "TONGA",
1183 "TSONGA",
1184 "TURKISH",
1185 "TURKMEN",
1186 "TWI",
1187 "UIGHUR",
1188 "UKRAINIAN",
1189 "URDU",
1190 "URDU_INDIA",
1191 "URDU_PAKISTAN",
1192 "UZBEK",
1193 "UZBEK_CYRILLIC",
1194 "UZBEK_LATIN",
1195 "VIETNAMESE",
1196 "VOLAPUK",
1197 "WELSH",
1198 "WOLOF",
1199 "XHOSA",
1200 "YIDDISH",
1201 "YORUBA",
1202 "ZHUANG",
1203 "ZULU",
1204 };
1205
1206 if ( (size_t)lang < WXSIZEOF(languageNames) )
1207 return languageNames[lang];
1208 else
1209 return "INVALID";
1210 }
1211
1212 static void TestDefaultLang()
1213 {
1214 puts("*** Testing wxLocale::GetSystemLanguage ***");
1215
1216 static const wxChar *langStrings[] =
1217 {
1218 NULL, // system default
1219 _T("C"),
1220 _T("fr"),
1221 _T("fr_FR"),
1222 _T("en"),
1223 _T("en_GB"),
1224 _T("en_US"),
1225 _T("de_DE.iso88591"),
1226 _T("german"),
1227 _T("?"), // invalid lang spec
1228 _T("klingonese"), // I bet on some systems it does exist...
1229 };
1230
1231 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1232 wxLocale::GetSystemEncodingName().c_str(),
1233 wxLocale::GetSystemEncoding());
1234
1235 for ( size_t n = 0; n < WXSIZEOF(langStrings); n++ )
1236 {
1237 const char *langStr = langStrings[n];
1238 if ( langStr )
1239 {
1240 // FIXME: this doesn't do anything at all under Windows, we need
1241 // to create a new wxLocale!
1242 wxSetEnv(_T("LC_ALL"), langStr);
1243 }
1244
1245 int lang = gs_localeDefault.GetSystemLanguage();
1246 printf("Locale for '%s' is %s.\n",
1247 langStr ? langStr : "system default", GetLangName(lang));
1248 }
1249 }
1250
1251 #endif // TEST_LOCALE
1252
1253 // ----------------------------------------------------------------------------
1254 // MIME types
1255 // ----------------------------------------------------------------------------
1256
1257 #ifdef TEST_MIME
1258
1259 #include <wx/mimetype.h>
1260
1261 static void TestMimeEnum()
1262 {
1263 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1264
1265 wxArrayString mimetypes;
1266
1267 size_t count = wxTheMimeTypesManager->EnumAllFileTypes(mimetypes);
1268
1269 printf("*** All %u known filetypes: ***\n", count);
1270
1271 wxArrayString exts;
1272 wxString desc;
1273
1274 for ( size_t n = 0; n < count; n++ )
1275 {
1276 wxFileType *filetype =
1277 wxTheMimeTypesManager->GetFileTypeFromMimeType(mimetypes[n]);
1278 if ( !filetype )
1279 {
1280 printf("nothing known about the filetype '%s'!\n",
1281 mimetypes[n].c_str());
1282 continue;
1283 }
1284
1285 filetype->GetDescription(&desc);
1286 filetype->GetExtensions(exts);
1287
1288 filetype->GetIcon(NULL);
1289
1290 wxString extsAll;
1291 for ( size_t e = 0; e < exts.GetCount(); e++ )
1292 {
1293 if ( e > 0 )
1294 extsAll << _T(", ");
1295 extsAll += exts[e];
1296 }
1297
1298 printf("\t%s: %s (%s)\n",
1299 mimetypes[n].c_str(), desc.c_str(), extsAll.c_str());
1300 }
1301
1302 puts("");
1303 }
1304
1305 static void TestMimeOverride()
1306 {
1307 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1308
1309 static const wxChar *mailcap = _T("/tmp/mailcap");
1310 static const wxChar *mimetypes = _T("/tmp/mime.types");
1311
1312 if ( wxFile::Exists(mailcap) )
1313 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1314 mailcap,
1315 wxTheMimeTypesManager->ReadMailcap(mailcap) ? _T("ok") : _T("ERROR"));
1316 else
1317 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1318 mailcap);
1319
1320 if ( wxFile::Exists(mimetypes) )
1321 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1322 mimetypes,
1323 wxTheMimeTypesManager->ReadMimeTypes(mimetypes) ? _T("ok") : _T("ERROR"));
1324 else
1325 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1326 mimetypes);
1327
1328 puts("");
1329 }
1330
1331 static void TestMimeFilename()
1332 {
1333 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1334
1335 static const wxChar *filenames[] =
1336 {
1337 _T("readme.txt"),
1338 _T("document.pdf"),
1339 _T("image.gif"),
1340 };
1341
1342 for ( size_t n = 0; n < WXSIZEOF(filenames); n++ )
1343 {
1344 const wxString fname = filenames[n];
1345 wxString ext = fname.AfterLast(_T('.'));
1346 wxFileType *ft = wxTheMimeTypesManager->GetFileTypeFromExtension(ext);
1347 if ( !ft )
1348 {
1349 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext.c_str());
1350 }
1351 else
1352 {
1353 wxString desc;
1354 if ( !ft->GetDescription(&desc) )
1355 desc = _T("<no description>");
1356
1357 wxString cmd;
1358 if ( !ft->GetOpenCommand(&cmd,
1359 wxFileType::MessageParameters(fname, _T(""))) )
1360 cmd = _T("<no command available>");
1361
1362 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1363 fname.c_str(), desc.c_str(), cmd.c_str());
1364
1365 delete ft;
1366 }
1367 }
1368
1369 puts("");
1370 }
1371
1372 static void TestMimeAssociate()
1373 {
1374 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1375
1376 wxFileTypeInfo ftInfo(
1377 _T("application/x-xyz"),
1378 _T("xyzview '%s'"), // open cmd
1379 _T(""), // print cmd
1380 _T("XYZ File") // description
1381 _T(".xyz"), // extensions
1382 NULL // end of extensions
1383 );
1384 ftInfo.SetShortDesc(_T("XYZFile")); // used under Win32 only
1385
1386 wxFileType *ft = wxTheMimeTypesManager->Associate(ftInfo);
1387 if ( !ft )
1388 {
1389 wxPuts(_T("ERROR: failed to create association!"));
1390 }
1391 else
1392 {
1393 // TODO: read it back
1394 delete ft;
1395 }
1396
1397 puts("");
1398 }
1399
1400 #endif // TEST_MIME
1401
1402 // ----------------------------------------------------------------------------
1403 // misc information functions
1404 // ----------------------------------------------------------------------------
1405
1406 #ifdef TEST_INFO_FUNCTIONS
1407
1408 #include <wx/utils.h>
1409
1410 static void TestDiskInfo()
1411 {
1412 puts("*** Testing wxGetDiskSpace() ***");
1413
1414 for ( ;; )
1415 {
1416 char pathname[128];
1417 printf("\nEnter a directory name: ");
1418 if ( !fgets(pathname, WXSIZEOF(pathname), stdin) )
1419 break;
1420
1421 // kill the last '\n'
1422 pathname[strlen(pathname) - 1] = 0;
1423
1424 wxLongLong total, free;
1425 if ( !wxGetDiskSpace(pathname, &total, &free) )
1426 {
1427 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1428 }
1429 else
1430 {
1431 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1432 (total / 1024).ToString().c_str(),
1433 (free / 1024).ToString().c_str(),
1434 pathname);
1435 }
1436 }
1437 }
1438
1439 static void TestOsInfo()
1440 {
1441 puts("*** Testing OS info functions ***\n");
1442
1443 int major, minor;
1444 wxGetOsVersion(&major, &minor);
1445 printf("Running under: %s, version %d.%d\n",
1446 wxGetOsDescription().c_str(), major, minor);
1447
1448 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1449
1450 printf("Host name is %s (%s).\n",
1451 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1452
1453 puts("");
1454 }
1455
1456 static void TestUserInfo()
1457 {
1458 puts("*** Testing user info functions ***\n");
1459
1460 printf("User id is:\t%s\n", wxGetUserId().c_str());
1461 printf("User name is:\t%s\n", wxGetUserName().c_str());
1462 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1463 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1464
1465 puts("");
1466 }
1467
1468 #endif // TEST_INFO_FUNCTIONS
1469
1470 // ----------------------------------------------------------------------------
1471 // long long
1472 // ----------------------------------------------------------------------------
1473
1474 #ifdef TEST_LONGLONG
1475
1476 #include <wx/longlong.h>
1477 #include <wx/timer.h>
1478
1479 // make a 64 bit number from 4 16 bit ones
1480 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1481
1482 // get a random 64 bit number
1483 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1484
1485 static const long testLongs[] =
1486 {
1487 0,
1488 1,
1489 -1,
1490 LONG_MAX,
1491 LONG_MIN,
1492 0x1234,
1493 -0x1234
1494 };
1495
1496 #if wxUSE_LONGLONG_WX
1497 inline bool operator==(const wxLongLongWx& a, const wxLongLongNative& b)
1498 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
1499 inline bool operator==(const wxLongLongNative& a, const wxLongLongWx& b)
1500 { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
1501 #endif // wxUSE_LONGLONG_WX
1502
1503 static void TestSpeed()
1504 {
1505 static const long max = 100000000;
1506 long n;
1507
1508 {
1509 wxStopWatch sw;
1510
1511 long l = 0;
1512 for ( n = 0; n < max; n++ )
1513 {
1514 l += n;
1515 }
1516
1517 printf("Summing longs took %ld milliseconds.\n", sw.Time());
1518 }
1519
1520 #if wxUSE_LONGLONG_NATIVE
1521 {
1522 wxStopWatch sw;
1523
1524 wxLongLong_t l = 0;
1525 for ( n = 0; n < max; n++ )
1526 {
1527 l += n;
1528 }
1529
1530 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw.Time());
1531 }
1532 #endif // wxUSE_LONGLONG_NATIVE
1533
1534 {
1535 wxStopWatch sw;
1536
1537 wxLongLong l;
1538 for ( n = 0; n < max; n++ )
1539 {
1540 l += n;
1541 }
1542
1543 printf("Summing wxLongLongs took %ld milliseconds.\n", sw.Time());
1544 }
1545 }
1546
1547 static void TestLongLongConversion()
1548 {
1549 puts("*** Testing wxLongLong conversions ***\n");
1550
1551 wxLongLong a;
1552 size_t nTested = 0;
1553 for ( size_t n = 0; n < 100000; n++ )
1554 {
1555 a = RAND_LL();
1556
1557 #if wxUSE_LONGLONG_NATIVE
1558 wxLongLongNative b(a.GetHi(), a.GetLo());
1559
1560 wxASSERT_MSG( a == b, "conversions failure" );
1561 #else
1562 puts("Can't do it without native long long type, test skipped.");
1563
1564 return;
1565 #endif // wxUSE_LONGLONG_NATIVE
1566
1567 if ( !(nTested % 1000) )
1568 {
1569 putchar('.');
1570 fflush(stdout);
1571 }
1572
1573 nTested++;
1574 }
1575
1576 puts(" done!");
1577 }
1578
1579 static void TestMultiplication()
1580 {
1581 puts("*** Testing wxLongLong multiplication ***\n");
1582
1583 wxLongLong a, b;
1584 size_t nTested = 0;
1585 for ( size_t n = 0; n < 100000; n++ )
1586 {
1587 a = RAND_LL();
1588 b = RAND_LL();
1589
1590 #if wxUSE_LONGLONG_NATIVE
1591 wxLongLongNative aa(a.GetHi(), a.GetLo());
1592 wxLongLongNative bb(b.GetHi(), b.GetLo());
1593
1594 wxASSERT_MSG( a*b == aa*bb, "multiplication failure" );
1595 #else // !wxUSE_LONGLONG_NATIVE
1596 puts("Can't do it without native long long type, test skipped.");
1597
1598 return;
1599 #endif // wxUSE_LONGLONG_NATIVE
1600
1601 if ( !(nTested % 1000) )
1602 {
1603 putchar('.');
1604 fflush(stdout);
1605 }
1606
1607 nTested++;
1608 }
1609
1610 puts(" done!");
1611 }
1612
1613 static void TestDivision()
1614 {
1615 puts("*** Testing wxLongLong division ***\n");
1616
1617 wxLongLong q, r;
1618 size_t nTested = 0;
1619 for ( size_t n = 0; n < 100000; n++ )
1620 {
1621 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1622 // multiplication will not overflow)
1623 wxLongLong ll = MAKE_LL((rand() >> 12), rand(), rand(), rand());
1624
1625 // get a random long (not wxLongLong for now) to divide it with
1626 long l = rand();
1627 q = ll / l;
1628 r = ll % l;
1629
1630 #if wxUSE_LONGLONG_NATIVE
1631 wxLongLongNative m(ll.GetHi(), ll.GetLo());
1632
1633 wxLongLongNative p = m / l, s = m % l;
1634 wxASSERT_MSG( q == p && r == s, "division failure" );
1635 #else // !wxUSE_LONGLONG_NATIVE
1636 // verify the result
1637 wxASSERT_MSG( ll == q*l + r, "division failure" );
1638 #endif // wxUSE_LONGLONG_NATIVE
1639
1640 if ( !(nTested % 1000) )
1641 {
1642 putchar('.');
1643 fflush(stdout);
1644 }
1645
1646 nTested++;
1647 }
1648
1649 puts(" done!");
1650 }
1651
1652 static void TestAddition()
1653 {
1654 puts("*** Testing wxLongLong addition ***\n");
1655
1656 wxLongLong a, b, c;
1657 size_t nTested = 0;
1658 for ( size_t n = 0; n < 100000; n++ )
1659 {
1660 a = RAND_LL();
1661 b = RAND_LL();
1662 c = a + b;
1663
1664 #if wxUSE_LONGLONG_NATIVE
1665 wxASSERT_MSG( c == wxLongLongNative(a.GetHi(), a.GetLo()) +
1666 wxLongLongNative(b.GetHi(), b.GetLo()),
1667 "addition failure" );
1668 #else // !wxUSE_LONGLONG_NATIVE
1669 wxASSERT_MSG( c - b == a, "addition failure" );
1670 #endif // wxUSE_LONGLONG_NATIVE
1671
1672 if ( !(nTested % 1000) )
1673 {
1674 putchar('.');
1675 fflush(stdout);
1676 }
1677
1678 nTested++;
1679 }
1680
1681 puts(" done!");
1682 }
1683
1684 static void TestBitOperations()
1685 {
1686 puts("*** Testing wxLongLong bit operation ***\n");
1687
1688 wxLongLong ll;
1689 size_t nTested = 0;
1690 for ( size_t n = 0; n < 100000; n++ )
1691 {
1692 ll = RAND_LL();
1693
1694 #if wxUSE_LONGLONG_NATIVE
1695 for ( size_t n = 0; n < 33; n++ )
1696 {
1697 }
1698 #else // !wxUSE_LONGLONG_NATIVE
1699 puts("Can't do it without native long long type, test skipped.");
1700
1701 return;
1702 #endif // wxUSE_LONGLONG_NATIVE
1703
1704 if ( !(nTested % 1000) )
1705 {
1706 putchar('.');
1707 fflush(stdout);
1708 }
1709
1710 nTested++;
1711 }
1712
1713 puts(" done!");
1714 }
1715
1716 static void TestLongLongComparison()
1717 {
1718 #if wxUSE_LONGLONG_WX
1719 puts("*** Testing wxLongLong comparison ***\n");
1720
1721 static const long ls[2] =
1722 {
1723 0x1234,
1724 -0x1234,
1725 };
1726
1727 wxLongLongWx lls[2];
1728 lls[0] = ls[0];
1729 lls[1] = ls[1];
1730
1731 for ( size_t n = 0; n < WXSIZEOF(testLongs); n++ )
1732 {
1733 bool res;
1734
1735 for ( size_t m = 0; m < WXSIZEOF(lls); m++ )
1736 {
1737 res = lls[m] > testLongs[n];
1738 printf("0x%lx > 0x%lx is %s (%s)\n",
1739 ls[m], testLongs[n], res ? "true" : "false",
1740 res == (ls[m] > testLongs[n]) ? "ok" : "ERROR");
1741
1742 res = lls[m] < testLongs[n];
1743 printf("0x%lx < 0x%lx is %s (%s)\n",
1744 ls[m], testLongs[n], res ? "true" : "false",
1745 res == (ls[m] < testLongs[n]) ? "ok" : "ERROR");
1746
1747 res = lls[m] == testLongs[n];
1748 printf("0x%lx == 0x%lx is %s (%s)\n",
1749 ls[m], testLongs[n], res ? "true" : "false",
1750 res == (ls[m] == testLongs[n]) ? "ok" : "ERROR");
1751 }
1752 }
1753 #endif // wxUSE_LONGLONG_WX
1754 }
1755
1756 static void TestLongLongPrint()
1757 {
1758 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1759
1760 for ( size_t n = 0; n < WXSIZEOF(testLongs); n++ )
1761 {
1762 wxLongLong ll = testLongs[n];
1763 wxPrintf(_T("%ld == %s\n"), testLongs[n], ll.ToString().c_str());
1764 }
1765
1766 wxLongLong ll(0x12345678, 0x87654321);
1767 wxPrintf(_T("0x1234567887654321 = %s\n"), ll.ToString().c_str());
1768
1769 ll.Negate();
1770 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll.ToString().c_str());
1771 }
1772
1773 #undef MAKE_LL
1774 #undef RAND_LL
1775
1776 #endif // TEST_LONGLONG
1777
1778 // ----------------------------------------------------------------------------
1779 // path list
1780 // ----------------------------------------------------------------------------
1781
1782 #ifdef TEST_PATHLIST
1783
1784 static void TestPathList()
1785 {
1786 puts("*** Testing wxPathList ***\n");
1787
1788 wxPathList pathlist;
1789 pathlist.AddEnvList("PATH");
1790 wxString path = pathlist.FindValidPath("ls");
1791 if ( path.empty() )
1792 {
1793 printf("ERROR: command not found in the path.\n");
1794 }
1795 else
1796 {
1797 printf("Command found in the path as '%s'.\n", path.c_str());
1798 }
1799 }
1800
1801 #endif // TEST_PATHLIST
1802
1803 // ----------------------------------------------------------------------------
1804 // regular expressions
1805 // ----------------------------------------------------------------------------
1806
1807 #ifdef TEST_REGEX
1808
1809 #include <wx/regex.h>
1810
1811 static void TestRegExCompile()
1812 {
1813 wxPuts(_T("*** Testing RE compilation ***\n"));
1814
1815 static struct RegExCompTestData
1816 {
1817 const wxChar *pattern;
1818 bool correct;
1819 } regExCompTestData[] =
1820 {
1821 { _T("foo"), TRUE },
1822 { _T("foo("), FALSE },
1823 { _T("foo(bar"), FALSE },
1824 { _T("foo(bar)"), TRUE },
1825 { _T("foo["), FALSE },
1826 { _T("foo[bar"), FALSE },
1827 { _T("foo[bar]"), TRUE },
1828 { _T("foo{"), TRUE },
1829 { _T("foo{1"), FALSE },
1830 { _T("foo{bar"), TRUE },
1831 { _T("foo{1}"), TRUE },
1832 { _T("foo{1,2}"), TRUE },
1833 { _T("foo{bar}"), TRUE },
1834 { _T("foo*"), TRUE },
1835 { _T("foo**"), FALSE },
1836 { _T("foo+"), TRUE },
1837 { _T("foo++"), FALSE },
1838 { _T("foo?"), TRUE },
1839 { _T("foo??"), FALSE },
1840 { _T("foo?+"), FALSE },
1841 };
1842
1843 wxRegEx re;
1844 for ( size_t n = 0; n < WXSIZEOF(regExCompTestData); n++ )
1845 {
1846 const RegExCompTestData& data = regExCompTestData[n];
1847 bool ok = re.Compile(data.pattern);
1848
1849 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1850 data.pattern,
1851 ok ? _T("") : _T("not "),
1852 ok == data.correct ? _T("ok") : _T("ERROR"));
1853 }
1854 }
1855
1856 static void TestRegExMatch()
1857 {
1858 wxPuts(_T("*** Testing RE matching ***\n"));
1859
1860 static struct RegExMatchTestData
1861 {
1862 const wxChar *pattern;
1863 const wxChar *text;
1864 bool correct;
1865 } regExMatchTestData[] =
1866 {
1867 { _T("foo"), _T("bar"), FALSE },
1868 { _T("foo"), _T("foobar"), TRUE },
1869 { _T("^foo"), _T("foobar"), TRUE },
1870 { _T("^foo"), _T("barfoo"), FALSE },
1871 { _T("bar$"), _T("barbar"), TRUE },
1872 { _T("bar$"), _T("barbar "), FALSE },
1873 };
1874
1875 for ( size_t n = 0; n < WXSIZEOF(regExMatchTestData); n++ )
1876 {
1877 const RegExMatchTestData& data = regExMatchTestData[n];
1878
1879 wxRegEx re(data.pattern);
1880 bool ok = re.Matches(data.text);
1881
1882 wxPrintf(_T("'%s' %s %s (%s)\n"),
1883 data.pattern,
1884 ok ? _T("matches") : _T("doesn't match"),
1885 data.text,
1886 ok == data.correct ? _T("ok") : _T("ERROR"));
1887 }
1888 }
1889
1890 static void TestRegExSubmatch()
1891 {
1892 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1893
1894 wxRegEx re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1895 if ( !re.IsValid() )
1896 {
1897 wxPuts(_T("ERROR: compilation failed."));
1898 return;
1899 }
1900
1901 wxString text = _T("Fri Jul 13 18:37:52 CEST 2001");
1902
1903 if ( !re.Matches(text) )
1904 {
1905 wxPuts(_T("ERROR: match expected."));
1906 }
1907 else
1908 {
1909 wxPrintf(_T("Entire match: %s\n"), re.GetMatch(text).c_str());
1910
1911 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1912 re.GetMatch(text, 3).c_str(),
1913 re.GetMatch(text, 2).c_str(),
1914 re.GetMatch(text, 4).c_str(),
1915 re.GetMatch(text, 1).c_str());
1916 }
1917 }
1918
1919 static void TestRegExReplacement()
1920 {
1921 wxPuts(_T("*** Testing RE replacement ***"));
1922
1923 static struct RegExReplTestData
1924 {
1925 const wxChar *text;
1926 const wxChar *repl;
1927 const wxChar *result;
1928 size_t count;
1929 } regExReplTestData[] =
1930 {
1931 { _T("foo123"), _T("bar"), _T("bar"), 1 },
1932 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
1933 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
1934 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
1935 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
1936 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
1937 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
1938 };
1939
1940 const wxChar *pattern = _T("([a-z]+)[^0-9]*([0-9]+)");
1941 wxRegEx re = pattern;
1942
1943 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern);
1944
1945 for ( size_t n = 0; n < WXSIZEOF(regExReplTestData); n++ )
1946 {
1947 const RegExReplTestData& data = regExReplTestData[n];
1948
1949 wxString text = data.text;
1950 size_t nRepl = re.Replace(&text, data.repl);
1951
1952 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
1953 data.text, data.repl,
1954 nRepl, nRepl == 1 ? _T("") : _T("es"),
1955 text.c_str());
1956 if ( text == data.result && nRepl == data.count )
1957 {
1958 wxPuts(_T("ok)"));
1959 }
1960 else
1961 {
1962 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
1963 data.count, data.result);
1964 }
1965 }
1966 }
1967
1968 static void TestRegExInteractive()
1969 {
1970 wxPuts(_T("*** Testing RE interactively ***"));
1971
1972 for ( ;; )
1973 {
1974 char pattern[128];
1975 printf("\nEnter a pattern: ");
1976 if ( !fgets(pattern, WXSIZEOF(pattern), stdin) )
1977 break;
1978
1979 // kill the last '\n'
1980 pattern[strlen(pattern) - 1] = 0;
1981
1982 wxRegEx re;
1983 if ( !re.Compile(pattern) )
1984 {
1985 continue;
1986 }
1987
1988 char text[128];
1989 for ( ;; )
1990 {
1991 printf("Enter text to match: ");
1992 if ( !fgets(text, WXSIZEOF(text), stdin) )
1993 break;
1994
1995 // kill the last '\n'
1996 text[strlen(text) - 1] = 0;
1997
1998 if ( !re.Matches(text) )
1999 {
2000 printf("No match.\n");
2001 }
2002 else
2003 {
2004 printf("Pattern matches at '%s'\n", re.GetMatch(text).c_str());
2005
2006 size_t start, len;
2007 for ( size_t n = 1; ; n++ )
2008 {
2009 if ( !re.GetMatch(&start, &len, n) )
2010 {
2011 break;
2012 }
2013
2014 printf("Subexpr %u matched '%s'\n",
2015 n, wxString(text + start, len).c_str());
2016 }
2017 }
2018 }
2019 }
2020 }
2021
2022 #endif // TEST_REGEX
2023
2024 // ----------------------------------------------------------------------------
2025 // registry and related stuff
2026 // ----------------------------------------------------------------------------
2027
2028 // this is for MSW only
2029 #ifndef __WXMSW__
2030 #undef TEST_REGCONF
2031 #undef TEST_REGISTRY
2032 #endif
2033
2034 #ifdef TEST_REGCONF
2035
2036 #include <wx/confbase.h>
2037 #include <wx/msw/regconf.h>
2038
2039 static void TestRegConfWrite()
2040 {
2041 wxRegConfig regconf(_T("console"), _T("wxwindows"));
2042 regconf.Write(_T("Hello"), wxString(_T("world")));
2043 }
2044
2045 #endif // TEST_REGCONF
2046
2047 #ifdef TEST_REGISTRY
2048
2049 #include <wx/msw/registry.h>
2050
2051 // I chose this one because I liked its name, but it probably only exists under
2052 // NT
2053 static const wxChar *TESTKEY =
2054 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2055
2056 static void TestRegistryRead()
2057 {
2058 puts("*** testing registry reading ***");
2059
2060 wxRegKey key(TESTKEY);
2061 printf("The test key name is '%s'.\n", key.GetName().c_str());
2062 if ( !key.Open() )
2063 {
2064 puts("ERROR: test key can't be opened, aborting test.");
2065
2066 return;
2067 }
2068
2069 size_t nSubKeys, nValues;
2070 if ( key.GetKeyInfo(&nSubKeys, NULL, &nValues, NULL) )
2071 {
2072 printf("It has %u subkeys and %u values.\n", nSubKeys, nValues);
2073 }
2074
2075 printf("Enumerating values:\n");
2076
2077 long dummy;
2078 wxString value;
2079 bool cont = key.GetFirstValue(value, dummy);
2080 while ( cont )
2081 {
2082 printf("Value '%s': type ", value.c_str());
2083 switch ( key.GetValueType(value) )
2084 {
2085 case wxRegKey::Type_None: printf("ERROR (none)"); break;
2086 case wxRegKey::Type_String: printf("SZ"); break;
2087 case wxRegKey::Type_Expand_String: printf("EXPAND_SZ"); break;
2088 case wxRegKey::Type_Binary: printf("BINARY"); break;
2089 case wxRegKey::Type_Dword: printf("DWORD"); break;
2090 case wxRegKey::Type_Multi_String: printf("MULTI_SZ"); break;
2091 default: printf("other (unknown)"); break;
2092 }
2093
2094 printf(", value = ");
2095 if ( key.IsNumericValue(value) )
2096 {
2097 long val;
2098 key.QueryValue(value, &val);
2099 printf("%ld", val);
2100 }
2101 else // string
2102 {
2103 wxString val;
2104 key.QueryValue(value, val);
2105 printf("'%s'", val.c_str());
2106
2107 key.QueryRawValue(value, val);
2108 printf(" (raw value '%s')", val.c_str());
2109 }
2110
2111 putchar('\n');
2112
2113 cont = key.GetNextValue(value, dummy);
2114 }
2115 }
2116
2117 static void TestRegistryAssociation()
2118 {
2119 /*
2120 The second call to deleteself genertaes an error message, with a
2121 messagebox saying .flo is crucial to system operation, while the .ddf
2122 call also fails, but with no error message
2123 */
2124
2125 wxRegKey key;
2126
2127 key.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2128 key.Create();
2129 key = "ddxf_auto_file" ;
2130 key.SetName("HKEY_CLASSES_ROOT\\.flo" );
2131 key.Create();
2132 key = "ddxf_auto_file" ;
2133 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2134 key.Create();
2135 key = "program,0" ;
2136 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2137 key.Create();
2138 key = "program \"%1\"" ;
2139
2140 key.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2141 key.DeleteSelf();
2142 key.SetName("HKEY_CLASSES_ROOT\\.flo" );
2143 key.DeleteSelf();
2144 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2145 key.DeleteSelf();
2146 key.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2147 key.DeleteSelf();
2148 }
2149
2150 #endif // TEST_REGISTRY
2151
2152 // ----------------------------------------------------------------------------
2153 // sockets
2154 // ----------------------------------------------------------------------------
2155
2156 #ifdef TEST_SOCKETS
2157
2158 #include <wx/socket.h>
2159 #include <wx/protocol/protocol.h>
2160 #include <wx/protocol/http.h>
2161
2162 static void TestSocketServer()
2163 {
2164 puts("*** Testing wxSocketServer ***\n");
2165
2166 static const int PORT = 3000;
2167
2168 wxIPV4address addr;
2169 addr.Service(PORT);
2170
2171 wxSocketServer *server = new wxSocketServer(addr);
2172 if ( !server->Ok() )
2173 {
2174 puts("ERROR: failed to bind");
2175
2176 return;
2177 }
2178
2179 for ( ;; )
2180 {
2181 printf("Server: waiting for connection on port %d...\n", PORT);
2182
2183 wxSocketBase *socket = server->Accept();
2184 if ( !socket )
2185 {
2186 puts("ERROR: wxSocketServer::Accept() failed.");
2187 break;
2188 }
2189
2190 puts("Server: got a client.");
2191
2192 server->SetTimeout(60); // 1 min
2193
2194 while ( socket->IsConnected() )
2195 {
2196 wxString s;
2197 char ch = '\0';
2198 for ( ;; )
2199 {
2200 if ( socket->Read(&ch, sizeof(ch)).Error() )
2201 {
2202 // don't log error if the client just close the connection
2203 if ( socket->IsConnected() )
2204 {
2205 puts("ERROR: in wxSocket::Read.");
2206 }
2207
2208 break;
2209 }
2210
2211 if ( ch == '\r' )
2212 continue;
2213
2214 if ( ch == '\n' )
2215 break;
2216
2217 s += ch;
2218 }
2219
2220 if ( ch != '\n' )
2221 {
2222 break;
2223 }
2224
2225 printf("Server: got '%s'.\n", s.c_str());
2226 if ( s == _T("bye") )
2227 {
2228 delete socket;
2229
2230 break;
2231 }
2232
2233 socket->Write(s.MakeUpper().c_str(), s.length());
2234 socket->Write("\r\n", 2);
2235 printf("Server: wrote '%s'.\n", s.c_str());
2236 }
2237
2238 puts("Server: lost a client.");
2239
2240 socket->Destroy();
2241 }
2242
2243 // same as "delete server" but is consistent with GUI programs
2244 server->Destroy();
2245 }
2246
2247 static void TestSocketClient()
2248 {
2249 puts("*** Testing wxSocketClient ***\n");
2250
2251 static const char *hostname = "www.wxwindows.org";
2252
2253 wxIPV4address addr;
2254 addr.Hostname(hostname);
2255 addr.Service(80);
2256
2257 printf("--- Attempting to connect to %s:80...\n", hostname);
2258
2259 wxSocketClient client;
2260 if ( !client.Connect(addr) )
2261 {
2262 printf("ERROR: failed to connect to %s\n", hostname);
2263 }
2264 else
2265 {
2266 printf("--- Connected to %s:%u...\n",
2267 addr.Hostname().c_str(), addr.Service());
2268
2269 char buf[8192];
2270
2271 // could use simply "GET" here I suppose
2272 wxString cmdGet =
2273 wxString::Format("GET http://%s/\r\n", hostname);
2274 client.Write(cmdGet, cmdGet.length());
2275 printf("--- Sent command '%s' to the server\n",
2276 MakePrintable(cmdGet).c_str());
2277 client.Read(buf, WXSIZEOF(buf));
2278 printf("--- Server replied:\n%s", buf);
2279 }
2280 }
2281
2282 #endif // TEST_SOCKETS
2283
2284 // ----------------------------------------------------------------------------
2285 // FTP
2286 // ----------------------------------------------------------------------------
2287
2288 #ifdef TEST_FTP
2289
2290 #include <wx/protocol/ftp.h>
2291
2292 static wxFTP ftp;
2293
2294 #define FTP_ANONYMOUS
2295
2296 #ifdef FTP_ANONYMOUS
2297 static const char *directory = "/pub";
2298 static const char *filename = "welcome.msg";
2299 #else
2300 static const char *directory = "/etc";
2301 static const char *filename = "issue";
2302 #endif
2303
2304 static bool TestFtpConnect()
2305 {
2306 puts("*** Testing FTP connect ***");
2307
2308 #ifdef FTP_ANONYMOUS
2309 static const char *hostname = "ftp.wxwindows.org";
2310
2311 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname);
2312 #else // !FTP_ANONYMOUS
2313 static const char *hostname = "localhost";
2314
2315 char user[256];
2316 fgets(user, WXSIZEOF(user), stdin);
2317 user[strlen(user) - 1] = '\0'; // chop off '\n'
2318 ftp.SetUser(user);
2319
2320 char password[256];
2321 printf("Password for %s: ", password);
2322 fgets(password, WXSIZEOF(password), stdin);
2323 password[strlen(password) - 1] = '\0'; // chop off '\n'
2324 ftp.SetPassword(password);
2325
2326 printf("--- Attempting to connect to %s:21 as %s...\n", hostname, user);
2327 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2328
2329 if ( !ftp.Connect(hostname) )
2330 {
2331 printf("ERROR: failed to connect to %s\n", hostname);
2332
2333 return FALSE;
2334 }
2335 else
2336 {
2337 printf("--- Connected to %s, current directory is '%s'\n",
2338 hostname, ftp.Pwd().c_str());
2339 }
2340
2341 return TRUE;
2342 }
2343
2344 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2345 static void TestFtpWuFtpd()
2346 {
2347 wxFTP ftp;
2348 static const char *hostname = "ftp.eudora.com";
2349 if ( !ftp.Connect(hostname) )
2350 {
2351 printf("ERROR: failed to connect to %s\n", hostname);
2352 }
2353 else
2354 {
2355 static const char *filename = "eudora/pubs/draft-gellens-submit-09.txt";
2356 wxInputStream *in = ftp.GetInputStream(filename);
2357 if ( !in )
2358 {
2359 printf("ERROR: couldn't get input stream for %s\n", filename);
2360 }
2361 else
2362 {
2363 size_t size = in->StreamSize();
2364 printf("Reading file %s (%u bytes)...", filename, size);
2365
2366 char *data = new char[size];
2367 if ( !in->Read(data, size) )
2368 {
2369 puts("ERROR: read error");
2370 }
2371 else
2372 {
2373 printf("Successfully retrieved the file.\n");
2374 }
2375
2376 delete [] data;
2377 delete in;
2378 }
2379 }
2380 }
2381
2382 static void TestFtpList()
2383 {
2384 puts("*** Testing wxFTP file listing ***\n");
2385
2386 // test CWD
2387 if ( !ftp.ChDir(directory) )
2388 {
2389 printf("ERROR: failed to cd to %s\n", directory);
2390 }
2391
2392 printf("Current directory is '%s'\n", ftp.Pwd().c_str());
2393
2394 // test NLIST and LIST
2395 wxArrayString files;
2396 if ( !ftp.GetFilesList(files) )
2397 {
2398 puts("ERROR: failed to get NLIST of files");
2399 }
2400 else
2401 {
2402 printf("Brief list of files under '%s':\n", ftp.Pwd().c_str());
2403 size_t count = files.GetCount();
2404 for ( size_t n = 0; n < count; n++ )
2405 {
2406 printf("\t%s\n", files[n].c_str());
2407 }
2408 puts("End of the file list");
2409 }
2410
2411 if ( !ftp.GetDirList(files) )
2412 {
2413 puts("ERROR: failed to get LIST of files");
2414 }
2415 else
2416 {
2417 printf("Detailed list of files under '%s':\n", ftp.Pwd().c_str());
2418 size_t count = files.GetCount();
2419 for ( size_t n = 0; n < count; n++ )
2420 {
2421 printf("\t%s\n", files[n].c_str());
2422 }
2423 puts("End of the file list");
2424 }
2425
2426 if ( !ftp.ChDir(_T("..")) )
2427 {
2428 puts("ERROR: failed to cd to ..");
2429 }
2430
2431 printf("Current directory is '%s'\n", ftp.Pwd().c_str());
2432 }
2433
2434 static void TestFtpDownload()
2435 {
2436 puts("*** Testing wxFTP download ***\n");
2437
2438 // test RETR
2439 wxInputStream *in = ftp.GetInputStream(filename);
2440 if ( !in )
2441 {
2442 printf("ERROR: couldn't get input stream for %s\n", filename);
2443 }
2444 else
2445 {
2446 size_t size = in->StreamSize();
2447 printf("Reading file %s (%u bytes)...", filename, size);
2448 fflush(stdout);
2449
2450 char *data = new char[size];
2451 if ( !in->Read(data, size) )
2452 {
2453 puts("ERROR: read error");
2454 }
2455 else
2456 {
2457 printf("\nContents of %s:\n%s\n", filename, data);
2458 }
2459
2460 delete [] data;
2461 delete in;
2462 }
2463 }
2464
2465 static void TestFtpFileSize()
2466 {
2467 puts("*** Testing FTP SIZE command ***");
2468
2469 if ( !ftp.ChDir(directory) )
2470 {
2471 printf("ERROR: failed to cd to %s\n", directory);
2472 }
2473
2474 printf("Current directory is '%s'\n", ftp.Pwd().c_str());
2475
2476 if ( ftp.FileExists(filename) )
2477 {
2478 int size = ftp.GetFileSize(filename);
2479 if ( size == -1 )
2480 printf("ERROR: couldn't get size of '%s'\n", filename);
2481 else
2482 printf("Size of '%s' is %d bytes.\n", filename, size);
2483 }
2484 else
2485 {
2486 printf("ERROR: '%s' doesn't exist\n", filename);
2487 }
2488 }
2489
2490 static void TestFtpMisc()
2491 {
2492 puts("*** Testing miscellaneous wxFTP functions ***");
2493
2494 if ( ftp.SendCommand("STAT") != '2' )
2495 {
2496 puts("ERROR: STAT failed");
2497 }
2498 else
2499 {
2500 printf("STAT returned:\n\n%s\n", ftp.GetLastResult().c_str());
2501 }
2502
2503 if ( ftp.SendCommand("HELP SITE") != '2' )
2504 {
2505 puts("ERROR: HELP SITE failed");
2506 }
2507 else
2508 {
2509 printf("The list of site-specific commands:\n\n%s\n",
2510 ftp.GetLastResult().c_str());
2511 }
2512 }
2513
2514 static void TestFtpInteractive()
2515 {
2516 puts("\n*** Interactive wxFTP test ***");
2517
2518 char buf[128];
2519
2520 for ( ;; )
2521 {
2522 printf("Enter FTP command: ");
2523 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
2524 break;
2525
2526 // kill the last '\n'
2527 buf[strlen(buf) - 1] = 0;
2528
2529 // special handling of LIST and NLST as they require data connection
2530 wxString start(buf, 4);
2531 start.MakeUpper();
2532 if ( start == "LIST" || start == "NLST" )
2533 {
2534 wxString wildcard;
2535 if ( strlen(buf) > 4 )
2536 wildcard = buf + 5;
2537
2538 wxArrayString files;
2539 if ( !ftp.GetList(files, wildcard, start == "LIST") )
2540 {
2541 printf("ERROR: failed to get %s of files\n", start.c_str());
2542 }
2543 else
2544 {
2545 printf("--- %s of '%s' under '%s':\n",
2546 start.c_str(), wildcard.c_str(), ftp.Pwd().c_str());
2547 size_t count = files.GetCount();
2548 for ( size_t n = 0; n < count; n++ )
2549 {
2550 printf("\t%s\n", files[n].c_str());
2551 }
2552 puts("--- End of the file list");
2553 }
2554 }
2555 else // !list
2556 {
2557 char ch = ftp.SendCommand(buf);
2558 printf("Command %s", ch ? "succeeded" : "failed");
2559 if ( ch )
2560 {
2561 printf(" (return code %c)", ch);
2562 }
2563
2564 printf(", server reply:\n%s\n\n", ftp.GetLastResult().c_str());
2565 }
2566 }
2567
2568 puts("\n*** done ***");
2569 }
2570
2571 static void TestFtpUpload()
2572 {
2573 puts("*** Testing wxFTP uploading ***\n");
2574
2575 // upload a file
2576 static const char *file1 = "test1";
2577 static const char *file2 = "test2";
2578 wxOutputStream *out = ftp.GetOutputStream(file1);
2579 if ( out )
2580 {
2581 printf("--- Uploading to %s ---\n", file1);
2582 out->Write("First hello", 11);
2583 delete out;
2584 }
2585
2586 // send a command to check the remote file
2587 if ( ftp.SendCommand(wxString("STAT ") + file1) != '2' )
2588 {
2589 printf("ERROR: STAT %s failed\n", file1);
2590 }
2591 else
2592 {
2593 printf("STAT %s returned:\n\n%s\n",
2594 file1, ftp.GetLastResult().c_str());
2595 }
2596
2597 out = ftp.GetOutputStream(file2);
2598 if ( out )
2599 {
2600 printf("--- Uploading to %s ---\n", file1);
2601 out->Write("Second hello", 12);
2602 delete out;
2603 }
2604 }
2605
2606 #endif // TEST_FTP
2607
2608 // ----------------------------------------------------------------------------
2609 // streams
2610 // ----------------------------------------------------------------------------
2611
2612 #ifdef TEST_STREAMS
2613
2614 #include <wx/wfstream.h>
2615 #include <wx/mstream.h>
2616
2617 static void TestFileStream()
2618 {
2619 puts("*** Testing wxFileInputStream ***");
2620
2621 static const wxChar *filename = _T("testdata.fs");
2622 {
2623 wxFileOutputStream fsOut(filename);
2624 fsOut.Write("foo", 3);
2625 }
2626
2627 wxFileInputStream fsIn(filename);
2628 printf("File stream size: %u\n", fsIn.GetSize());
2629 while ( !fsIn.Eof() )
2630 {
2631 putchar(fsIn.GetC());
2632 }
2633
2634 if ( !wxRemoveFile(filename) )
2635 {
2636 printf("ERROR: failed to remove the file '%s'.\n", filename);
2637 }
2638
2639 puts("\n*** wxFileInputStream test done ***");
2640 }
2641
2642 static void TestMemoryStream()
2643 {
2644 puts("*** Testing wxMemoryInputStream ***");
2645
2646 wxChar buf[1024];
2647 wxStrncpy(buf, _T("Hello, stream!"), WXSIZEOF(buf));
2648
2649 wxMemoryInputStream memInpStream(buf, wxStrlen(buf));
2650 printf(_T("Memory stream size: %u\n"), memInpStream.GetSize());
2651 while ( !memInpStream.Eof() )
2652 {
2653 putchar(memInpStream.GetC());
2654 }
2655
2656 puts("\n*** wxMemoryInputStream test done ***");
2657 }
2658
2659 #endif // TEST_STREAMS
2660
2661 // ----------------------------------------------------------------------------
2662 // timers
2663 // ----------------------------------------------------------------------------
2664
2665 #ifdef TEST_TIMER
2666
2667 #include <wx/timer.h>
2668 #include <wx/utils.h>
2669
2670 static void TestStopWatch()
2671 {
2672 puts("*** Testing wxStopWatch ***\n");
2673
2674 wxStopWatch sw;
2675 printf("Sleeping 3 seconds...");
2676 wxSleep(3);
2677 printf("\telapsed time: %ldms\n", sw.Time());
2678
2679 sw.Pause();
2680 printf("Sleeping 2 more seconds...");
2681 wxSleep(2);
2682 printf("\telapsed time: %ldms\n", sw.Time());
2683
2684 sw.Resume();
2685 printf("And 3 more seconds...");
2686 wxSleep(3);
2687 printf("\telapsed time: %ldms\n", sw.Time());
2688
2689 wxStopWatch sw2;
2690 puts("\nChecking for 'backwards clock' bug...");
2691 for ( size_t n = 0; n < 70; n++ )
2692 {
2693 sw2.Start();
2694
2695 for ( size_t m = 0; m < 100000; m++ )
2696 {
2697 if ( sw.Time() < 0 || sw2.Time() < 0 )
2698 {
2699 puts("\ntime is negative - ERROR!");
2700 }
2701 }
2702
2703 putchar('.');
2704 }
2705
2706 puts(", ok.");
2707 }
2708
2709 #endif // TEST_TIMER
2710
2711 // ----------------------------------------------------------------------------
2712 // vCard support
2713 // ----------------------------------------------------------------------------
2714
2715 #ifdef TEST_VCARD
2716
2717 #include <wx/vcard.h>
2718
2719 static void DumpVObject(size_t level, const wxVCardObject& vcard)
2720 {
2721 void *cookie;
2722 wxVCardObject *vcObj = vcard.GetFirstProp(&cookie);
2723 while ( vcObj )
2724 {
2725 printf("%s%s",
2726 wxString(_T('\t'), level).c_str(),
2727 vcObj->GetName().c_str());
2728
2729 wxString value;
2730 switch ( vcObj->GetType() )
2731 {
2732 case wxVCardObject::String:
2733 case wxVCardObject::UString:
2734 {
2735 wxString val;
2736 vcObj->GetValue(&val);
2737 value << _T('"') << val << _T('"');
2738 }
2739 break;
2740
2741 case wxVCardObject::Int:
2742 {
2743 unsigned int i;
2744 vcObj->GetValue(&i);
2745 value.Printf(_T("%u"), i);
2746 }
2747 break;
2748
2749 case wxVCardObject::Long:
2750 {
2751 unsigned long l;
2752 vcObj->GetValue(&l);
2753 value.Printf(_T("%lu"), l);
2754 }
2755 break;
2756
2757 case wxVCardObject::None:
2758 break;
2759
2760 case wxVCardObject::Object:
2761 value = _T("<node>");
2762 break;
2763
2764 default:
2765 value = _T("<unknown value type>");
2766 }
2767
2768 if ( !!value )
2769 printf(" = %s", value.c_str());
2770 putchar('\n');
2771
2772 DumpVObject(level + 1, *vcObj);
2773
2774 delete vcObj;
2775 vcObj = vcard.GetNextProp(&cookie);
2776 }
2777 }
2778
2779 static void DumpVCardAddresses(const wxVCard& vcard)
2780 {
2781 puts("\nShowing all addresses from vCard:\n");
2782
2783 size_t nAdr = 0;
2784 void *cookie;
2785 wxVCardAddress *addr = vcard.GetFirstAddress(&cookie);
2786 while ( addr )
2787 {
2788 wxString flagsStr;
2789 int flags = addr->GetFlags();
2790 if ( flags & wxVCardAddress::Domestic )
2791 {
2792 flagsStr << _T("domestic ");
2793 }
2794 if ( flags & wxVCardAddress::Intl )
2795 {
2796 flagsStr << _T("international ");
2797 }
2798 if ( flags & wxVCardAddress::Postal )
2799 {
2800 flagsStr << _T("postal ");
2801 }
2802 if ( flags & wxVCardAddress::Parcel )
2803 {
2804 flagsStr << _T("parcel ");
2805 }
2806 if ( flags & wxVCardAddress::Home )
2807 {
2808 flagsStr << _T("home ");
2809 }
2810 if ( flags & wxVCardAddress::Work )
2811 {
2812 flagsStr << _T("work ");
2813 }
2814
2815 printf("Address %u:\n"
2816 "\tflags = %s\n"
2817 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2818 ++nAdr,
2819 flagsStr.c_str(),
2820 addr->GetPostOffice().c_str(),
2821 addr->GetExtAddress().c_str(),
2822 addr->GetStreet().c_str(),
2823 addr->GetLocality().c_str(),
2824 addr->GetRegion().c_str(),
2825 addr->GetPostalCode().c_str(),
2826 addr->GetCountry().c_str()
2827 );
2828
2829 delete addr;
2830 addr = vcard.GetNextAddress(&cookie);
2831 }
2832 }
2833
2834 static void DumpVCardPhoneNumbers(const wxVCard& vcard)
2835 {
2836 puts("\nShowing all phone numbers from vCard:\n");
2837
2838 size_t nPhone = 0;
2839 void *cookie;
2840 wxVCardPhoneNumber *phone = vcard.GetFirstPhoneNumber(&cookie);
2841 while ( phone )
2842 {
2843 wxString flagsStr;
2844 int flags = phone->GetFlags();
2845 if ( flags & wxVCardPhoneNumber::Voice )
2846 {
2847 flagsStr << _T("voice ");
2848 }
2849 if ( flags & wxVCardPhoneNumber::Fax )
2850 {
2851 flagsStr << _T("fax ");
2852 }
2853 if ( flags & wxVCardPhoneNumber::Cellular )
2854 {
2855 flagsStr << _T("cellular ");
2856 }
2857 if ( flags & wxVCardPhoneNumber::Modem )
2858 {
2859 flagsStr << _T("modem ");
2860 }
2861 if ( flags & wxVCardPhoneNumber::Home )
2862 {
2863 flagsStr << _T("home ");
2864 }
2865 if ( flags & wxVCardPhoneNumber::Work )
2866 {
2867 flagsStr << _T("work ");
2868 }
2869
2870 printf("Phone number %u:\n"
2871 "\tflags = %s\n"
2872 "\tvalue = %s\n",
2873 ++nPhone,
2874 flagsStr.c_str(),
2875 phone->GetNumber().c_str()
2876 );
2877
2878 delete phone;
2879 phone = vcard.GetNextPhoneNumber(&cookie);
2880 }
2881 }
2882
2883 static void TestVCardRead()
2884 {
2885 puts("*** Testing wxVCard reading ***\n");
2886
2887 wxVCard vcard(_T("vcard.vcf"));
2888 if ( !vcard.IsOk() )
2889 {
2890 puts("ERROR: couldn't load vCard.");
2891 }
2892 else
2893 {
2894 // read individual vCard properties
2895 wxVCardObject *vcObj = vcard.GetProperty("FN");
2896 wxString value;
2897 if ( vcObj )
2898 {
2899 vcObj->GetValue(&value);
2900 delete vcObj;
2901 }
2902 else
2903 {
2904 value = _T("<none>");
2905 }
2906
2907 printf("Full name retrieved directly: %s\n", value.c_str());
2908
2909
2910 if ( !vcard.GetFullName(&value) )
2911 {
2912 value = _T("<none>");
2913 }
2914
2915 printf("Full name from wxVCard API: %s\n", value.c_str());
2916
2917 // now show how to deal with multiply occuring properties
2918 DumpVCardAddresses(vcard);
2919 DumpVCardPhoneNumbers(vcard);
2920
2921 // and finally show all
2922 puts("\nNow dumping the entire vCard:\n"
2923 "-----------------------------\n");
2924
2925 DumpVObject(0, vcard);
2926 }
2927 }
2928
2929 static void TestVCardWrite()
2930 {
2931 puts("*** Testing wxVCard writing ***\n");
2932
2933 wxVCard vcard;
2934 if ( !vcard.IsOk() )
2935 {
2936 puts("ERROR: couldn't create vCard.");
2937 }
2938 else
2939 {
2940 // set some fields
2941 vcard.SetName("Zeitlin", "Vadim");
2942 vcard.SetFullName("Vadim Zeitlin");
2943 vcard.SetOrganization("wxWindows", "R&D");
2944
2945 // just dump the vCard back
2946 puts("Entire vCard follows:\n");
2947 puts(vcard.Write());
2948 }
2949 }
2950
2951 #endif // TEST_VCARD
2952
2953 // ----------------------------------------------------------------------------
2954 // wide char (Unicode) support
2955 // ----------------------------------------------------------------------------
2956
2957 #ifdef TEST_WCHAR
2958
2959 #include <wx/strconv.h>
2960 #include <wx/fontenc.h>
2961 #include <wx/encconv.h>
2962 #include <wx/buffer.h>
2963
2964 static void TestUtf8()
2965 {
2966 puts("*** Testing UTF8 support ***\n");
2967
2968 static const char textInUtf8[] =
2969 {
2970 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2971 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2972 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2973 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2974 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2975 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2976 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2977 };
2978
2979 char buf[1024];
2980 wchar_t wbuf[1024];
2981 if ( wxConvUTF8.MB2WC(wbuf, textInUtf8, WXSIZEOF(textInUtf8)) <= 0 )
2982 {
2983 puts("ERROR: UTF-8 decoding failed.");
2984 }
2985 else
2986 {
2987 // using wxEncodingConverter
2988 #if 0
2989 wxEncodingConverter ec;
2990 ec.Init(wxFONTENCODING_UNICODE, wxFONTENCODING_KOI8);
2991 ec.Convert(wbuf, buf);
2992 #else // using wxCSConv
2993 wxCSConv conv(_T("koi8-r"));
2994 if ( conv.WC2MB(buf, wbuf, 0 /* not needed wcslen(wbuf) */) <= 0 )
2995 {
2996 puts("ERROR: conversion to KOI8-R failed.");
2997 }
2998 else
2999 #endif
3000
3001 printf("The resulting string (in koi8-r): %s\n", buf);
3002 }
3003 }
3004
3005 #endif // TEST_WCHAR
3006
3007 // ----------------------------------------------------------------------------
3008 // ZIP stream
3009 // ----------------------------------------------------------------------------
3010
3011 #ifdef TEST_ZIP
3012
3013 #include "wx/filesys.h"
3014 #include "wx/fs_zip.h"
3015 #include "wx/zipstrm.h"
3016
3017 static const wxChar *TESTFILE_ZIP = _T("testdata.zip");
3018
3019 static void TestZipStreamRead()
3020 {
3021 puts("*** Testing ZIP reading ***\n");
3022
3023 static const wxChar *filename = _T("foo");
3024 wxZipInputStream istr(TESTFILE_ZIP, filename);
3025 printf("Archive size: %u\n", istr.GetSize());
3026
3027 printf("Dumping the file '%s':\n", filename);
3028 while ( !istr.Eof() )
3029 {
3030 putchar(istr.GetC());
3031 fflush(stdout);
3032 }
3033
3034 puts("\n----- done ------");
3035 }
3036
3037 static void DumpZipDirectory(wxFileSystem& fs,
3038 const wxString& dir,
3039 const wxString& indent)
3040 {
3041 wxString prefix = wxString::Format(_T("%s#zip:%s"),
3042 TESTFILE_ZIP, dir.c_str());
3043 wxString wildcard = prefix + _T("/*");
3044
3045 wxString dirname = fs.FindFirst(wildcard, wxDIR);
3046 while ( !dirname.empty() )
3047 {
3048 if ( !dirname.StartsWith(prefix + _T('/'), &dirname) )
3049 {
3050 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3051
3052 break;
3053 }
3054
3055 wxPrintf(_T("%s%s\n"), indent.c_str(), dirname.c_str());
3056
3057 DumpZipDirectory(fs, dirname,
3058 indent + wxString(_T(' '), 4));
3059
3060 dirname = fs.FindNext();
3061 }
3062
3063 wxString filename = fs.FindFirst(wildcard, wxFILE);
3064 while ( !filename.empty() )
3065 {
3066 if ( !filename.StartsWith(prefix, &filename) )
3067 {
3068 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3069
3070 break;
3071 }
3072
3073 wxPrintf(_T("%s%s\n"), indent.c_str(), filename.c_str());
3074
3075 filename = fs.FindNext();
3076 }
3077 }
3078
3079 static void TestZipFileSystem()
3080 {
3081 puts("*** Testing ZIP file system ***\n");
3082
3083 wxFileSystem::AddHandler(new wxZipFSHandler);
3084 wxFileSystem fs;
3085 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP);
3086
3087 DumpZipDirectory(fs, _T(""), wxString(_T(' '), 4));
3088 }
3089
3090 #endif // TEST_ZIP
3091
3092 // ----------------------------------------------------------------------------
3093 // ZLIB stream
3094 // ----------------------------------------------------------------------------
3095
3096 #ifdef TEST_ZLIB
3097
3098 #include <wx/zstream.h>
3099 #include <wx/wfstream.h>
3100
3101 static const wxChar *FILENAME_GZ = _T("test.gz");
3102 static const char *TEST_DATA = "hello and hello again";
3103
3104 static void TestZlibStreamWrite()
3105 {
3106 puts("*** Testing Zlib stream reading ***\n");
3107
3108 wxFileOutputStream fileOutStream(FILENAME_GZ);
3109 wxZlibOutputStream ostr(fileOutStream, 0);
3110 printf("Compressing the test string... ");
3111 ostr.Write(TEST_DATA, sizeof(TEST_DATA));
3112 if ( !ostr )
3113 {
3114 puts("(ERROR: failed)");
3115 }
3116 else
3117 {
3118 puts("(ok)");
3119 }
3120
3121 puts("\n----- done ------");
3122 }
3123
3124 static void TestZlibStreamRead()
3125 {
3126 puts("*** Testing Zlib stream reading ***\n");
3127
3128 wxFileInputStream fileInStream(FILENAME_GZ);
3129 wxZlibInputStream istr(fileInStream);
3130 printf("Archive size: %u\n", istr.GetSize());
3131
3132 puts("Dumping the file:");
3133 while ( !istr.Eof() )
3134 {
3135 putchar(istr.GetC());
3136 fflush(stdout);
3137 }
3138
3139 puts("\n----- done ------");
3140 }
3141
3142 #endif // TEST_ZLIB
3143
3144 // ----------------------------------------------------------------------------
3145 // date time
3146 // ----------------------------------------------------------------------------
3147
3148 #ifdef TEST_DATETIME
3149
3150 #include <math.h>
3151
3152 #include <wx/date.h>
3153
3154 #include <wx/datetime.h>
3155
3156 // the test data
3157 struct Date
3158 {
3159 wxDateTime::wxDateTime_t day;
3160 wxDateTime::Month month;
3161 int year;
3162 wxDateTime::wxDateTime_t hour, min, sec;
3163 double jdn;
3164 wxDateTime::WeekDay wday;
3165 time_t gmticks, ticks;
3166
3167 void Init(const wxDateTime::Tm& tm)
3168 {
3169 day = tm.mday;
3170 month = tm.mon;
3171 year = tm.year;
3172 hour = tm.hour;
3173 min = tm.min;
3174 sec = tm.sec;
3175 jdn = 0.0;
3176 gmticks = ticks = -1;
3177 }
3178
3179 wxDateTime DT() const
3180 { return wxDateTime(day, month, year, hour, min, sec); }
3181
3182 bool SameDay(const wxDateTime::Tm& tm) const
3183 {
3184 return day == tm.mday && month == tm.mon && year == tm.year;
3185 }
3186
3187 wxString Format() const
3188 {
3189 wxString s;
3190 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3191 hour, min, sec,
3192 wxDateTime::GetMonthName(month).c_str(),
3193 day,
3194 abs(wxDateTime::ConvertYearToBC(year)),
3195 year > 0 ? "AD" : "BC");
3196 return s;
3197 }
3198
3199 wxString FormatDate() const
3200 {
3201 wxString s;
3202 s.Printf("%02d-%s-%4d%s",
3203 day,
3204 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
3205 abs(wxDateTime::ConvertYearToBC(year)),
3206 year > 0 ? "AD" : "BC");
3207 return s;
3208 }
3209 };
3210
3211 static const Date testDates[] =
3212 {
3213 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
3214 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
3215 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
3216 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
3217 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
3218 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
3219 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
3220 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
3221 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
3222 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
3223 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
3224 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
3225 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
3226 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
3227 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
3228 };
3229
3230 // this test miscellaneous static wxDateTime functions
3231 static void TestTimeStatic()
3232 {
3233 puts("\n*** wxDateTime static methods test ***");
3234
3235 // some info about the current date
3236 int year = wxDateTime::GetCurrentYear();
3237 printf("Current year %d is %sa leap one and has %d days.\n",
3238 year,
3239 wxDateTime::IsLeapYear(year) ? "" : "not ",
3240 wxDateTime::GetNumberOfDays(year));
3241
3242 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
3243 printf("Current month is '%s' ('%s') and it has %d days\n",
3244 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
3245 wxDateTime::GetMonthName(month).c_str(),
3246 wxDateTime::GetNumberOfDays(month));
3247
3248 // leap year logic
3249 static const size_t nYears = 5;
3250 static const size_t years[2][nYears] =
3251 {
3252 // first line: the years to test
3253 { 1990, 1976, 2000, 2030, 1984, },
3254
3255 // second line: TRUE if leap, FALSE otherwise
3256 { FALSE, TRUE, TRUE, FALSE, TRUE }
3257 };
3258
3259 for ( size_t n = 0; n < nYears; n++ )
3260 {
3261 int year = years[0][n];
3262 bool should = years[1][n] != 0,
3263 is = wxDateTime::IsLeapYear(year);
3264
3265 printf("Year %d is %sa leap year (%s)\n",
3266 year,
3267 is ? "" : "not ",
3268 should == is ? "ok" : "ERROR");
3269
3270 wxASSERT( should == wxDateTime::IsLeapYear(year) );
3271 }
3272 }
3273
3274 // test constructing wxDateTime objects
3275 static void TestTimeSet()
3276 {
3277 puts("\n*** wxDateTime construction test ***");
3278
3279 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3280 {
3281 const Date& d1 = testDates[n];
3282 wxDateTime dt = d1.DT();
3283
3284 Date d2;
3285 d2.Init(dt.GetTm());
3286
3287 wxString s1 = d1.Format(),
3288 s2 = d2.Format();
3289
3290 printf("Date: %s == %s (%s)\n",
3291 s1.c_str(), s2.c_str(),
3292 s1 == s2 ? "ok" : "ERROR");
3293 }
3294 }
3295
3296 // test time zones stuff
3297 static void TestTimeZones()
3298 {
3299 puts("\n*** wxDateTime timezone test ***");
3300
3301 wxDateTime now = wxDateTime::Now();
3302
3303 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
3304 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
3305 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
3306 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
3307 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
3308 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
3309
3310 wxDateTime::Tm tm = now.GetTm();
3311 if ( wxDateTime(tm) != now )
3312 {
3313 printf("ERROR: got %s instead of %s\n",
3314 wxDateTime(tm).Format().c_str(), now.Format().c_str());
3315 }
3316 }
3317
3318 // test some minimal support for the dates outside the standard range
3319 static void TestTimeRange()
3320 {
3321 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3322
3323 static const char *fmt = "%d-%b-%Y %H:%M:%S";
3324
3325 printf("Unix epoch:\t%s\n",
3326 wxDateTime(2440587.5).Format(fmt).c_str());
3327 printf("Feb 29, 0: \t%s\n",
3328 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
3329 printf("JDN 0: \t%s\n",
3330 wxDateTime(0.0).Format(fmt).c_str());
3331 printf("Jan 1, 1AD:\t%s\n",
3332 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
3333 printf("May 29, 2099:\t%s\n",
3334 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
3335 }
3336
3337 static void TestTimeTicks()
3338 {
3339 puts("\n*** wxDateTime ticks test ***");
3340
3341 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3342 {
3343 const Date& d = testDates[n];
3344 if ( d.ticks == -1 )
3345 continue;
3346
3347 wxDateTime dt = d.DT();
3348 long ticks = (dt.GetValue() / 1000).ToLong();
3349 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
3350 if ( ticks == d.ticks )
3351 {
3352 puts(" (ok)");
3353 }
3354 else
3355 {
3356 printf(" (ERROR: should be %ld, delta = %ld)\n",
3357 d.ticks, ticks - d.ticks);
3358 }
3359
3360 dt = d.DT().ToTimezone(wxDateTime::GMT0);
3361 ticks = (dt.GetValue() / 1000).ToLong();
3362 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
3363 if ( ticks == d.gmticks )
3364 {
3365 puts(" (ok)");
3366 }
3367 else
3368 {
3369 printf(" (ERROR: should be %ld, delta = %ld)\n",
3370 d.gmticks, ticks - d.gmticks);
3371 }
3372 }
3373
3374 puts("");
3375 }
3376
3377 // test conversions to JDN &c
3378 static void TestTimeJDN()
3379 {
3380 puts("\n*** wxDateTime to JDN test ***");
3381
3382 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3383 {
3384 const Date& d = testDates[n];
3385 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
3386 double jdn = dt.GetJulianDayNumber();
3387
3388 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
3389 if ( jdn == d.jdn )
3390 {
3391 puts(" (ok)");
3392 }
3393 else
3394 {
3395 printf(" (ERROR: should be %f, delta = %f)\n",
3396 d.jdn, jdn - d.jdn);
3397 }
3398 }
3399 }
3400
3401 // test week days computation
3402 static void TestTimeWDays()
3403 {
3404 puts("\n*** wxDateTime weekday test ***");
3405
3406 // test GetWeekDay()
3407 size_t n;
3408 for ( n = 0; n < WXSIZEOF(testDates); n++ )
3409 {
3410 const Date& d = testDates[n];
3411 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
3412
3413 wxDateTime::WeekDay wday = dt.GetWeekDay();
3414 printf("%s is: %s",
3415 d.Format().c_str(),
3416 wxDateTime::GetWeekDayName(wday).c_str());
3417 if ( wday == d.wday )
3418 {
3419 puts(" (ok)");
3420 }
3421 else
3422 {
3423 printf(" (ERROR: should be %s)\n",
3424 wxDateTime::GetWeekDayName(d.wday).c_str());
3425 }
3426 }
3427
3428 puts("");
3429
3430 // test SetToWeekDay()
3431 struct WeekDateTestData
3432 {
3433 Date date; // the real date (precomputed)
3434 int nWeek; // its week index in the month
3435 wxDateTime::WeekDay wday; // the weekday
3436 wxDateTime::Month month; // the month
3437 int year; // and the year
3438
3439 wxString Format() const
3440 {
3441 wxString s, which;
3442 switch ( nWeek < -1 ? -nWeek : nWeek )
3443 {
3444 case 1: which = "first"; break;
3445 case 2: which = "second"; break;
3446 case 3: which = "third"; break;
3447 case 4: which = "fourth"; break;
3448 case 5: which = "fifth"; break;
3449
3450 case -1: which = "last"; break;
3451 }
3452
3453 if ( nWeek < -1 )
3454 {
3455 which += " from end";
3456 }
3457
3458 s.Printf("The %s %s of %s in %d",
3459 which.c_str(),
3460 wxDateTime::GetWeekDayName(wday).c_str(),
3461 wxDateTime::GetMonthName(month).c_str(),
3462 year);
3463
3464 return s;
3465 }
3466 };
3467
3468 // the array data was generated by the following python program
3469 /*
3470 from DateTime import *
3471 from whrandom import *
3472 from string import *
3473
3474 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3475 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3476
3477 week = DateTimeDelta(7)
3478
3479 for n in range(20):
3480 year = randint(1900, 2100)
3481 month = randint(1, 12)
3482 day = randint(1, 28)
3483 dt = DateTime(year, month, day)
3484 wday = dt.day_of_week
3485
3486 countFromEnd = choice([-1, 1])
3487 weekNum = 0;
3488
3489 while dt.month is month:
3490 dt = dt - countFromEnd * week
3491 weekNum = weekNum + countFromEnd
3492
3493 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3494
3495 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3496 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3497 */
3498
3499 static const WeekDateTestData weekDatesTestData[] =
3500 {
3501 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
3502 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
3503 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
3504 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
3505 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
3506 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
3507 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
3508 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
3509 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
3510 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
3511 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
3512 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
3513 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
3514 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
3515 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
3516 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
3517 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
3518 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
3519 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
3520 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
3521 };
3522
3523 static const char *fmt = "%d-%b-%Y";
3524
3525 wxDateTime dt;
3526 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
3527 {
3528 const WeekDateTestData& wd = weekDatesTestData[n];
3529
3530 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
3531
3532 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
3533
3534 const Date& d = wd.date;
3535 if ( d.SameDay(dt.GetTm()) )
3536 {
3537 puts(" (ok)");
3538 }
3539 else
3540 {
3541 dt.Set(d.day, d.month, d.year);
3542
3543 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
3544 }
3545 }
3546 }
3547
3548 // test the computation of (ISO) week numbers
3549 static void TestTimeWNumber()
3550 {
3551 puts("\n*** wxDateTime week number test ***");
3552
3553 struct WeekNumberTestData
3554 {
3555 Date date; // the date
3556 wxDateTime::wxDateTime_t week; // the week number in the year
3557 wxDateTime::wxDateTime_t wmon; // the week number in the month
3558 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
3559 wxDateTime::wxDateTime_t dnum; // day number in the year
3560 };
3561
3562 // data generated with the following python script:
3563 /*
3564 from DateTime import *
3565 from whrandom import *
3566 from string import *
3567
3568 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3569 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3570
3571 def GetMonthWeek(dt):
3572 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3573 if weekNumMonth < 0:
3574 weekNumMonth = weekNumMonth + 53
3575 return weekNumMonth
3576
3577 def GetLastSundayBefore(dt):
3578 if dt.iso_week[2] == 7:
3579 return dt
3580 else:
3581 return dt - DateTimeDelta(dt.iso_week[2])
3582
3583 for n in range(20):
3584 year = randint(1900, 2100)
3585 month = randint(1, 12)
3586 day = randint(1, 28)
3587 dt = DateTime(year, month, day)
3588 dayNum = dt.day_of_year
3589 weekNum = dt.iso_week[1]
3590 weekNumMonth = GetMonthWeek(dt)
3591
3592 weekNumMonth2 = 0
3593 dtSunday = GetLastSundayBefore(dt)
3594
3595 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3596 weekNumMonth2 = weekNumMonth2 + 1
3597 dtSunday = dtSunday - DateTimeDelta(7)
3598
3599 data = { 'day': rjust(`day`, 2), \
3600 'month': monthNames[month - 1], \
3601 'year': year, \
3602 'weekNum': rjust(`weekNum`, 2), \
3603 'weekNumMonth': weekNumMonth, \
3604 'weekNumMonth2': weekNumMonth2, \
3605 'dayNum': rjust(`dayNum`, 3) }
3606
3607 print " { { %(day)s, "\
3608 "wxDateTime::%(month)s, "\
3609 "%(year)d }, "\
3610 "%(weekNum)s, "\
3611 "%(weekNumMonth)s, "\
3612 "%(weekNumMonth2)s, "\
3613 "%(dayNum)s }," % data
3614
3615 */
3616 static const WeekNumberTestData weekNumberTestDates[] =
3617 {
3618 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
3619 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
3620 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
3621 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
3622 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
3623 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
3624 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
3625 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
3626 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
3627 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
3628 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
3629 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
3630 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
3631 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
3632 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
3633 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
3634 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
3635 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
3636 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
3637 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
3638 };
3639
3640 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
3641 {
3642 const WeekNumberTestData& wn = weekNumberTestDates[n];
3643 const Date& d = wn.date;
3644
3645 wxDateTime dt = d.DT();
3646
3647 wxDateTime::wxDateTime_t
3648 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
3649 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
3650 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
3651 dnum = dt.GetDayOfYear();
3652
3653 printf("%s: the day number is %d",
3654 d.FormatDate().c_str(), dnum);
3655 if ( dnum == wn.dnum )
3656 {
3657 printf(" (ok)");
3658 }
3659 else
3660 {
3661 printf(" (ERROR: should be %d)", wn.dnum);
3662 }
3663
3664 printf(", week in month is %d", wmon);
3665 if ( wmon == wn.wmon )
3666 {
3667 printf(" (ok)");
3668 }
3669 else
3670 {
3671 printf(" (ERROR: should be %d)", wn.wmon);
3672 }
3673
3674 printf(" or %d", wmon2);
3675 if ( wmon2 == wn.wmon2 )
3676 {
3677 printf(" (ok)");
3678 }
3679 else
3680 {
3681 printf(" (ERROR: should be %d)", wn.wmon2);
3682 }
3683
3684 printf(", week in year is %d", week);
3685 if ( week == wn.week )
3686 {
3687 puts(" (ok)");
3688 }
3689 else
3690 {
3691 printf(" (ERROR: should be %d)\n", wn.week);
3692 }
3693 }
3694 }
3695
3696 // test DST calculations
3697 static void TestTimeDST()
3698 {
3699 puts("\n*** wxDateTime DST test ***");
3700
3701 printf("DST is%s in effect now.\n\n",
3702 wxDateTime::Now().IsDST() ? "" : " not");
3703
3704 // taken from http://www.energy.ca.gov/daylightsaving.html
3705 static const Date datesDST[2][2004 - 1900 + 1] =
3706 {
3707 {
3708 { 1, wxDateTime::Apr, 1990 },
3709 { 7, wxDateTime::Apr, 1991 },
3710 { 5, wxDateTime::Apr, 1992 },
3711 { 4, wxDateTime::Apr, 1993 },
3712 { 3, wxDateTime::Apr, 1994 },
3713 { 2, wxDateTime::Apr, 1995 },
3714 { 7, wxDateTime::Apr, 1996 },
3715 { 6, wxDateTime::Apr, 1997 },
3716 { 5, wxDateTime::Apr, 1998 },
3717 { 4, wxDateTime::Apr, 1999 },
3718 { 2, wxDateTime::Apr, 2000 },
3719 { 1, wxDateTime::Apr, 2001 },
3720 { 7, wxDateTime::Apr, 2002 },
3721 { 6, wxDateTime::Apr, 2003 },
3722 { 4, wxDateTime::Apr, 2004 },
3723 },
3724 {
3725 { 28, wxDateTime::Oct, 1990 },
3726 { 27, wxDateTime::Oct, 1991 },
3727 { 25, wxDateTime::Oct, 1992 },
3728 { 31, wxDateTime::Oct, 1993 },
3729 { 30, wxDateTime::Oct, 1994 },
3730 { 29, wxDateTime::Oct, 1995 },
3731 { 27, wxDateTime::Oct, 1996 },
3732 { 26, wxDateTime::Oct, 1997 },
3733 { 25, wxDateTime::Oct, 1998 },
3734 { 31, wxDateTime::Oct, 1999 },
3735 { 29, wxDateTime::Oct, 2000 },
3736 { 28, wxDateTime::Oct, 2001 },
3737 { 27, wxDateTime::Oct, 2002 },
3738 { 26, wxDateTime::Oct, 2003 },
3739 { 31, wxDateTime::Oct, 2004 },
3740 }
3741 };
3742
3743 int year;
3744 for ( year = 1990; year < 2005; year++ )
3745 {
3746 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
3747 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
3748
3749 printf("DST period in the US for year %d: from %s to %s",
3750 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
3751
3752 size_t n = year - 1990;
3753 const Date& dBegin = datesDST[0][n];
3754 const Date& dEnd = datesDST[1][n];
3755
3756 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
3757 {
3758 puts(" (ok)");
3759 }
3760 else
3761 {
3762 printf(" (ERROR: should be %s %d to %s %d)\n",
3763 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
3764 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
3765 }
3766 }
3767
3768 puts("");
3769
3770 for ( year = 1990; year < 2005; year++ )
3771 {
3772 printf("DST period in Europe for year %d: from %s to %s\n",
3773 year,
3774 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
3775 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
3776 }
3777 }
3778
3779 // test wxDateTime -> text conversion
3780 static void TestTimeFormat()
3781 {
3782 puts("\n*** wxDateTime formatting test ***");
3783
3784 // some information may be lost during conversion, so store what kind
3785 // of info should we recover after a round trip
3786 enum CompareKind
3787 {
3788 CompareNone, // don't try comparing
3789 CompareBoth, // dates and times should be identical
3790 CompareDate, // dates only
3791 CompareTime // time only
3792 };
3793
3794 static const struct
3795 {
3796 CompareKind compareKind;
3797 const char *format;
3798 } formatTestFormats[] =
3799 {
3800 { CompareBoth, "---> %c" },
3801 { CompareDate, "Date is %A, %d of %B, in year %Y" },
3802 { CompareBoth, "Date is %x, time is %X" },
3803 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
3804 { CompareNone, "The day of year: %j, the week of year: %W" },
3805 { CompareDate, "ISO date without separators: %4Y%2m%2d" },
3806 };
3807
3808 static const Date formatTestDates[] =
3809 {
3810 { 29, wxDateTime::May, 1976, 18, 30, 00 },
3811 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
3812 #if 0
3813 // this test can't work for other centuries because it uses two digit
3814 // years in formats, so don't even try it
3815 { 29, wxDateTime::May, 2076, 18, 30, 00 },
3816 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
3817 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
3818 #endif
3819 };
3820
3821 // an extra test (as it doesn't depend on date, don't do it in the loop)
3822 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3823
3824 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
3825 {
3826 puts("");
3827
3828 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
3829 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
3830 {
3831 wxString s = dt.Format(formatTestFormats[n].format);
3832 printf("%s", s.c_str());
3833
3834 // what can we recover?
3835 int kind = formatTestFormats[n].compareKind;
3836
3837 // convert back
3838 wxDateTime dt2;
3839 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
3840 if ( !result )
3841 {
3842 // converion failed - should it have?
3843 if ( kind == CompareNone )
3844 puts(" (ok)");
3845 else
3846 puts(" (ERROR: conversion back failed)");
3847 }
3848 else if ( *result )
3849 {
3850 // should have parsed the entire string
3851 puts(" (ERROR: conversion back stopped too soon)");
3852 }
3853 else
3854 {
3855 bool equal = FALSE; // suppress compilaer warning
3856 switch ( kind )
3857 {
3858 case CompareBoth:
3859 equal = dt2 == dt;
3860 break;
3861
3862 case CompareDate:
3863 equal = dt.IsSameDate(dt2);
3864 break;
3865
3866 case CompareTime:
3867 equal = dt.IsSameTime(dt2);
3868 break;
3869 }
3870
3871 if ( !equal )
3872 {
3873 printf(" (ERROR: got back '%s' instead of '%s')\n",
3874 dt2.Format().c_str(), dt.Format().c_str());
3875 }
3876 else
3877 {
3878 puts(" (ok)");
3879 }
3880 }
3881 }
3882 }
3883 }
3884
3885 // test text -> wxDateTime conversion
3886 static void TestTimeParse()
3887 {
3888 puts("\n*** wxDateTime parse test ***");
3889
3890 struct ParseTestData
3891 {
3892 const char *format;
3893 Date date;
3894 bool good;
3895 };
3896
3897 static const ParseTestData parseTestDates[] =
3898 {
3899 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
3900 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
3901 };
3902
3903 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
3904 {
3905 const char *format = parseTestDates[n].format;
3906
3907 printf("%s => ", format);
3908
3909 wxDateTime dt;
3910 if ( dt.ParseRfc822Date(format) )
3911 {
3912 printf("%s ", dt.Format().c_str());
3913
3914 if ( parseTestDates[n].good )
3915 {
3916 wxDateTime dtReal = parseTestDates[n].date.DT();
3917 if ( dt == dtReal )
3918 {
3919 puts("(ok)");
3920 }
3921 else
3922 {
3923 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
3924 }
3925 }
3926 else
3927 {
3928 puts("(ERROR: bad format)");
3929 }
3930 }
3931 else
3932 {
3933 printf("bad format (%s)\n",
3934 parseTestDates[n].good ? "ERROR" : "ok");
3935 }
3936 }
3937 }
3938
3939 static void TestDateTimeInteractive()
3940 {
3941 puts("\n*** interactive wxDateTime tests ***");
3942
3943 char buf[128];
3944
3945 for ( ;; )
3946 {
3947 printf("Enter a date: ");
3948 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
3949 break;
3950
3951 // kill the last '\n'
3952 buf[strlen(buf) - 1] = 0;
3953
3954 wxDateTime dt;
3955 const char *p = dt.ParseDate(buf);
3956 if ( !p )
3957 {
3958 printf("ERROR: failed to parse the date '%s'.\n", buf);
3959
3960 continue;
3961 }
3962 else if ( *p )
3963 {
3964 printf("WARNING: parsed only first %u characters.\n", p - buf);
3965 }
3966
3967 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3968 dt.Format("%b %d, %Y").c_str(),
3969 dt.GetDayOfYear(),
3970 dt.GetWeekOfMonth(wxDateTime::Monday_First),
3971 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
3972 dt.GetWeekOfYear(wxDateTime::Monday_First));
3973 }
3974
3975 puts("\n*** done ***");
3976 }
3977
3978 static void TestTimeMS()
3979 {
3980 puts("*** testing millisecond-resolution support in wxDateTime ***");
3981
3982 wxDateTime dt1 = wxDateTime::Now(),
3983 dt2 = wxDateTime::UNow();
3984
3985 printf("Now = %s\n", dt1.Format("%H:%M:%S:%l").c_str());
3986 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
3987 printf("Dummy loop: ");
3988 for ( int i = 0; i < 6000; i++ )
3989 {
3990 //for ( int j = 0; j < 10; j++ )
3991 {
3992 wxString s;
3993 s.Printf("%g", sqrt(i));
3994 }
3995
3996 if ( !(i % 100) )
3997 putchar('.');
3998 }
3999 puts(", done");
4000
4001 dt1 = dt2;
4002 dt2 = wxDateTime::UNow();
4003 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
4004
4005 printf("Loop executed in %s ms\n", (dt2 - dt1).Format("%l").c_str());
4006
4007 puts("\n*** done ***");
4008 }
4009
4010 static void TestTimeArithmetics()
4011 {
4012 puts("\n*** testing arithmetic operations on wxDateTime ***");
4013
4014 static const struct ArithmData
4015 {
4016 ArithmData(const wxDateSpan& sp, const char *nam)
4017 : span(sp), name(nam) { }
4018
4019 wxDateSpan span;
4020 const char *name;
4021 } testArithmData[] =
4022 {
4023 ArithmData(wxDateSpan::Day(), "day"),
4024 ArithmData(wxDateSpan::Week(), "week"),
4025 ArithmData(wxDateSpan::Month(), "month"),
4026 ArithmData(wxDateSpan::Year(), "year"),
4027 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4028 };
4029
4030 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
4031
4032 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
4033 {
4034 wxDateSpan span = testArithmData[n].span;
4035 dt1 = dt + span;
4036 dt2 = dt - span;
4037
4038 const char *name = testArithmData[n].name;
4039 printf("%s + %s = %s, %s - %s = %s\n",
4040 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
4041 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
4042
4043 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
4044 if ( dt1 - span == dt )
4045 {
4046 puts(" (ok)");
4047 }
4048 else
4049 {
4050 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
4051 }
4052
4053 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
4054 if ( dt2 + span == dt )
4055 {
4056 puts(" (ok)");
4057 }
4058 else
4059 {
4060 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
4061 }
4062
4063 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
4064 if ( dt2 + 2*span == dt1 )
4065 {
4066 puts(" (ok)");
4067 }
4068 else
4069 {
4070 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
4071 }
4072
4073 puts("");
4074 }
4075 }
4076
4077 static void TestTimeHolidays()
4078 {
4079 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4080
4081 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
4082 wxDateTime dtStart(1, tm.mon, tm.year),
4083 dtEnd = dtStart.GetLastMonthDay();
4084
4085 wxDateTimeArray hol;
4086 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
4087
4088 const wxChar *format = "%d-%b-%Y (%a)";
4089
4090 printf("All holidays between %s and %s:\n",
4091 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
4092
4093 size_t count = hol.GetCount();
4094 for ( size_t n = 0; n < count; n++ )
4095 {
4096 printf("\t%s\n", hol[n].Format(format).c_str());
4097 }
4098
4099 puts("");
4100 }
4101
4102 static void TestTimeZoneBug()
4103 {
4104 puts("\n*** testing for DST/timezone bug ***\n");
4105
4106 wxDateTime date = wxDateTime(1, wxDateTime::Mar, 2000);
4107 for ( int i = 0; i < 31; i++ )
4108 {
4109 printf("Date %s: week day %s.\n",
4110 date.Format(_T("%d-%m-%Y")).c_str(),
4111 date.GetWeekDayName(date.GetWeekDay()).c_str());
4112
4113 date += wxDateSpan::Day();
4114 }
4115
4116 puts("");
4117 }
4118
4119 static void TestTimeSpanFormat()
4120 {
4121 puts("\n*** wxTimeSpan tests ***");
4122
4123 static const char *formats[] =
4124 {
4125 _T("(default) %H:%M:%S"),
4126 _T("%E weeks and %D days"),
4127 _T("%l milliseconds"),
4128 _T("(with ms) %H:%M:%S:%l"),
4129 _T("100%% of minutes is %M"), // test "%%"
4130 _T("%D days and %H hours"),
4131 _T("or also %S seconds"),
4132 };
4133
4134 wxTimeSpan ts1(1, 2, 3, 4),
4135 ts2(111, 222, 333);
4136 for ( size_t n = 0; n < WXSIZEOF(formats); n++ )
4137 {
4138 printf("ts1 = %s\tts2 = %s\n",
4139 ts1.Format(formats[n]).c_str(),
4140 ts2.Format(formats[n]).c_str());
4141 }
4142
4143 puts("");
4144 }
4145
4146 #if 0
4147
4148 // test compatibility with the old wxDate/wxTime classes
4149 static void TestTimeCompatibility()
4150 {
4151 puts("\n*** wxDateTime compatibility test ***");
4152
4153 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4154 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4155
4156 double jdnNow = wxDateTime::Now().GetJDN();
4157 long jdnMidnight = (long)(jdnNow - 0.5);
4158 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
4159
4160 jdnMidnight = wxDate().Set().GetJulianDate();
4161 printf("wxDateTime for today: %s\n",
4162 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
4163
4164 int flags = wxEUROPEAN;//wxFULL;
4165 wxDate date;
4166 date.Set();
4167 printf("Today is %s\n", date.FormatDate(flags).c_str());
4168 for ( int n = 0; n < 7; n++ )
4169 {
4170 printf("Previous %s is %s\n",
4171 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
4172 date.Previous(n + 1).FormatDate(flags).c_str());
4173 }
4174 }
4175
4176 #endif // 0
4177
4178 #endif // TEST_DATETIME
4179
4180 // ----------------------------------------------------------------------------
4181 // threads
4182 // ----------------------------------------------------------------------------
4183
4184 #ifdef TEST_THREADS
4185
4186 #include <wx/thread.h>
4187
4188 static size_t gs_counter = (size_t)-1;
4189 static wxCriticalSection gs_critsect;
4190 static wxCondition gs_cond;
4191
4192 class MyJoinableThread : public wxThread
4193 {
4194 public:
4195 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
4196 { m_n = n; Create(); }
4197
4198 // thread execution starts here
4199 virtual ExitCode Entry();
4200
4201 private:
4202 size_t m_n;
4203 };
4204
4205 wxThread::ExitCode MyJoinableThread::Entry()
4206 {
4207 unsigned long res = 1;
4208 for ( size_t n = 1; n < m_n; n++ )
4209 {
4210 res *= n;
4211
4212 // it's a loooong calculation :-)
4213 Sleep(100);
4214 }
4215
4216 return (ExitCode)res;
4217 }
4218
4219 class MyDetachedThread : public wxThread
4220 {
4221 public:
4222 MyDetachedThread(size_t n, char ch)
4223 {
4224 m_n = n;
4225 m_ch = ch;
4226 m_cancelled = FALSE;
4227
4228 Create();
4229 }
4230
4231 // thread execution starts here
4232 virtual ExitCode Entry();
4233
4234 // and stops here
4235 virtual void OnExit();
4236
4237 private:
4238 size_t m_n; // number of characters to write
4239 char m_ch; // character to write
4240
4241 bool m_cancelled; // FALSE if we exit normally
4242 };
4243
4244 wxThread::ExitCode MyDetachedThread::Entry()
4245 {
4246 {
4247 wxCriticalSectionLocker lock(gs_critsect);
4248 if ( gs_counter == (size_t)-1 )
4249 gs_counter = 1;
4250 else
4251 gs_counter++;
4252 }
4253
4254 for ( size_t n = 0; n < m_n; n++ )
4255 {
4256 if ( TestDestroy() )
4257 {
4258 m_cancelled = TRUE;
4259
4260 break;
4261 }
4262
4263 putchar(m_ch);
4264 fflush(stdout);
4265
4266 wxThread::Sleep(100);
4267 }
4268
4269 return 0;
4270 }
4271
4272 void MyDetachedThread::OnExit()
4273 {
4274 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4275
4276 wxCriticalSectionLocker lock(gs_critsect);
4277 if ( !--gs_counter && !m_cancelled )
4278 gs_cond.Signal();
4279 }
4280
4281 void TestDetachedThreads()
4282 {
4283 puts("\n*** Testing detached threads ***");
4284
4285 static const size_t nThreads = 3;
4286 MyDetachedThread *threads[nThreads];
4287 size_t n;
4288 for ( n = 0; n < nThreads; n++ )
4289 {
4290 threads[n] = new MyDetachedThread(10, 'A' + n);
4291 }
4292
4293 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
4294 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
4295
4296 for ( n = 0; n < nThreads; n++ )
4297 {
4298 threads[n]->Run();
4299 }
4300
4301 // wait until all threads terminate
4302 gs_cond.Wait();
4303
4304 puts("");
4305 }
4306
4307 void TestJoinableThreads()
4308 {
4309 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4310
4311 // calc 10! in the background
4312 MyJoinableThread thread(10);
4313 thread.Run();
4314
4315 printf("\nThread terminated with exit code %lu.\n",
4316 (unsigned long)thread.Wait());
4317 }
4318
4319 void TestThreadSuspend()
4320 {
4321 puts("\n*** Testing thread suspend/resume functions ***");
4322
4323 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
4324
4325 thread->Run();
4326
4327 // this is for this demo only, in a real life program we'd use another
4328 // condition variable which would be signaled from wxThread::Entry() to
4329 // tell us that the thread really started running - but here just wait a
4330 // bit and hope that it will be enough (the problem is, of course, that
4331 // the thread might still not run when we call Pause() which will result
4332 // in an error)
4333 wxThread::Sleep(300);
4334
4335 for ( size_t n = 0; n < 3; n++ )
4336 {
4337 thread->Pause();
4338
4339 puts("\nThread suspended");
4340 if ( n > 0 )
4341 {
4342 // don't sleep but resume immediately the first time
4343 wxThread::Sleep(300);
4344 }
4345 puts("Going to resume the thread");
4346
4347 thread->Resume();
4348 }
4349
4350 puts("Waiting until it terminates now");
4351
4352 // wait until the thread terminates
4353 gs_cond.Wait();
4354
4355 puts("");
4356 }
4357
4358 void TestThreadDelete()
4359 {
4360 // As above, using Sleep() is only for testing here - we must use some
4361 // synchronisation object instead to ensure that the thread is still
4362 // running when we delete it - deleting a detached thread which already
4363 // terminated will lead to a crash!
4364
4365 puts("\n*** Testing thread delete function ***");
4366
4367 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
4368
4369 thread0->Delete();
4370
4371 puts("\nDeleted a thread which didn't start to run yet.");
4372
4373 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
4374
4375 thread1->Run();
4376
4377 wxThread::Sleep(300);
4378
4379 thread1->Delete();
4380
4381 puts("\nDeleted a running thread.");
4382
4383 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
4384
4385 thread2->Run();
4386
4387 wxThread::Sleep(300);
4388
4389 thread2->Pause();
4390
4391 thread2->Delete();
4392
4393 puts("\nDeleted a sleeping thread.");
4394
4395 MyJoinableThread thread3(20);
4396 thread3.Run();
4397
4398 thread3.Delete();
4399
4400 puts("\nDeleted a joinable thread.");
4401
4402 MyJoinableThread thread4(2);
4403 thread4.Run();
4404
4405 wxThread::Sleep(300);
4406
4407 thread4.Delete();
4408
4409 puts("\nDeleted a joinable thread which already terminated.");
4410
4411 puts("");
4412 }
4413
4414 #endif // TEST_THREADS
4415
4416 // ----------------------------------------------------------------------------
4417 // arrays
4418 // ----------------------------------------------------------------------------
4419
4420 #ifdef TEST_ARRAYS
4421
4422 static void PrintArray(const char* name, const wxArrayString& array)
4423 {
4424 printf("Dump of the array '%s'\n", name);
4425
4426 size_t nCount = array.GetCount();
4427 for ( size_t n = 0; n < nCount; n++ )
4428 {
4429 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
4430 }
4431 }
4432
4433 static void PrintArray(const char* name, const wxArrayInt& array)
4434 {
4435 printf("Dump of the array '%s'\n", name);
4436
4437 size_t nCount = array.GetCount();
4438 for ( size_t n = 0; n < nCount; n++ )
4439 {
4440 printf("\t%s[%u] = %d\n", name, n, array[n]);
4441 }
4442 }
4443
4444 int wxCMPFUNC_CONV StringLenCompare(const wxString& first,
4445 const wxString& second)
4446 {
4447 return first.length() - second.length();
4448 }
4449
4450 int wxCMPFUNC_CONV IntCompare(int *first,
4451 int *second)
4452 {
4453 return *first - *second;
4454 }
4455
4456 int wxCMPFUNC_CONV IntRevCompare(int *first,
4457 int *second)
4458 {
4459 return *second - *first;
4460 }
4461
4462 static void TestArrayOfInts()
4463 {
4464 puts("*** Testing wxArrayInt ***\n");
4465
4466 wxArrayInt a;
4467 a.Add(1);
4468 a.Add(17);
4469 a.Add(5);
4470 a.Add(3);
4471
4472 puts("Initially:");
4473 PrintArray("a", a);
4474
4475 puts("After sort:");
4476 a.Sort(IntCompare);
4477 PrintArray("a", a);
4478
4479 puts("After reverse sort:");
4480 a.Sort(IntRevCompare);
4481 PrintArray("a", a);
4482 }
4483
4484 #include "wx/dynarray.h"
4485
4486 WX_DECLARE_OBJARRAY(Bar, ArrayBars);
4487 #include "wx/arrimpl.cpp"
4488 WX_DEFINE_OBJARRAY(ArrayBars);
4489
4490 static void TestArrayOfObjects()
4491 {
4492 puts("*** Testing wxObjArray ***\n");
4493
4494 {
4495 ArrayBars bars;
4496 Bar bar("second bar");
4497
4498 printf("Initially: %u objects in the array, %u objects total.\n",
4499 bars.GetCount(), Bar::GetNumber());
4500
4501 bars.Add(new Bar("first bar"));
4502 bars.Add(bar);
4503
4504 printf("Now: %u objects in the array, %u objects total.\n",
4505 bars.GetCount(), Bar::GetNumber());
4506
4507 bars.Empty();
4508
4509 printf("After Empty(): %u objects in the array, %u objects total.\n",
4510 bars.GetCount(), Bar::GetNumber());
4511 }
4512
4513 printf("Finally: no more objects in the array, %u objects total.\n",
4514 Bar::GetNumber());
4515 }
4516
4517 #endif // TEST_ARRAYS
4518
4519 // ----------------------------------------------------------------------------
4520 // strings
4521 // ----------------------------------------------------------------------------
4522
4523 #ifdef TEST_STRINGS
4524
4525 #include "wx/timer.h"
4526 #include "wx/tokenzr.h"
4527
4528 static void TestStringConstruction()
4529 {
4530 puts("*** Testing wxString constructores ***");
4531
4532 #define TEST_CTOR(args, res) \
4533 { \
4534 wxString s args ; \
4535 printf("wxString%s = %s ", #args, s.c_str()); \
4536 if ( s == res ) \
4537 { \
4538 puts("(ok)"); \
4539 } \
4540 else \
4541 { \
4542 printf("(ERROR: should be %s)\n", res); \
4543 } \
4544 }
4545
4546 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4547 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4548 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4549 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4550
4551 static const wxChar *s = _T("?really!");
4552 const wxChar *start = wxStrchr(s, _T('r'));
4553 const wxChar *end = wxStrchr(s, _T('!'));
4554 TEST_CTOR((start, end), _T("really"));
4555
4556 puts("");
4557 }
4558
4559 static void TestString()
4560 {
4561 wxStopWatch sw;
4562
4563 wxString a, b, c;
4564
4565 a.reserve (128);
4566 b.reserve (128);
4567 c.reserve (128);
4568
4569 for (int i = 0; i < 1000000; ++i)
4570 {
4571 a = "Hello";
4572 b = " world";
4573 c = "! How'ya doin'?";
4574 a += b;
4575 a += c;
4576 c = "Hello world! What's up?";
4577 if (c != a)
4578 c = "Doh!";
4579 }
4580
4581 printf ("TestString elapsed time: %ld\n", sw.Time());
4582 }
4583
4584 static void TestPChar()
4585 {
4586 wxStopWatch sw;
4587
4588 char a [128];
4589 char b [128];
4590 char c [128];
4591
4592 for (int i = 0; i < 1000000; ++i)
4593 {
4594 strcpy (a, "Hello");
4595 strcpy (b, " world");
4596 strcpy (c, "! How'ya doin'?");
4597 strcat (a, b);
4598 strcat (a, c);
4599 strcpy (c, "Hello world! What's up?");
4600 if (strcmp (c, a) == 0)
4601 strcpy (c, "Doh!");
4602 }
4603
4604 printf ("TestPChar elapsed time: %ld\n", sw.Time());
4605 }
4606
4607 static void TestStringSub()
4608 {
4609 wxString s("Hello, world!");
4610
4611 puts("*** Testing wxString substring extraction ***");
4612
4613 printf("String = '%s'\n", s.c_str());
4614 printf("Left(5) = '%s'\n", s.Left(5).c_str());
4615 printf("Right(6) = '%s'\n", s.Right(6).c_str());
4616 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4617 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
4618 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
4619 printf("substr(3) = '%s'\n", s.substr(3).c_str());
4620
4621 static const wxChar *prefixes[] =
4622 {
4623 _T("Hello"),
4624 _T("Hello, "),
4625 _T("Hello, world!"),
4626 _T("Hello, world!!!"),
4627 _T(""),
4628 _T("Goodbye"),
4629 _T("Hi"),
4630 };
4631
4632 for ( size_t n = 0; n < WXSIZEOF(prefixes); n++ )
4633 {
4634 wxString prefix = prefixes[n], rest;
4635 bool rc = s.StartsWith(prefix, &rest);
4636 printf("StartsWith('%s') = %s", prefix.c_str(), rc ? "TRUE" : "FALSE");
4637 if ( rc )
4638 {
4639 printf(" (the rest is '%s')\n", rest.c_str());
4640 }
4641 else
4642 {
4643 putchar('\n');
4644 }
4645 }
4646
4647 puts("");
4648 }
4649
4650 static void TestStringFormat()
4651 {
4652 puts("*** Testing wxString formatting ***");
4653
4654 wxString s;
4655 s.Printf("%03d", 18);
4656
4657 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4658 printf("Number 18: %s\n", s.c_str());
4659
4660 puts("");
4661 }
4662
4663 // returns "not found" for npos, value for all others
4664 static wxString PosToString(size_t res)
4665 {
4666 wxString s = res == wxString::npos ? wxString(_T("not found"))
4667 : wxString::Format(_T("%u"), res);
4668 return s;
4669 }
4670
4671 static void TestStringFind()
4672 {
4673 puts("*** Testing wxString find() functions ***");
4674
4675 static const wxChar *strToFind = _T("ell");
4676 static const struct StringFindTest
4677 {
4678 const wxChar *str;
4679 size_t start,
4680 result; // of searching "ell" in str
4681 } findTestData[] =
4682 {
4683 { _T("Well, hello world"), 0, 1 },
4684 { _T("Well, hello world"), 6, 7 },
4685 { _T("Well, hello world"), 9, wxString::npos },
4686 };
4687
4688 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
4689 {
4690 const StringFindTest& ft = findTestData[n];
4691 size_t res = wxString(ft.str).find(strToFind, ft.start);
4692
4693 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4694 strToFind, ft.str, ft.start, PosToString(res).c_str());
4695
4696 size_t resTrue = ft.result;
4697 if ( res == resTrue )
4698 {
4699 puts(_T("(ok)"));
4700 }
4701 else
4702 {
4703 printf(_T("(ERROR: should be %s)\n"),
4704 PosToString(resTrue).c_str());
4705 }
4706 }
4707
4708 puts("");
4709 }
4710
4711 static void TestStringTokenizer()
4712 {
4713 puts("*** Testing wxStringTokenizer ***");
4714
4715 static const wxChar *modeNames[] =
4716 {
4717 _T("default"),
4718 _T("return empty"),
4719 _T("return all empty"),
4720 _T("with delims"),
4721 _T("like strtok"),
4722 };
4723
4724 static const struct StringTokenizerTest
4725 {
4726 const wxChar *str; // string to tokenize
4727 const wxChar *delims; // delimiters to use
4728 size_t count; // count of token
4729 wxStringTokenizerMode mode; // how should we tokenize it
4730 } tokenizerTestData[] =
4731 {
4732 { _T(""), _T(" "), 0 },
4733 { _T("Hello, world"), _T(" "), 2 },
4734 { _T("Hello, world "), _T(" "), 2 },
4735 { _T("Hello, world"), _T(","), 2 },
4736 { _T("Hello, world!"), _T(",!"), 2 },
4737 { _T("Hello,, world!"), _T(",!"), 3 },
4738 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
4739 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4740 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
4741 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
4742 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
4743 { _T("01/02/99"), _T("/-"), 3 },
4744 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
4745 };
4746
4747 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
4748 {
4749 const StringTokenizerTest& tt = tokenizerTestData[n];
4750 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
4751
4752 size_t count = tkz.CountTokens();
4753 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4754 MakePrintable(tt.str).c_str(),
4755 count,
4756 MakePrintable(tt.delims).c_str(),
4757 modeNames[tkz.GetMode()]);
4758 if ( count == tt.count )
4759 {
4760 puts(_T("(ok)"));
4761 }
4762 else
4763 {
4764 printf(_T("(ERROR: should be %u)\n"), tt.count);
4765
4766 continue;
4767 }
4768
4769 // if we emulate strtok(), check that we do it correctly
4770 wxChar *buf, *s = NULL, *last;
4771
4772 if ( tkz.GetMode() == wxTOKEN_STRTOK )
4773 {
4774 buf = new wxChar[wxStrlen(tt.str) + 1];
4775 wxStrcpy(buf, tt.str);
4776
4777 s = wxStrtok(buf, tt.delims, &last);
4778 }
4779 else
4780 {
4781 buf = NULL;
4782 }
4783
4784 // now show the tokens themselves
4785 size_t count2 = 0;
4786 while ( tkz.HasMoreTokens() )
4787 {
4788 wxString token = tkz.GetNextToken();
4789
4790 printf(_T("\ttoken %u: '%s'"),
4791 ++count2,
4792 MakePrintable(token).c_str());
4793
4794 if ( buf )
4795 {
4796 if ( token == s )
4797 {
4798 puts(" (ok)");
4799 }
4800 else
4801 {
4802 printf(" (ERROR: should be %s)\n", s);
4803 }
4804
4805 s = wxStrtok(NULL, tt.delims, &last);
4806 }
4807 else
4808 {
4809 // nothing to compare with
4810 puts("");
4811 }
4812 }
4813
4814 if ( count2 != count )
4815 {
4816 puts(_T("\tERROR: token count mismatch"));
4817 }
4818
4819 delete [] buf;
4820 }
4821
4822 puts("");
4823 }
4824
4825 static void TestStringReplace()
4826 {
4827 puts("*** Testing wxString::replace ***");
4828
4829 static const struct StringReplaceTestData
4830 {
4831 const wxChar *original; // original test string
4832 size_t start, len; // the part to replace
4833 const wxChar *replacement; // the replacement string
4834 const wxChar *result; // and the expected result
4835 } stringReplaceTestData[] =
4836 {
4837 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4838 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4839 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4840 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4841 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4842 };
4843
4844 for ( size_t n = 0; n < WXSIZEOF(stringReplaceTestData); n++ )
4845 {
4846 const StringReplaceTestData data = stringReplaceTestData[n];
4847
4848 wxString original = data.original;
4849 original.replace(data.start, data.len, data.replacement);
4850
4851 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4852 data.original, data.start, data.len, data.replacement,
4853 original.c_str());
4854
4855 if ( original == data.result )
4856 {
4857 puts("(ok)");
4858 }
4859 else
4860 {
4861 wxPrintf(_T("(ERROR: should be '%s')\n"), data.result);
4862 }
4863 }
4864
4865 puts("");
4866 }
4867
4868 static void TestStringMatch()
4869 {
4870 wxPuts(_T("*** Testing wxString::Matches() ***"));
4871
4872 static const struct StringMatchTestData
4873 {
4874 const wxChar *text;
4875 const wxChar *wildcard;
4876 bool matches;
4877 } stringMatchTestData[] =
4878 {
4879 { _T("foobar"), _T("foo*"), 1 },
4880 { _T("foobar"), _T("*oo*"), 1 },
4881 { _T("foobar"), _T("*bar"), 1 },
4882 { _T("foobar"), _T("??????"), 1 },
4883 { _T("foobar"), _T("f??b*"), 1 },
4884 { _T("foobar"), _T("f?b*"), 0 },
4885 { _T("foobar"), _T("*goo*"), 0 },
4886 { _T("foobar"), _T("*foo"), 0 },
4887 { _T("foobarfoo"), _T("*foo"), 1 },
4888 { _T(""), _T("*"), 1 },
4889 { _T(""), _T("?"), 0 },
4890 };
4891
4892 for ( size_t n = 0; n < WXSIZEOF(stringMatchTestData); n++ )
4893 {
4894 const StringMatchTestData& data = stringMatchTestData[n];
4895 bool matches = wxString(data.text).Matches(data.wildcard);
4896 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4897 data.wildcard,
4898 matches ? _T("matches") : _T("doesn't match"),
4899 data.text,
4900 matches == data.matches ? _T("ok") : _T("ERROR"));
4901 }
4902
4903 wxPuts(_T(""));
4904 }
4905
4906 #endif // TEST_STRINGS
4907
4908 // ----------------------------------------------------------------------------
4909 // entry point
4910 // ----------------------------------------------------------------------------
4911
4912 int main(int argc, char **argv)
4913 {
4914 wxInitializer initializer;
4915 if ( !initializer )
4916 {
4917 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
4918
4919 return -1;
4920 }
4921
4922 #ifdef TEST_SNGLINST
4923 wxSingleInstanceChecker checker;
4924 if ( checker.Create(_T(".wxconsole.lock")) )
4925 {
4926 if ( checker.IsAnotherRunning() )
4927 {
4928 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4929
4930 return 1;
4931 }
4932
4933 // wait some time to give time to launch another instance
4934 wxPrintf(_T("Press \"Enter\" to continue..."));
4935 wxFgetc(stdin);
4936 }
4937 else // failed to create
4938 {
4939 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4940 }
4941 #endif // TEST_SNGLINST
4942
4943 #ifdef TEST_CHARSET
4944 TestCharset();
4945 #endif // TEST_CHARSET
4946
4947 #ifdef TEST_CMDLINE
4948 static const wxCmdLineEntryDesc cmdLineDesc[] =
4949 {
4950 { wxCMD_LINE_SWITCH, _T("h"), _T("help"), "show this help message",
4951 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
4952 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
4953 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
4954
4955 { wxCMD_LINE_OPTION, "o", "output", "output file" },
4956 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
4957 { wxCMD_LINE_OPTION, "s", "size", "output block size",
4958 wxCMD_LINE_VAL_NUMBER },
4959 { wxCMD_LINE_OPTION, "d", "date", "output file date",
4960 wxCMD_LINE_VAL_DATE },
4961
4962 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
4963 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
4964
4965 { wxCMD_LINE_NONE }
4966 };
4967
4968 wxCmdLineParser parser(cmdLineDesc, argc, argv);
4969
4970 parser.AddOption("project_name", "", "full path to project file",
4971 wxCMD_LINE_VAL_STRING,
4972 wxCMD_LINE_OPTION_MANDATORY | wxCMD_LINE_NEEDS_SEPARATOR);
4973
4974 switch ( parser.Parse() )
4975 {
4976 case -1:
4977 wxLogMessage("Help was given, terminating.");
4978 break;
4979
4980 case 0:
4981 ShowCmdLine(parser);
4982 break;
4983
4984 default:
4985 wxLogMessage("Syntax error detected, aborting.");
4986 break;
4987 }
4988 #endif // TEST_CMDLINE
4989
4990 #ifdef TEST_STRINGS
4991 if ( 0 )
4992 {
4993 TestPChar();
4994 TestString();
4995 TestStringSub();
4996 TestStringConstruction();
4997 TestStringFormat();
4998 TestStringFind();
4999 TestStringTokenizer();
5000 TestStringReplace();
5001 }
5002 TestStringMatch();
5003 #endif // TEST_STRINGS
5004
5005 #ifdef TEST_ARRAYS
5006 if ( 0 )
5007 {
5008 wxArrayString a1;
5009 a1.Add("tiger");
5010 a1.Add("cat");
5011 a1.Add("lion");
5012 a1.Add("dog");
5013 a1.Add("human");
5014 a1.Add("ape");
5015
5016 puts("*** Initially:");
5017
5018 PrintArray("a1", a1);
5019
5020 wxArrayString a2(a1);
5021 PrintArray("a2", a2);
5022
5023 wxSortedArrayString a3(a1);
5024 PrintArray("a3", a3);
5025
5026 puts("*** After deleting a string from a1");
5027 a1.Remove(2);
5028
5029 PrintArray("a1", a1);
5030 PrintArray("a2", a2);
5031 PrintArray("a3", a3);
5032
5033 puts("*** After reassigning a1 to a2 and a3");
5034 a3 = a2 = a1;
5035 PrintArray("a2", a2);
5036 PrintArray("a3", a3);
5037
5038 puts("*** After sorting a1");
5039 a1.Sort();
5040 PrintArray("a1", a1);
5041
5042 puts("*** After sorting a1 in reverse order");
5043 a1.Sort(TRUE);
5044 PrintArray("a1", a1);
5045
5046 puts("*** After sorting a1 by the string length");
5047 a1.Sort(StringLenCompare);
5048 PrintArray("a1", a1);
5049
5050 TestArrayOfObjects();
5051 }
5052 TestArrayOfInts();
5053 #endif // TEST_ARRAYS
5054
5055 #ifdef TEST_DIR
5056 if ( 0 )
5057 TestDirEnum();
5058 TestDirTraverse();
5059 #endif // TEST_DIR
5060
5061 #ifdef TEST_DLLLOADER
5062 TestDllLoad();
5063 #endif // TEST_DLLLOADER
5064
5065 #ifdef TEST_ENVIRON
5066 TestEnvironment();
5067 #endif // TEST_ENVIRON
5068
5069 #ifdef TEST_EXECUTE
5070 TestExecute();
5071 #endif // TEST_EXECUTE
5072
5073 #ifdef TEST_FILECONF
5074 TestFileConfRead();
5075 #endif // TEST_FILECONF
5076
5077 #ifdef TEST_LIST
5078 TestListCtor();
5079 #endif // TEST_LIST
5080
5081 #ifdef TEST_LOCALE
5082 TestDefaultLang();
5083 #endif // TEST_LOCALE
5084
5085 #ifdef TEST_LOG
5086 wxString s;
5087 for ( size_t n = 0; n < 8000; n++ )
5088 {
5089 s << (char)('A' + (n % 26));
5090 }
5091
5092 wxString msg;
5093 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
5094
5095 // this one shouldn't be truncated
5096 printf(msg);
5097
5098 // but this one will because log functions use fixed size buffer
5099 // (note that it doesn't need '\n' at the end neither - will be added
5100 // by wxLog anyhow)
5101 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
5102 #endif // TEST_LOG
5103
5104 #ifdef TEST_FILE
5105 if ( 0 )
5106 {
5107 TestFileRead();
5108 TestTextFileRead();
5109 }
5110 TestFileCopy();
5111 #endif // TEST_FILE
5112
5113 #ifdef TEST_FILENAME
5114 TestFileNameSplit();
5115 if ( 0 )
5116 {
5117 TestFileNameConstruction();
5118 TestFileNameCwd();
5119 TestFileNameComparison();
5120 TestFileNameOperations();
5121 }
5122 #endif // TEST_FILENAME
5123
5124 #ifdef TEST_FILETIME
5125 TestFileGetTimes();
5126 TestFileSetTimes();
5127 #endif // TEST_FILETIME
5128
5129 #ifdef TEST_FTP
5130 wxLog::AddTraceMask(FTP_TRACE_MASK);
5131 if ( TestFtpConnect() )
5132 {
5133 TestFtpFileSize();
5134 if ( 0 )
5135 {
5136 TestFtpList();
5137 TestFtpDownload();
5138 TestFtpMisc();
5139 TestFtpUpload();
5140 }
5141 if ( 0 )
5142 TestFtpInteractive();
5143 }
5144 //else: connecting to the FTP server failed
5145
5146 if ( 0 )
5147 TestFtpWuFtpd();
5148 #endif // TEST_FTP
5149
5150 #ifdef TEST_THREADS
5151 int nCPUs = wxThread::GetCPUCount();
5152 printf("This system has %d CPUs\n", nCPUs);
5153 if ( nCPUs != -1 )
5154 wxThread::SetConcurrency(nCPUs);
5155
5156 if ( argc > 1 && argv[1][0] == 't' )
5157 wxLog::AddTraceMask("thread");
5158
5159 if ( 1 )
5160 TestDetachedThreads();
5161 if ( 1 )
5162 TestJoinableThreads();
5163 if ( 1 )
5164 TestThreadSuspend();
5165 if ( 1 )
5166 TestThreadDelete();
5167
5168 #endif // TEST_THREADS
5169
5170 #ifdef TEST_LONGLONG
5171 // seed pseudo random generator
5172 srand((unsigned)time(NULL));
5173
5174 if ( 0 )
5175 {
5176 TestSpeed();
5177 }
5178 if ( 0 )
5179 {
5180 TestMultiplication();
5181 TestDivision();
5182 TestAddition();
5183 TestLongLongConversion();
5184 TestBitOperations();
5185 TestLongLongComparison();
5186 }
5187 TestLongLongPrint();
5188 #endif // TEST_LONGLONG
5189
5190 #ifdef TEST_HASH
5191 TestHash();
5192 #endif // TEST_HASH
5193
5194 #ifdef TEST_MIME
5195 wxLog::AddTraceMask(_T("mime"));
5196 if ( 1 )
5197 {
5198 TestMimeEnum();
5199 TestMimeOverride();
5200 TestMimeFilename();
5201 }
5202 else
5203 TestMimeAssociate();
5204 #endif // TEST_MIME
5205
5206 #ifdef TEST_INFO_FUNCTIONS
5207 TestDiskInfo();
5208 if ( 0 )
5209 {
5210 TestOsInfo();
5211 TestUserInfo();
5212 }
5213 #endif // TEST_INFO_FUNCTIONS
5214
5215 #ifdef TEST_PATHLIST
5216 TestPathList();
5217 #endif // TEST_PATHLIST
5218
5219 #ifdef TEST_REGCONF
5220 TestRegConfWrite();
5221 #endif // TEST_REGCONF
5222
5223 #ifdef TEST_REGEX
5224 // TODO: write a real test using src/regex/tests file
5225 if ( 0 )
5226 {
5227 TestRegExCompile();
5228 TestRegExMatch();
5229 TestRegExSubmatch();
5230 TestRegExInteractive();
5231 }
5232 TestRegExReplacement();
5233 #endif // TEST_REGEX
5234
5235 #ifdef TEST_REGISTRY
5236 if ( 0 )
5237 TestRegistryRead();
5238 TestRegistryAssociation();
5239 #endif // TEST_REGISTRY
5240
5241 #ifdef TEST_SOCKETS
5242 if ( 0 )
5243 {
5244 TestSocketServer();
5245 }
5246 TestSocketClient();
5247 #endif // TEST_SOCKETS
5248
5249 #ifdef TEST_STREAMS
5250 if ( 0 )
5251 TestFileStream();
5252 TestMemoryStream();
5253 #endif // TEST_STREAMS
5254
5255 #ifdef TEST_TIMER
5256 TestStopWatch();
5257 #endif // TEST_TIMER
5258
5259 #ifdef TEST_DATETIME
5260 if ( 0 )
5261 {
5262 TestTimeSet();
5263 TestTimeStatic();
5264 TestTimeRange();
5265 TestTimeZones();
5266 TestTimeTicks();
5267 TestTimeJDN();
5268 TestTimeDST();
5269 TestTimeWDays();
5270 TestTimeWNumber();
5271 TestTimeParse();
5272 TestTimeArithmetics();
5273 TestTimeHolidays();
5274 TestTimeFormat();
5275 TestTimeMS();
5276
5277 TestTimeZoneBug();
5278 }
5279 TestTimeSpanFormat();
5280 if ( 0 )
5281 TestDateTimeInteractive();
5282 #endif // TEST_DATETIME
5283
5284 #ifdef TEST_USLEEP
5285 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5286 wxUsleep(3000);
5287 #endif // TEST_USLEEP
5288
5289 #ifdef TEST_VCARD
5290 if ( 0 )
5291 TestVCardRead();
5292 TestVCardWrite();
5293 #endif // TEST_VCARD
5294
5295 #ifdef TEST_WCHAR
5296 TestUtf8();
5297 #endif // TEST_WCHAR
5298
5299 #ifdef TEST_ZIP
5300 if ( 0 )
5301 TestZipStreamRead();
5302 TestZipFileSystem();
5303 #endif // TEST_ZIP
5304
5305 #ifdef TEST_ZLIB
5306 if ( 0 )
5307 TestZlibStreamWrite();
5308 TestZlibStreamRead();
5309 #endif // TEST_ZLIB
5310
5311 return 0;
5312 }
5313