]> git.saurik.com Git - wxWidgets.git/blob - samples/console/console.cpp
added missing const
[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)(const 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 #include "wx/datetime.h"
3154
3155 // the test data
3156 struct Date
3157 {
3158 wxDateTime::wxDateTime_t day;
3159 wxDateTime::Month month;
3160 int year;
3161 wxDateTime::wxDateTime_t hour, min, sec;
3162 double jdn;
3163 wxDateTime::WeekDay wday;
3164 time_t gmticks, ticks;
3165
3166 void Init(const wxDateTime::Tm& tm)
3167 {
3168 day = tm.mday;
3169 month = tm.mon;
3170 year = tm.year;
3171 hour = tm.hour;
3172 min = tm.min;
3173 sec = tm.sec;
3174 jdn = 0.0;
3175 gmticks = ticks = -1;
3176 }
3177
3178 wxDateTime DT() const
3179 { return wxDateTime(day, month, year, hour, min, sec); }
3180
3181 bool SameDay(const wxDateTime::Tm& tm) const
3182 {
3183 return day == tm.mday && month == tm.mon && year == tm.year;
3184 }
3185
3186 wxString Format() const
3187 {
3188 wxString s;
3189 s.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3190 hour, min, sec,
3191 wxDateTime::GetMonthName(month).c_str(),
3192 day,
3193 abs(wxDateTime::ConvertYearToBC(year)),
3194 year > 0 ? "AD" : "BC");
3195 return s;
3196 }
3197
3198 wxString FormatDate() const
3199 {
3200 wxString s;
3201 s.Printf("%02d-%s-%4d%s",
3202 day,
3203 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
3204 abs(wxDateTime::ConvertYearToBC(year)),
3205 year > 0 ? "AD" : "BC");
3206 return s;
3207 }
3208 };
3209
3210 static const Date testDates[] =
3211 {
3212 { 1, wxDateTime::Jan, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu, 0, -3600 },
3213 { 21, wxDateTime::Jan, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon, -1, -1 },
3214 { 29, wxDateTime::May, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat, 202219200, 202212000 },
3215 { 29, wxDateTime::Feb, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun, 194400000, 194396400 },
3216 { 1, wxDateTime::Jan, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon, -1, -1 },
3217 { 1, wxDateTime::Jan, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon, -1, -1 },
3218 { 15, wxDateTime::Oct, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri, -1, -1 },
3219 { 4, wxDateTime::Oct, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon, -1, -1 },
3220 { 1, wxDateTime::Mar, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu, -1, -1 },
3221 { 1, wxDateTime::Jan, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon, -1, -1 },
3222 { 31, wxDateTime::Dec, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun, -1, -1 },
3223 { 1, wxDateTime::Jan, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat, -1, -1 },
3224 { 12, wxDateTime::Aug, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri, -1, -1 },
3225 { 12, wxDateTime::Aug, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat, -1, -1 },
3226 { 24, wxDateTime::Nov, -4713, 00, 00, 00, -0.5, wxDateTime::Mon, -1, -1 },
3227 };
3228
3229 // this test miscellaneous static wxDateTime functions
3230 static void TestTimeStatic()
3231 {
3232 puts("\n*** wxDateTime static methods test ***");
3233
3234 // some info about the current date
3235 int year = wxDateTime::GetCurrentYear();
3236 printf("Current year %d is %sa leap one and has %d days.\n",
3237 year,
3238 wxDateTime::IsLeapYear(year) ? "" : "not ",
3239 wxDateTime::GetNumberOfDays(year));
3240
3241 wxDateTime::Month month = wxDateTime::GetCurrentMonth();
3242 printf("Current month is '%s' ('%s') and it has %d days\n",
3243 wxDateTime::GetMonthName(month, wxDateTime::Name_Abbr).c_str(),
3244 wxDateTime::GetMonthName(month).c_str(),
3245 wxDateTime::GetNumberOfDays(month));
3246
3247 // leap year logic
3248 static const size_t nYears = 5;
3249 static const size_t years[2][nYears] =
3250 {
3251 // first line: the years to test
3252 { 1990, 1976, 2000, 2030, 1984, },
3253
3254 // second line: TRUE if leap, FALSE otherwise
3255 { FALSE, TRUE, TRUE, FALSE, TRUE }
3256 };
3257
3258 for ( size_t n = 0; n < nYears; n++ )
3259 {
3260 int year = years[0][n];
3261 bool should = years[1][n] != 0,
3262 is = wxDateTime::IsLeapYear(year);
3263
3264 printf("Year %d is %sa leap year (%s)\n",
3265 year,
3266 is ? "" : "not ",
3267 should == is ? "ok" : "ERROR");
3268
3269 wxASSERT( should == wxDateTime::IsLeapYear(year) );
3270 }
3271 }
3272
3273 // test constructing wxDateTime objects
3274 static void TestTimeSet()
3275 {
3276 puts("\n*** wxDateTime construction test ***");
3277
3278 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3279 {
3280 const Date& d1 = testDates[n];
3281 wxDateTime dt = d1.DT();
3282
3283 Date d2;
3284 d2.Init(dt.GetTm());
3285
3286 wxString s1 = d1.Format(),
3287 s2 = d2.Format();
3288
3289 printf("Date: %s == %s (%s)\n",
3290 s1.c_str(), s2.c_str(),
3291 s1 == s2 ? "ok" : "ERROR");
3292 }
3293 }
3294
3295 // test time zones stuff
3296 static void TestTimeZones()
3297 {
3298 puts("\n*** wxDateTime timezone test ***");
3299
3300 wxDateTime now = wxDateTime::Now();
3301
3302 printf("Current GMT time:\t%s\n", now.Format("%c", wxDateTime::GMT0).c_str());
3303 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0).c_str());
3304 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST).c_str());
3305 printf("Current time in Paris:\t%s\n", now.Format("%c", wxDateTime::CET).c_str());
3306 printf(" Moscow:\t%s\n", now.Format("%c", wxDateTime::MSK).c_str());
3307 printf(" New York:\t%s\n", now.Format("%c", wxDateTime::EST).c_str());
3308
3309 wxDateTime::Tm tm = now.GetTm();
3310 if ( wxDateTime(tm) != now )
3311 {
3312 printf("ERROR: got %s instead of %s\n",
3313 wxDateTime(tm).Format().c_str(), now.Format().c_str());
3314 }
3315 }
3316
3317 // test some minimal support for the dates outside the standard range
3318 static void TestTimeRange()
3319 {
3320 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3321
3322 static const char *fmt = "%d-%b-%Y %H:%M:%S";
3323
3324 printf("Unix epoch:\t%s\n",
3325 wxDateTime(2440587.5).Format(fmt).c_str());
3326 printf("Feb 29, 0: \t%s\n",
3327 wxDateTime(29, wxDateTime::Feb, 0).Format(fmt).c_str());
3328 printf("JDN 0: \t%s\n",
3329 wxDateTime(0.0).Format(fmt).c_str());
3330 printf("Jan 1, 1AD:\t%s\n",
3331 wxDateTime(1, wxDateTime::Jan, 1).Format(fmt).c_str());
3332 printf("May 29, 2099:\t%s\n",
3333 wxDateTime(29, wxDateTime::May, 2099).Format(fmt).c_str());
3334 }
3335
3336 static void TestTimeTicks()
3337 {
3338 puts("\n*** wxDateTime ticks test ***");
3339
3340 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3341 {
3342 const Date& d = testDates[n];
3343 if ( d.ticks == -1 )
3344 continue;
3345
3346 wxDateTime dt = d.DT();
3347 long ticks = (dt.GetValue() / 1000).ToLong();
3348 printf("Ticks of %s:\t% 10ld", d.Format().c_str(), ticks);
3349 if ( ticks == d.ticks )
3350 {
3351 puts(" (ok)");
3352 }
3353 else
3354 {
3355 printf(" (ERROR: should be %ld, delta = %ld)\n",
3356 d.ticks, ticks - d.ticks);
3357 }
3358
3359 dt = d.DT().ToTimezone(wxDateTime::GMT0);
3360 ticks = (dt.GetValue() / 1000).ToLong();
3361 printf("GMtks of %s:\t% 10ld", d.Format().c_str(), ticks);
3362 if ( ticks == d.gmticks )
3363 {
3364 puts(" (ok)");
3365 }
3366 else
3367 {
3368 printf(" (ERROR: should be %ld, delta = %ld)\n",
3369 d.gmticks, ticks - d.gmticks);
3370 }
3371 }
3372
3373 puts("");
3374 }
3375
3376 // test conversions to JDN &c
3377 static void TestTimeJDN()
3378 {
3379 puts("\n*** wxDateTime to JDN test ***");
3380
3381 for ( size_t n = 0; n < WXSIZEOF(testDates); n++ )
3382 {
3383 const Date& d = testDates[n];
3384 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
3385 double jdn = dt.GetJulianDayNumber();
3386
3387 printf("JDN of %s is:\t% 15.6f", d.Format().c_str(), jdn);
3388 if ( jdn == d.jdn )
3389 {
3390 puts(" (ok)");
3391 }
3392 else
3393 {
3394 printf(" (ERROR: should be %f, delta = %f)\n",
3395 d.jdn, jdn - d.jdn);
3396 }
3397 }
3398 }
3399
3400 // test week days computation
3401 static void TestTimeWDays()
3402 {
3403 puts("\n*** wxDateTime weekday test ***");
3404
3405 // test GetWeekDay()
3406 size_t n;
3407 for ( n = 0; n < WXSIZEOF(testDates); n++ )
3408 {
3409 const Date& d = testDates[n];
3410 wxDateTime dt(d.day, d.month, d.year, d.hour, d.min, d.sec);
3411
3412 wxDateTime::WeekDay wday = dt.GetWeekDay();
3413 printf("%s is: %s",
3414 d.Format().c_str(),
3415 wxDateTime::GetWeekDayName(wday).c_str());
3416 if ( wday == d.wday )
3417 {
3418 puts(" (ok)");
3419 }
3420 else
3421 {
3422 printf(" (ERROR: should be %s)\n",
3423 wxDateTime::GetWeekDayName(d.wday).c_str());
3424 }
3425 }
3426
3427 puts("");
3428
3429 // test SetToWeekDay()
3430 struct WeekDateTestData
3431 {
3432 Date date; // the real date (precomputed)
3433 int nWeek; // its week index in the month
3434 wxDateTime::WeekDay wday; // the weekday
3435 wxDateTime::Month month; // the month
3436 int year; // and the year
3437
3438 wxString Format() const
3439 {
3440 wxString s, which;
3441 switch ( nWeek < -1 ? -nWeek : nWeek )
3442 {
3443 case 1: which = "first"; break;
3444 case 2: which = "second"; break;
3445 case 3: which = "third"; break;
3446 case 4: which = "fourth"; break;
3447 case 5: which = "fifth"; break;
3448
3449 case -1: which = "last"; break;
3450 }
3451
3452 if ( nWeek < -1 )
3453 {
3454 which += " from end";
3455 }
3456
3457 s.Printf("The %s %s of %s in %d",
3458 which.c_str(),
3459 wxDateTime::GetWeekDayName(wday).c_str(),
3460 wxDateTime::GetMonthName(month).c_str(),
3461 year);
3462
3463 return s;
3464 }
3465 };
3466
3467 // the array data was generated by the following python program
3468 /*
3469 from DateTime import *
3470 from whrandom import *
3471 from string import *
3472
3473 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3474 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3475
3476 week = DateTimeDelta(7)
3477
3478 for n in range(20):
3479 year = randint(1900, 2100)
3480 month = randint(1, 12)
3481 day = randint(1, 28)
3482 dt = DateTime(year, month, day)
3483 wday = dt.day_of_week
3484
3485 countFromEnd = choice([-1, 1])
3486 weekNum = 0;
3487
3488 while dt.month is month:
3489 dt = dt - countFromEnd * week
3490 weekNum = weekNum + countFromEnd
3491
3492 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3493
3494 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3495 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3496 */
3497
3498 static const WeekDateTestData weekDatesTestData[] =
3499 {
3500 { { 20, wxDateTime::Mar, 2045 }, 3, wxDateTime::Mon, wxDateTime::Mar, 2045 },
3501 { { 5, wxDateTime::Jun, 1985 }, -4, wxDateTime::Wed, wxDateTime::Jun, 1985 },
3502 { { 12, wxDateTime::Nov, 1961 }, -3, wxDateTime::Sun, wxDateTime::Nov, 1961 },
3503 { { 27, wxDateTime::Feb, 2093 }, -1, wxDateTime::Fri, wxDateTime::Feb, 2093 },
3504 { { 4, wxDateTime::Jul, 2070 }, -4, wxDateTime::Fri, wxDateTime::Jul, 2070 },
3505 { { 2, wxDateTime::Apr, 1906 }, -5, wxDateTime::Mon, wxDateTime::Apr, 1906 },
3506 { { 19, wxDateTime::Jul, 2023 }, -2, wxDateTime::Wed, wxDateTime::Jul, 2023 },
3507 { { 5, wxDateTime::May, 1958 }, -4, wxDateTime::Mon, wxDateTime::May, 1958 },
3508 { { 11, wxDateTime::Aug, 1900 }, 2, wxDateTime::Sat, wxDateTime::Aug, 1900 },
3509 { { 14, wxDateTime::Feb, 1945 }, 2, wxDateTime::Wed, wxDateTime::Feb, 1945 },
3510 { { 25, wxDateTime::Jul, 1967 }, -1, wxDateTime::Tue, wxDateTime::Jul, 1967 },
3511 { { 9, wxDateTime::May, 1916 }, -4, wxDateTime::Tue, wxDateTime::May, 1916 },
3512 { { 20, wxDateTime::Jun, 1927 }, 3, wxDateTime::Mon, wxDateTime::Jun, 1927 },
3513 { { 2, wxDateTime::Aug, 2000 }, 1, wxDateTime::Wed, wxDateTime::Aug, 2000 },
3514 { { 20, wxDateTime::Apr, 2044 }, 3, wxDateTime::Wed, wxDateTime::Apr, 2044 },
3515 { { 20, wxDateTime::Feb, 1932 }, -2, wxDateTime::Sat, wxDateTime::Feb, 1932 },
3516 { { 25, wxDateTime::Jul, 2069 }, 4, wxDateTime::Thu, wxDateTime::Jul, 2069 },
3517 { { 3, wxDateTime::Apr, 1925 }, 1, wxDateTime::Fri, wxDateTime::Apr, 1925 },
3518 { { 21, wxDateTime::Mar, 2093 }, 3, wxDateTime::Sat, wxDateTime::Mar, 2093 },
3519 { { 3, wxDateTime::Dec, 2074 }, -5, wxDateTime::Mon, wxDateTime::Dec, 2074 },
3520 };
3521
3522 static const char *fmt = "%d-%b-%Y";
3523
3524 wxDateTime dt;
3525 for ( n = 0; n < WXSIZEOF(weekDatesTestData); n++ )
3526 {
3527 const WeekDateTestData& wd = weekDatesTestData[n];
3528
3529 dt.SetToWeekDay(wd.wday, wd.nWeek, wd.month, wd.year);
3530
3531 printf("%s is %s", wd.Format().c_str(), dt.Format(fmt).c_str());
3532
3533 const Date& d = wd.date;
3534 if ( d.SameDay(dt.GetTm()) )
3535 {
3536 puts(" (ok)");
3537 }
3538 else
3539 {
3540 dt.Set(d.day, d.month, d.year);
3541
3542 printf(" (ERROR: should be %s)\n", dt.Format(fmt).c_str());
3543 }
3544 }
3545 }
3546
3547 // test the computation of (ISO) week numbers
3548 static void TestTimeWNumber()
3549 {
3550 puts("\n*** wxDateTime week number test ***");
3551
3552 struct WeekNumberTestData
3553 {
3554 Date date; // the date
3555 wxDateTime::wxDateTime_t week; // the week number in the year
3556 wxDateTime::wxDateTime_t wmon; // the week number in the month
3557 wxDateTime::wxDateTime_t wmon2; // same but week starts with Sun
3558 wxDateTime::wxDateTime_t dnum; // day number in the year
3559 };
3560
3561 // data generated with the following python script:
3562 /*
3563 from DateTime import *
3564 from whrandom import *
3565 from string import *
3566
3567 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3568 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3569
3570 def GetMonthWeek(dt):
3571 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3572 if weekNumMonth < 0:
3573 weekNumMonth = weekNumMonth + 53
3574 return weekNumMonth
3575
3576 def GetLastSundayBefore(dt):
3577 if dt.iso_week[2] == 7:
3578 return dt
3579 else:
3580 return dt - DateTimeDelta(dt.iso_week[2])
3581
3582 for n in range(20):
3583 year = randint(1900, 2100)
3584 month = randint(1, 12)
3585 day = randint(1, 28)
3586 dt = DateTime(year, month, day)
3587 dayNum = dt.day_of_year
3588 weekNum = dt.iso_week[1]
3589 weekNumMonth = GetMonthWeek(dt)
3590
3591 weekNumMonth2 = 0
3592 dtSunday = GetLastSundayBefore(dt)
3593
3594 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3595 weekNumMonth2 = weekNumMonth2 + 1
3596 dtSunday = dtSunday - DateTimeDelta(7)
3597
3598 data = { 'day': rjust(`day`, 2), \
3599 'month': monthNames[month - 1], \
3600 'year': year, \
3601 'weekNum': rjust(`weekNum`, 2), \
3602 'weekNumMonth': weekNumMonth, \
3603 'weekNumMonth2': weekNumMonth2, \
3604 'dayNum': rjust(`dayNum`, 3) }
3605
3606 print " { { %(day)s, "\
3607 "wxDateTime::%(month)s, "\
3608 "%(year)d }, "\
3609 "%(weekNum)s, "\
3610 "%(weekNumMonth)s, "\
3611 "%(weekNumMonth2)s, "\
3612 "%(dayNum)s }," % data
3613
3614 */
3615 static const WeekNumberTestData weekNumberTestDates[] =
3616 {
3617 { { 27, wxDateTime::Dec, 1966 }, 52, 5, 5, 361 },
3618 { { 22, wxDateTime::Jul, 1926 }, 29, 4, 4, 203 },
3619 { { 22, wxDateTime::Oct, 2076 }, 43, 4, 4, 296 },
3620 { { 1, wxDateTime::Jul, 1967 }, 26, 1, 1, 182 },
3621 { { 8, wxDateTime::Nov, 2004 }, 46, 2, 2, 313 },
3622 { { 21, wxDateTime::Mar, 1920 }, 12, 3, 4, 81 },
3623 { { 7, wxDateTime::Jan, 1965 }, 1, 2, 2, 7 },
3624 { { 19, wxDateTime::Oct, 1999 }, 42, 4, 4, 292 },
3625 { { 13, wxDateTime::Aug, 1955 }, 32, 2, 2, 225 },
3626 { { 18, wxDateTime::Jul, 2087 }, 29, 3, 3, 199 },
3627 { { 2, wxDateTime::Sep, 2028 }, 35, 1, 1, 246 },
3628 { { 28, wxDateTime::Jul, 1945 }, 30, 5, 4, 209 },
3629 { { 15, wxDateTime::Jun, 1901 }, 24, 3, 3, 166 },
3630 { { 10, wxDateTime::Oct, 1939 }, 41, 3, 2, 283 },
3631 { { 3, wxDateTime::Dec, 1965 }, 48, 1, 1, 337 },
3632 { { 23, wxDateTime::Feb, 1940 }, 8, 4, 4, 54 },
3633 { { 2, wxDateTime::Jan, 1987 }, 1, 1, 1, 2 },
3634 { { 11, wxDateTime::Aug, 2079 }, 32, 2, 2, 223 },
3635 { { 2, wxDateTime::Feb, 2063 }, 5, 1, 1, 33 },
3636 { { 16, wxDateTime::Oct, 1942 }, 42, 3, 3, 289 },
3637 };
3638
3639 for ( size_t n = 0; n < WXSIZEOF(weekNumberTestDates); n++ )
3640 {
3641 const WeekNumberTestData& wn = weekNumberTestDates[n];
3642 const Date& d = wn.date;
3643
3644 wxDateTime dt = d.DT();
3645
3646 wxDateTime::wxDateTime_t
3647 week = dt.GetWeekOfYear(wxDateTime::Monday_First),
3648 wmon = dt.GetWeekOfMonth(wxDateTime::Monday_First),
3649 wmon2 = dt.GetWeekOfMonth(wxDateTime::Sunday_First),
3650 dnum = dt.GetDayOfYear();
3651
3652 printf("%s: the day number is %d",
3653 d.FormatDate().c_str(), dnum);
3654 if ( dnum == wn.dnum )
3655 {
3656 printf(" (ok)");
3657 }
3658 else
3659 {
3660 printf(" (ERROR: should be %d)", wn.dnum);
3661 }
3662
3663 printf(", week in month is %d", wmon);
3664 if ( wmon == wn.wmon )
3665 {
3666 printf(" (ok)");
3667 }
3668 else
3669 {
3670 printf(" (ERROR: should be %d)", wn.wmon);
3671 }
3672
3673 printf(" or %d", wmon2);
3674 if ( wmon2 == wn.wmon2 )
3675 {
3676 printf(" (ok)");
3677 }
3678 else
3679 {
3680 printf(" (ERROR: should be %d)", wn.wmon2);
3681 }
3682
3683 printf(", week in year is %d", week);
3684 if ( week == wn.week )
3685 {
3686 puts(" (ok)");
3687 }
3688 else
3689 {
3690 printf(" (ERROR: should be %d)\n", wn.week);
3691 }
3692 }
3693 }
3694
3695 // test DST calculations
3696 static void TestTimeDST()
3697 {
3698 puts("\n*** wxDateTime DST test ***");
3699
3700 printf("DST is%s in effect now.\n\n",
3701 wxDateTime::Now().IsDST() ? "" : " not");
3702
3703 // taken from http://www.energy.ca.gov/daylightsaving.html
3704 static const Date datesDST[2][2004 - 1900 + 1] =
3705 {
3706 {
3707 { 1, wxDateTime::Apr, 1990 },
3708 { 7, wxDateTime::Apr, 1991 },
3709 { 5, wxDateTime::Apr, 1992 },
3710 { 4, wxDateTime::Apr, 1993 },
3711 { 3, wxDateTime::Apr, 1994 },
3712 { 2, wxDateTime::Apr, 1995 },
3713 { 7, wxDateTime::Apr, 1996 },
3714 { 6, wxDateTime::Apr, 1997 },
3715 { 5, wxDateTime::Apr, 1998 },
3716 { 4, wxDateTime::Apr, 1999 },
3717 { 2, wxDateTime::Apr, 2000 },
3718 { 1, wxDateTime::Apr, 2001 },
3719 { 7, wxDateTime::Apr, 2002 },
3720 { 6, wxDateTime::Apr, 2003 },
3721 { 4, wxDateTime::Apr, 2004 },
3722 },
3723 {
3724 { 28, wxDateTime::Oct, 1990 },
3725 { 27, wxDateTime::Oct, 1991 },
3726 { 25, wxDateTime::Oct, 1992 },
3727 { 31, wxDateTime::Oct, 1993 },
3728 { 30, wxDateTime::Oct, 1994 },
3729 { 29, wxDateTime::Oct, 1995 },
3730 { 27, wxDateTime::Oct, 1996 },
3731 { 26, wxDateTime::Oct, 1997 },
3732 { 25, wxDateTime::Oct, 1998 },
3733 { 31, wxDateTime::Oct, 1999 },
3734 { 29, wxDateTime::Oct, 2000 },
3735 { 28, wxDateTime::Oct, 2001 },
3736 { 27, wxDateTime::Oct, 2002 },
3737 { 26, wxDateTime::Oct, 2003 },
3738 { 31, wxDateTime::Oct, 2004 },
3739 }
3740 };
3741
3742 int year;
3743 for ( year = 1990; year < 2005; year++ )
3744 {
3745 wxDateTime dtBegin = wxDateTime::GetBeginDST(year, wxDateTime::USA),
3746 dtEnd = wxDateTime::GetEndDST(year, wxDateTime::USA);
3747
3748 printf("DST period in the US for year %d: from %s to %s",
3749 year, dtBegin.Format().c_str(), dtEnd.Format().c_str());
3750
3751 size_t n = year - 1990;
3752 const Date& dBegin = datesDST[0][n];
3753 const Date& dEnd = datesDST[1][n];
3754
3755 if ( dBegin.SameDay(dtBegin.GetTm()) && dEnd.SameDay(dtEnd.GetTm()) )
3756 {
3757 puts(" (ok)");
3758 }
3759 else
3760 {
3761 printf(" (ERROR: should be %s %d to %s %d)\n",
3762 wxDateTime::GetMonthName(dBegin.month).c_str(), dBegin.day,
3763 wxDateTime::GetMonthName(dEnd.month).c_str(), dEnd.day);
3764 }
3765 }
3766
3767 puts("");
3768
3769 for ( year = 1990; year < 2005; year++ )
3770 {
3771 printf("DST period in Europe for year %d: from %s to %s\n",
3772 year,
3773 wxDateTime::GetBeginDST(year, wxDateTime::Country_EEC).Format().c_str(),
3774 wxDateTime::GetEndDST(year, wxDateTime::Country_EEC).Format().c_str());
3775 }
3776 }
3777
3778 // test wxDateTime -> text conversion
3779 static void TestTimeFormat()
3780 {
3781 puts("\n*** wxDateTime formatting test ***");
3782
3783 // some information may be lost during conversion, so store what kind
3784 // of info should we recover after a round trip
3785 enum CompareKind
3786 {
3787 CompareNone, // don't try comparing
3788 CompareBoth, // dates and times should be identical
3789 CompareDate, // dates only
3790 CompareTime // time only
3791 };
3792
3793 static const struct
3794 {
3795 CompareKind compareKind;
3796 const char *format;
3797 } formatTestFormats[] =
3798 {
3799 { CompareBoth, "---> %c" },
3800 { CompareDate, "Date is %A, %d of %B, in year %Y" },
3801 { CompareBoth, "Date is %x, time is %X" },
3802 { CompareTime, "Time is %H:%M:%S or %I:%M:%S %p" },
3803 { CompareNone, "The day of year: %j, the week of year: %W" },
3804 { CompareDate, "ISO date without separators: %4Y%2m%2d" },
3805 };
3806
3807 static const Date formatTestDates[] =
3808 {
3809 { 29, wxDateTime::May, 1976, 18, 30, 00 },
3810 { 31, wxDateTime::Dec, 1999, 23, 30, 00 },
3811 #if 0
3812 // this test can't work for other centuries because it uses two digit
3813 // years in formats, so don't even try it
3814 { 29, wxDateTime::May, 2076, 18, 30, 00 },
3815 { 29, wxDateTime::Feb, 2400, 02, 15, 25 },
3816 { 01, wxDateTime::Jan, -52, 03, 16, 47 },
3817 #endif
3818 };
3819
3820 // an extra test (as it doesn't depend on date, don't do it in the loop)
3821 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3822
3823 for ( size_t d = 0; d < WXSIZEOF(formatTestDates) + 1; d++ )
3824 {
3825 puts("");
3826
3827 wxDateTime dt = d == 0 ? wxDateTime::Now() : formatTestDates[d - 1].DT();
3828 for ( size_t n = 0; n < WXSIZEOF(formatTestFormats); n++ )
3829 {
3830 wxString s = dt.Format(formatTestFormats[n].format);
3831 printf("%s", s.c_str());
3832
3833 // what can we recover?
3834 int kind = formatTestFormats[n].compareKind;
3835
3836 // convert back
3837 wxDateTime dt2;
3838 const wxChar *result = dt2.ParseFormat(s, formatTestFormats[n].format);
3839 if ( !result )
3840 {
3841 // converion failed - should it have?
3842 if ( kind == CompareNone )
3843 puts(" (ok)");
3844 else
3845 puts(" (ERROR: conversion back failed)");
3846 }
3847 else if ( *result )
3848 {
3849 // should have parsed the entire string
3850 puts(" (ERROR: conversion back stopped too soon)");
3851 }
3852 else
3853 {
3854 bool equal = FALSE; // suppress compilaer warning
3855 switch ( kind )
3856 {
3857 case CompareBoth:
3858 equal = dt2 == dt;
3859 break;
3860
3861 case CompareDate:
3862 equal = dt.IsSameDate(dt2);
3863 break;
3864
3865 case CompareTime:
3866 equal = dt.IsSameTime(dt2);
3867 break;
3868 }
3869
3870 if ( !equal )
3871 {
3872 printf(" (ERROR: got back '%s' instead of '%s')\n",
3873 dt2.Format().c_str(), dt.Format().c_str());
3874 }
3875 else
3876 {
3877 puts(" (ok)");
3878 }
3879 }
3880 }
3881 }
3882 }
3883
3884 // test text -> wxDateTime conversion
3885 static void TestTimeParse()
3886 {
3887 puts("\n*** wxDateTime parse test ***");
3888
3889 struct ParseTestData
3890 {
3891 const char *format;
3892 Date date;
3893 bool good;
3894 };
3895
3896 static const ParseTestData parseTestDates[] =
3897 {
3898 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec, 1999, 00, 46, 40 }, TRUE },
3899 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec, 1999, 03, 17, 20 }, TRUE },
3900 };
3901
3902 for ( size_t n = 0; n < WXSIZEOF(parseTestDates); n++ )
3903 {
3904 const char *format = parseTestDates[n].format;
3905
3906 printf("%s => ", format);
3907
3908 wxDateTime dt;
3909 if ( dt.ParseRfc822Date(format) )
3910 {
3911 printf("%s ", dt.Format().c_str());
3912
3913 if ( parseTestDates[n].good )
3914 {
3915 wxDateTime dtReal = parseTestDates[n].date.DT();
3916 if ( dt == dtReal )
3917 {
3918 puts("(ok)");
3919 }
3920 else
3921 {
3922 printf("(ERROR: should be %s)\n", dtReal.Format().c_str());
3923 }
3924 }
3925 else
3926 {
3927 puts("(ERROR: bad format)");
3928 }
3929 }
3930 else
3931 {
3932 printf("bad format (%s)\n",
3933 parseTestDates[n].good ? "ERROR" : "ok");
3934 }
3935 }
3936 }
3937
3938 static void TestDateTimeInteractive()
3939 {
3940 puts("\n*** interactive wxDateTime tests ***");
3941
3942 char buf[128];
3943
3944 for ( ;; )
3945 {
3946 printf("Enter a date: ");
3947 if ( !fgets(buf, WXSIZEOF(buf), stdin) )
3948 break;
3949
3950 // kill the last '\n'
3951 buf[strlen(buf) - 1] = 0;
3952
3953 wxDateTime dt;
3954 const char *p = dt.ParseDate(buf);
3955 if ( !p )
3956 {
3957 printf("ERROR: failed to parse the date '%s'.\n", buf);
3958
3959 continue;
3960 }
3961 else if ( *p )
3962 {
3963 printf("WARNING: parsed only first %u characters.\n", p - buf);
3964 }
3965
3966 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3967 dt.Format("%b %d, %Y").c_str(),
3968 dt.GetDayOfYear(),
3969 dt.GetWeekOfMonth(wxDateTime::Monday_First),
3970 dt.GetWeekOfMonth(wxDateTime::Sunday_First),
3971 dt.GetWeekOfYear(wxDateTime::Monday_First));
3972 }
3973
3974 puts("\n*** done ***");
3975 }
3976
3977 static void TestTimeMS()
3978 {
3979 puts("*** testing millisecond-resolution support in wxDateTime ***");
3980
3981 wxDateTime dt1 = wxDateTime::Now(),
3982 dt2 = wxDateTime::UNow();
3983
3984 printf("Now = %s\n", dt1.Format("%H:%M:%S:%l").c_str());
3985 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
3986 printf("Dummy loop: ");
3987 for ( int i = 0; i < 6000; i++ )
3988 {
3989 //for ( int j = 0; j < 10; j++ )
3990 {
3991 wxString s;
3992 s.Printf("%g", sqrt(i));
3993 }
3994
3995 if ( !(i % 100) )
3996 putchar('.');
3997 }
3998 puts(", done");
3999
4000 dt1 = dt2;
4001 dt2 = wxDateTime::UNow();
4002 printf("UNow = %s\n", dt2.Format("%H:%M:%S:%l").c_str());
4003
4004 printf("Loop executed in %s ms\n", (dt2 - dt1).Format("%l").c_str());
4005
4006 puts("\n*** done ***");
4007 }
4008
4009 static void TestTimeArithmetics()
4010 {
4011 puts("\n*** testing arithmetic operations on wxDateTime ***");
4012
4013 static const struct ArithmData
4014 {
4015 ArithmData(const wxDateSpan& sp, const char *nam)
4016 : span(sp), name(nam) { }
4017
4018 wxDateSpan span;
4019 const char *name;
4020 } testArithmData[] =
4021 {
4022 ArithmData(wxDateSpan::Day(), "day"),
4023 ArithmData(wxDateSpan::Week(), "week"),
4024 ArithmData(wxDateSpan::Month(), "month"),
4025 ArithmData(wxDateSpan::Year(), "year"),
4026 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4027 };
4028
4029 wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
4030
4031 for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
4032 {
4033 wxDateSpan span = testArithmData[n].span;
4034 dt1 = dt + span;
4035 dt2 = dt - span;
4036
4037 const char *name = testArithmData[n].name;
4038 printf("%s + %s = %s, %s - %s = %s\n",
4039 dt.FormatISODate().c_str(), name, dt1.FormatISODate().c_str(),
4040 dt.FormatISODate().c_str(), name, dt2.FormatISODate().c_str());
4041
4042 printf("Going back: %s", (dt1 - span).FormatISODate().c_str());
4043 if ( dt1 - span == dt )
4044 {
4045 puts(" (ok)");
4046 }
4047 else
4048 {
4049 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
4050 }
4051
4052 printf("Going forward: %s", (dt2 + span).FormatISODate().c_str());
4053 if ( dt2 + span == dt )
4054 {
4055 puts(" (ok)");
4056 }
4057 else
4058 {
4059 printf(" (ERROR: should be %s)\n", dt.FormatISODate().c_str());
4060 }
4061
4062 printf("Double increment: %s", (dt2 + 2*span).FormatISODate().c_str());
4063 if ( dt2 + 2*span == dt1 )
4064 {
4065 puts(" (ok)");
4066 }
4067 else
4068 {
4069 printf(" (ERROR: should be %s)\n", dt2.FormatISODate().c_str());
4070 }
4071
4072 puts("");
4073 }
4074 }
4075
4076 static void TestTimeHolidays()
4077 {
4078 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4079
4080 wxDateTime::Tm tm = wxDateTime(29, wxDateTime::May, 2000).GetTm();
4081 wxDateTime dtStart(1, tm.mon, tm.year),
4082 dtEnd = dtStart.GetLastMonthDay();
4083
4084 wxDateTimeArray hol;
4085 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart, dtEnd, hol);
4086
4087 const wxChar *format = "%d-%b-%Y (%a)";
4088
4089 printf("All holidays between %s and %s:\n",
4090 dtStart.Format(format).c_str(), dtEnd.Format(format).c_str());
4091
4092 size_t count = hol.GetCount();
4093 for ( size_t n = 0; n < count; n++ )
4094 {
4095 printf("\t%s\n", hol[n].Format(format).c_str());
4096 }
4097
4098 puts("");
4099 }
4100
4101 static void TestTimeZoneBug()
4102 {
4103 puts("\n*** testing for DST/timezone bug ***\n");
4104
4105 wxDateTime date = wxDateTime(1, wxDateTime::Mar, 2000);
4106 for ( int i = 0; i < 31; i++ )
4107 {
4108 printf("Date %s: week day %s.\n",
4109 date.Format(_T("%d-%m-%Y")).c_str(),
4110 date.GetWeekDayName(date.GetWeekDay()).c_str());
4111
4112 date += wxDateSpan::Day();
4113 }
4114
4115 puts("");
4116 }
4117
4118 static void TestTimeSpanFormat()
4119 {
4120 puts("\n*** wxTimeSpan tests ***");
4121
4122 static const char *formats[] =
4123 {
4124 _T("(default) %H:%M:%S"),
4125 _T("%E weeks and %D days"),
4126 _T("%l milliseconds"),
4127 _T("(with ms) %H:%M:%S:%l"),
4128 _T("100%% of minutes is %M"), // test "%%"
4129 _T("%D days and %H hours"),
4130 _T("or also %S seconds"),
4131 };
4132
4133 wxTimeSpan ts1(1, 2, 3, 4),
4134 ts2(111, 222, 333);
4135 for ( size_t n = 0; n < WXSIZEOF(formats); n++ )
4136 {
4137 printf("ts1 = %s\tts2 = %s\n",
4138 ts1.Format(formats[n]).c_str(),
4139 ts2.Format(formats[n]).c_str());
4140 }
4141
4142 puts("");
4143 }
4144
4145 #if 0
4146
4147 // test compatibility with the old wxDate/wxTime classes
4148 static void TestTimeCompatibility()
4149 {
4150 puts("\n*** wxDateTime compatibility test ***");
4151
4152 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4153 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4154
4155 double jdnNow = wxDateTime::Now().GetJDN();
4156 long jdnMidnight = (long)(jdnNow - 0.5);
4157 printf("wxDate for today: %s\n", wxDate(jdnMidnight).FormatDate().c_str());
4158
4159 jdnMidnight = wxDate().Set().GetJulianDate();
4160 printf("wxDateTime for today: %s\n",
4161 wxDateTime((double)(jdnMidnight + 0.5)).Format("%c", wxDateTime::GMT0).c_str());
4162
4163 int flags = wxEUROPEAN;//wxFULL;
4164 wxDate date;
4165 date.Set();
4166 printf("Today is %s\n", date.FormatDate(flags).c_str());
4167 for ( int n = 0; n < 7; n++ )
4168 {
4169 printf("Previous %s is %s\n",
4170 wxDateTime::GetWeekDayName((wxDateTime::WeekDay)n),
4171 date.Previous(n + 1).FormatDate(flags).c_str());
4172 }
4173 }
4174
4175 #endif // 0
4176
4177 #endif // TEST_DATETIME
4178
4179 // ----------------------------------------------------------------------------
4180 // threads
4181 // ----------------------------------------------------------------------------
4182
4183 #ifdef TEST_THREADS
4184
4185 #include "wx/thread.h"
4186
4187 static size_t gs_counter = (size_t)-1;
4188 static wxCriticalSection gs_critsect;
4189 static wxCondition gs_cond;
4190
4191 class MyJoinableThread : public wxThread
4192 {
4193 public:
4194 MyJoinableThread(size_t n) : wxThread(wxTHREAD_JOINABLE)
4195 { m_n = n; Create(); }
4196
4197 // thread execution starts here
4198 virtual ExitCode Entry();
4199
4200 private:
4201 size_t m_n;
4202 };
4203
4204 wxThread::ExitCode MyJoinableThread::Entry()
4205 {
4206 unsigned long res = 1;
4207 for ( size_t n = 1; n < m_n; n++ )
4208 {
4209 res *= n;
4210
4211 // it's a loooong calculation :-)
4212 Sleep(100);
4213 }
4214
4215 return (ExitCode)res;
4216 }
4217
4218 class MyDetachedThread : public wxThread
4219 {
4220 public:
4221 MyDetachedThread(size_t n, char ch)
4222 {
4223 m_n = n;
4224 m_ch = ch;
4225 m_cancelled = FALSE;
4226
4227 Create();
4228 }
4229
4230 // thread execution starts here
4231 virtual ExitCode Entry();
4232
4233 // and stops here
4234 virtual void OnExit();
4235
4236 private:
4237 size_t m_n; // number of characters to write
4238 char m_ch; // character to write
4239
4240 bool m_cancelled; // FALSE if we exit normally
4241 };
4242
4243 wxThread::ExitCode MyDetachedThread::Entry()
4244 {
4245 {
4246 wxCriticalSectionLocker lock(gs_critsect);
4247 if ( gs_counter == (size_t)-1 )
4248 gs_counter = 1;
4249 else
4250 gs_counter++;
4251 }
4252
4253 for ( size_t n = 0; n < m_n; n++ )
4254 {
4255 if ( TestDestroy() )
4256 {
4257 m_cancelled = TRUE;
4258
4259 break;
4260 }
4261
4262 putchar(m_ch);
4263 fflush(stdout);
4264
4265 wxThread::Sleep(100);
4266 }
4267
4268 return 0;
4269 }
4270
4271 void MyDetachedThread::OnExit()
4272 {
4273 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4274
4275 wxCriticalSectionLocker lock(gs_critsect);
4276 if ( !--gs_counter && !m_cancelled )
4277 gs_cond.Signal();
4278 }
4279
4280 void TestDetachedThreads()
4281 {
4282 puts("\n*** Testing detached threads ***");
4283
4284 static const size_t nThreads = 3;
4285 MyDetachedThread *threads[nThreads];
4286 size_t n;
4287 for ( n = 0; n < nThreads; n++ )
4288 {
4289 threads[n] = new MyDetachedThread(10, 'A' + n);
4290 }
4291
4292 threads[0]->SetPriority(WXTHREAD_MIN_PRIORITY);
4293 threads[1]->SetPriority(WXTHREAD_MAX_PRIORITY);
4294
4295 for ( n = 0; n < nThreads; n++ )
4296 {
4297 threads[n]->Run();
4298 }
4299
4300 // wait until all threads terminate
4301 gs_cond.Wait();
4302
4303 puts("");
4304 }
4305
4306 void TestJoinableThreads()
4307 {
4308 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4309
4310 // calc 10! in the background
4311 MyJoinableThread thread(10);
4312 thread.Run();
4313
4314 printf("\nThread terminated with exit code %lu.\n",
4315 (unsigned long)thread.Wait());
4316 }
4317
4318 void TestThreadSuspend()
4319 {
4320 puts("\n*** Testing thread suspend/resume functions ***");
4321
4322 MyDetachedThread *thread = new MyDetachedThread(15, 'X');
4323
4324 thread->Run();
4325
4326 // this is for this demo only, in a real life program we'd use another
4327 // condition variable which would be signaled from wxThread::Entry() to
4328 // tell us that the thread really started running - but here just wait a
4329 // bit and hope that it will be enough (the problem is, of course, that
4330 // the thread might still not run when we call Pause() which will result
4331 // in an error)
4332 wxThread::Sleep(300);
4333
4334 for ( size_t n = 0; n < 3; n++ )
4335 {
4336 thread->Pause();
4337
4338 puts("\nThread suspended");
4339 if ( n > 0 )
4340 {
4341 // don't sleep but resume immediately the first time
4342 wxThread::Sleep(300);
4343 }
4344 puts("Going to resume the thread");
4345
4346 thread->Resume();
4347 }
4348
4349 puts("Waiting until it terminates now");
4350
4351 // wait until the thread terminates
4352 gs_cond.Wait();
4353
4354 puts("");
4355 }
4356
4357 void TestThreadDelete()
4358 {
4359 // As above, using Sleep() is only for testing here - we must use some
4360 // synchronisation object instead to ensure that the thread is still
4361 // running when we delete it - deleting a detached thread which already
4362 // terminated will lead to a crash!
4363
4364 puts("\n*** Testing thread delete function ***");
4365
4366 MyDetachedThread *thread0 = new MyDetachedThread(30, 'W');
4367
4368 thread0->Delete();
4369
4370 puts("\nDeleted a thread which didn't start to run yet.");
4371
4372 MyDetachedThread *thread1 = new MyDetachedThread(30, 'Y');
4373
4374 thread1->Run();
4375
4376 wxThread::Sleep(300);
4377
4378 thread1->Delete();
4379
4380 puts("\nDeleted a running thread.");
4381
4382 MyDetachedThread *thread2 = new MyDetachedThread(30, 'Z');
4383
4384 thread2->Run();
4385
4386 wxThread::Sleep(300);
4387
4388 thread2->Pause();
4389
4390 thread2->Delete();
4391
4392 puts("\nDeleted a sleeping thread.");
4393
4394 MyJoinableThread thread3(20);
4395 thread3.Run();
4396
4397 thread3.Delete();
4398
4399 puts("\nDeleted a joinable thread.");
4400
4401 MyJoinableThread thread4(2);
4402 thread4.Run();
4403
4404 wxThread::Sleep(300);
4405
4406 thread4.Delete();
4407
4408 puts("\nDeleted a joinable thread which already terminated.");
4409
4410 puts("");
4411 }
4412
4413 #endif // TEST_THREADS
4414
4415 // ----------------------------------------------------------------------------
4416 // arrays
4417 // ----------------------------------------------------------------------------
4418
4419 #ifdef TEST_ARRAYS
4420
4421 static void PrintArray(const char* name, const wxArrayString& array)
4422 {
4423 printf("Dump of the array '%s'\n", name);
4424
4425 size_t nCount = array.GetCount();
4426 for ( size_t n = 0; n < nCount; n++ )
4427 {
4428 printf("\t%s[%u] = '%s'\n", name, n, array[n].c_str());
4429 }
4430 }
4431
4432 static void PrintArray(const char* name, const wxArrayInt& array)
4433 {
4434 printf("Dump of the array '%s'\n", name);
4435
4436 size_t nCount = array.GetCount();
4437 for ( size_t n = 0; n < nCount; n++ )
4438 {
4439 printf("\t%s[%u] = %d\n", name, n, array[n]);
4440 }
4441 }
4442
4443 int wxCMPFUNC_CONV StringLenCompare(const wxString& first,
4444 const wxString& second)
4445 {
4446 return first.length() - second.length();
4447 }
4448
4449 int wxCMPFUNC_CONV IntCompare(int *first,
4450 int *second)
4451 {
4452 return *first - *second;
4453 }
4454
4455 int wxCMPFUNC_CONV IntRevCompare(int *first,
4456 int *second)
4457 {
4458 return *second - *first;
4459 }
4460
4461 static void TestArrayOfInts()
4462 {
4463 puts("*** Testing wxArrayInt ***\n");
4464
4465 wxArrayInt a;
4466 a.Add(1);
4467 a.Add(17);
4468 a.Add(5);
4469 a.Add(3);
4470
4471 puts("Initially:");
4472 PrintArray("a", a);
4473
4474 puts("After sort:");
4475 a.Sort(IntCompare);
4476 PrintArray("a", a);
4477
4478 puts("After reverse sort:");
4479 a.Sort(IntRevCompare);
4480 PrintArray("a", a);
4481 }
4482
4483 #include "wx/dynarray.h"
4484
4485 WX_DECLARE_OBJARRAY(Bar, ArrayBars);
4486 #include "wx/arrimpl.cpp"
4487 WX_DEFINE_OBJARRAY(ArrayBars);
4488
4489 static void TestArrayOfObjects()
4490 {
4491 puts("*** Testing wxObjArray ***\n");
4492
4493 {
4494 ArrayBars bars;
4495 Bar bar("second bar");
4496
4497 printf("Initially: %u objects in the array, %u objects total.\n",
4498 bars.GetCount(), Bar::GetNumber());
4499
4500 bars.Add(new Bar("first bar"));
4501 bars.Add(bar);
4502
4503 printf("Now: %u objects in the array, %u objects total.\n",
4504 bars.GetCount(), Bar::GetNumber());
4505
4506 bars.Empty();
4507
4508 printf("After Empty(): %u objects in the array, %u objects total.\n",
4509 bars.GetCount(), Bar::GetNumber());
4510 }
4511
4512 printf("Finally: no more objects in the array, %u objects total.\n",
4513 Bar::GetNumber());
4514 }
4515
4516 #endif // TEST_ARRAYS
4517
4518 // ----------------------------------------------------------------------------
4519 // strings
4520 // ----------------------------------------------------------------------------
4521
4522 #ifdef TEST_STRINGS
4523
4524 #include "wx/timer.h"
4525 #include "wx/tokenzr.h"
4526
4527 static void TestStringConstruction()
4528 {
4529 puts("*** Testing wxString constructores ***");
4530
4531 #define TEST_CTOR(args, res) \
4532 { \
4533 wxString s args ; \
4534 printf("wxString%s = %s ", #args, s.c_str()); \
4535 if ( s == res ) \
4536 { \
4537 puts("(ok)"); \
4538 } \
4539 else \
4540 { \
4541 printf("(ERROR: should be %s)\n", res); \
4542 } \
4543 }
4544
4545 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4546 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4547 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4548 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4549
4550 static const wxChar *s = _T("?really!");
4551 const wxChar *start = wxStrchr(s, _T('r'));
4552 const wxChar *end = wxStrchr(s, _T('!'));
4553 TEST_CTOR((start, end), _T("really"));
4554
4555 puts("");
4556 }
4557
4558 static void TestString()
4559 {
4560 wxStopWatch sw;
4561
4562 wxString a, b, c;
4563
4564 a.reserve (128);
4565 b.reserve (128);
4566 c.reserve (128);
4567
4568 for (int i = 0; i < 1000000; ++i)
4569 {
4570 a = "Hello";
4571 b = " world";
4572 c = "! How'ya doin'?";
4573 a += b;
4574 a += c;
4575 c = "Hello world! What's up?";
4576 if (c != a)
4577 c = "Doh!";
4578 }
4579
4580 printf ("TestString elapsed time: %ld\n", sw.Time());
4581 }
4582
4583 static void TestPChar()
4584 {
4585 wxStopWatch sw;
4586
4587 char a [128];
4588 char b [128];
4589 char c [128];
4590
4591 for (int i = 0; i < 1000000; ++i)
4592 {
4593 strcpy (a, "Hello");
4594 strcpy (b, " world");
4595 strcpy (c, "! How'ya doin'?");
4596 strcat (a, b);
4597 strcat (a, c);
4598 strcpy (c, "Hello world! What's up?");
4599 if (strcmp (c, a) == 0)
4600 strcpy (c, "Doh!");
4601 }
4602
4603 printf ("TestPChar elapsed time: %ld\n", sw.Time());
4604 }
4605
4606 static void TestStringSub()
4607 {
4608 wxString s("Hello, world!");
4609
4610 puts("*** Testing wxString substring extraction ***");
4611
4612 printf("String = '%s'\n", s.c_str());
4613 printf("Left(5) = '%s'\n", s.Left(5).c_str());
4614 printf("Right(6) = '%s'\n", s.Right(6).c_str());
4615 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4616 printf("Mid(3) = '%s'\n", s.Mid(3).c_str());
4617 printf("substr(3, 5) = '%s'\n", s.substr(3, 5).c_str());
4618 printf("substr(3) = '%s'\n", s.substr(3).c_str());
4619
4620 static const wxChar *prefixes[] =
4621 {
4622 _T("Hello"),
4623 _T("Hello, "),
4624 _T("Hello, world!"),
4625 _T("Hello, world!!!"),
4626 _T(""),
4627 _T("Goodbye"),
4628 _T("Hi"),
4629 };
4630
4631 for ( size_t n = 0; n < WXSIZEOF(prefixes); n++ )
4632 {
4633 wxString prefix = prefixes[n], rest;
4634 bool rc = s.StartsWith(prefix, &rest);
4635 printf("StartsWith('%s') = %s", prefix.c_str(), rc ? "TRUE" : "FALSE");
4636 if ( rc )
4637 {
4638 printf(" (the rest is '%s')\n", rest.c_str());
4639 }
4640 else
4641 {
4642 putchar('\n');
4643 }
4644 }
4645
4646 puts("");
4647 }
4648
4649 static void TestStringFormat()
4650 {
4651 puts("*** Testing wxString formatting ***");
4652
4653 wxString s;
4654 s.Printf("%03d", 18);
4655
4656 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4657 printf("Number 18: %s\n", s.c_str());
4658
4659 puts("");
4660 }
4661
4662 // returns "not found" for npos, value for all others
4663 static wxString PosToString(size_t res)
4664 {
4665 wxString s = res == wxString::npos ? wxString(_T("not found"))
4666 : wxString::Format(_T("%u"), res);
4667 return s;
4668 }
4669
4670 static void TestStringFind()
4671 {
4672 puts("*** Testing wxString find() functions ***");
4673
4674 static const wxChar *strToFind = _T("ell");
4675 static const struct StringFindTest
4676 {
4677 const wxChar *str;
4678 size_t start,
4679 result; // of searching "ell" in str
4680 } findTestData[] =
4681 {
4682 { _T("Well, hello world"), 0, 1 },
4683 { _T("Well, hello world"), 6, 7 },
4684 { _T("Well, hello world"), 9, wxString::npos },
4685 };
4686
4687 for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
4688 {
4689 const StringFindTest& ft = findTestData[n];
4690 size_t res = wxString(ft.str).find(strToFind, ft.start);
4691
4692 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4693 strToFind, ft.str, ft.start, PosToString(res).c_str());
4694
4695 size_t resTrue = ft.result;
4696 if ( res == resTrue )
4697 {
4698 puts(_T("(ok)"));
4699 }
4700 else
4701 {
4702 printf(_T("(ERROR: should be %s)\n"),
4703 PosToString(resTrue).c_str());
4704 }
4705 }
4706
4707 puts("");
4708 }
4709
4710 static void TestStringTokenizer()
4711 {
4712 puts("*** Testing wxStringTokenizer ***");
4713
4714 static const wxChar *modeNames[] =
4715 {
4716 _T("default"),
4717 _T("return empty"),
4718 _T("return all empty"),
4719 _T("with delims"),
4720 _T("like strtok"),
4721 };
4722
4723 static const struct StringTokenizerTest
4724 {
4725 const wxChar *str; // string to tokenize
4726 const wxChar *delims; // delimiters to use
4727 size_t count; // count of token
4728 wxStringTokenizerMode mode; // how should we tokenize it
4729 } tokenizerTestData[] =
4730 {
4731 { _T(""), _T(" "), 0 },
4732 { _T("Hello, world"), _T(" "), 2 },
4733 { _T("Hello, world "), _T(" "), 2 },
4734 { _T("Hello, world"), _T(","), 2 },
4735 { _T("Hello, world!"), _T(",!"), 2 },
4736 { _T("Hello,, world!"), _T(",!"), 3 },
4737 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
4738 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4739 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 4 },
4740 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
4741 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
4742 { _T("01/02/99"), _T("/-"), 3 },
4743 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
4744 };
4745
4746 for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
4747 {
4748 const StringTokenizerTest& tt = tokenizerTestData[n];
4749 wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
4750
4751 size_t count = tkz.CountTokens();
4752 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4753 MakePrintable(tt.str).c_str(),
4754 count,
4755 MakePrintable(tt.delims).c_str(),
4756 modeNames[tkz.GetMode()]);
4757 if ( count == tt.count )
4758 {
4759 puts(_T("(ok)"));
4760 }
4761 else
4762 {
4763 printf(_T("(ERROR: should be %u)\n"), tt.count);
4764
4765 continue;
4766 }
4767
4768 // if we emulate strtok(), check that we do it correctly
4769 wxChar *buf, *s = NULL, *last;
4770
4771 if ( tkz.GetMode() == wxTOKEN_STRTOK )
4772 {
4773 buf = new wxChar[wxStrlen(tt.str) + 1];
4774 wxStrcpy(buf, tt.str);
4775
4776 s = wxStrtok(buf, tt.delims, &last);
4777 }
4778 else
4779 {
4780 buf = NULL;
4781 }
4782
4783 // now show the tokens themselves
4784 size_t count2 = 0;
4785 while ( tkz.HasMoreTokens() )
4786 {
4787 wxString token = tkz.GetNextToken();
4788
4789 printf(_T("\ttoken %u: '%s'"),
4790 ++count2,
4791 MakePrintable(token).c_str());
4792
4793 if ( buf )
4794 {
4795 if ( token == s )
4796 {
4797 puts(" (ok)");
4798 }
4799 else
4800 {
4801 printf(" (ERROR: should be %s)\n", s);
4802 }
4803
4804 s = wxStrtok(NULL, tt.delims, &last);
4805 }
4806 else
4807 {
4808 // nothing to compare with
4809 puts("");
4810 }
4811 }
4812
4813 if ( count2 != count )
4814 {
4815 puts(_T("\tERROR: token count mismatch"));
4816 }
4817
4818 delete [] buf;
4819 }
4820
4821 puts("");
4822 }
4823
4824 static void TestStringReplace()
4825 {
4826 puts("*** Testing wxString::replace ***");
4827
4828 static const struct StringReplaceTestData
4829 {
4830 const wxChar *original; // original test string
4831 size_t start, len; // the part to replace
4832 const wxChar *replacement; // the replacement string
4833 const wxChar *result; // and the expected result
4834 } stringReplaceTestData[] =
4835 {
4836 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4837 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4838 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4839 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4840 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4841 };
4842
4843 for ( size_t n = 0; n < WXSIZEOF(stringReplaceTestData); n++ )
4844 {
4845 const StringReplaceTestData data = stringReplaceTestData[n];
4846
4847 wxString original = data.original;
4848 original.replace(data.start, data.len, data.replacement);
4849
4850 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4851 data.original, data.start, data.len, data.replacement,
4852 original.c_str());
4853
4854 if ( original == data.result )
4855 {
4856 puts("(ok)");
4857 }
4858 else
4859 {
4860 wxPrintf(_T("(ERROR: should be '%s')\n"), data.result);
4861 }
4862 }
4863
4864 puts("");
4865 }
4866
4867 static void TestStringMatch()
4868 {
4869 wxPuts(_T("*** Testing wxString::Matches() ***"));
4870
4871 static const struct StringMatchTestData
4872 {
4873 const wxChar *text;
4874 const wxChar *wildcard;
4875 bool matches;
4876 } stringMatchTestData[] =
4877 {
4878 { _T("foobar"), _T("foo*"), 1 },
4879 { _T("foobar"), _T("*oo*"), 1 },
4880 { _T("foobar"), _T("*bar"), 1 },
4881 { _T("foobar"), _T("??????"), 1 },
4882 { _T("foobar"), _T("f??b*"), 1 },
4883 { _T("foobar"), _T("f?b*"), 0 },
4884 { _T("foobar"), _T("*goo*"), 0 },
4885 { _T("foobar"), _T("*foo"), 0 },
4886 { _T("foobarfoo"), _T("*foo"), 1 },
4887 { _T(""), _T("*"), 1 },
4888 { _T(""), _T("?"), 0 },
4889 };
4890
4891 for ( size_t n = 0; n < WXSIZEOF(stringMatchTestData); n++ )
4892 {
4893 const StringMatchTestData& data = stringMatchTestData[n];
4894 bool matches = wxString(data.text).Matches(data.wildcard);
4895 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4896 data.wildcard,
4897 matches ? _T("matches") : _T("doesn't match"),
4898 data.text,
4899 matches == data.matches ? _T("ok") : _T("ERROR"));
4900 }
4901
4902 wxPuts(_T(""));
4903 }
4904
4905 #endif // TEST_STRINGS
4906
4907 // ----------------------------------------------------------------------------
4908 // entry point
4909 // ----------------------------------------------------------------------------
4910
4911 int main(int argc, char **argv)
4912 {
4913 wxInitializer initializer;
4914 if ( !initializer )
4915 {
4916 fprintf(stderr, "Failed to initialize the wxWindows library, aborting.");
4917
4918 return -1;
4919 }
4920
4921 #ifdef TEST_SNGLINST
4922 wxSingleInstanceChecker checker;
4923 if ( checker.Create(_T(".wxconsole.lock")) )
4924 {
4925 if ( checker.IsAnotherRunning() )
4926 {
4927 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4928
4929 return 1;
4930 }
4931
4932 // wait some time to give time to launch another instance
4933 wxPrintf(_T("Press \"Enter\" to continue..."));
4934 wxFgetc(stdin);
4935 }
4936 else // failed to create
4937 {
4938 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4939 }
4940 #endif // TEST_SNGLINST
4941
4942 #ifdef TEST_CHARSET
4943 TestCharset();
4944 #endif // TEST_CHARSET
4945
4946 #ifdef TEST_CMDLINE
4947 static const wxCmdLineEntryDesc cmdLineDesc[] =
4948 {
4949 { wxCMD_LINE_SWITCH, _T("h"), _T("help"), "show this help message",
4950 wxCMD_LINE_VAL_NONE, wxCMD_LINE_OPTION_HELP },
4951 { wxCMD_LINE_SWITCH, "v", "verbose", "be verbose" },
4952 { wxCMD_LINE_SWITCH, "q", "quiet", "be quiet" },
4953
4954 { wxCMD_LINE_OPTION, "o", "output", "output file" },
4955 { wxCMD_LINE_OPTION, "i", "input", "input dir" },
4956 { wxCMD_LINE_OPTION, "s", "size", "output block size",
4957 wxCMD_LINE_VAL_NUMBER },
4958 { wxCMD_LINE_OPTION, "d", "date", "output file date",
4959 wxCMD_LINE_VAL_DATE },
4960
4961 { wxCMD_LINE_PARAM, NULL, NULL, "input file",
4962 wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_MULTIPLE },
4963
4964 { wxCMD_LINE_NONE }
4965 };
4966
4967 wxCmdLineParser parser(cmdLineDesc, argc, argv);
4968
4969 parser.AddOption("project_name", "", "full path to project file",
4970 wxCMD_LINE_VAL_STRING,
4971 wxCMD_LINE_OPTION_MANDATORY | wxCMD_LINE_NEEDS_SEPARATOR);
4972
4973 switch ( parser.Parse() )
4974 {
4975 case -1:
4976 wxLogMessage("Help was given, terminating.");
4977 break;
4978
4979 case 0:
4980 ShowCmdLine(parser);
4981 break;
4982
4983 default:
4984 wxLogMessage("Syntax error detected, aborting.");
4985 break;
4986 }
4987 #endif // TEST_CMDLINE
4988
4989 #ifdef TEST_STRINGS
4990 if ( 0 )
4991 {
4992 TestPChar();
4993 TestString();
4994 TestStringSub();
4995 TestStringConstruction();
4996 TestStringFormat();
4997 TestStringFind();
4998 TestStringTokenizer();
4999 TestStringReplace();
5000 }
5001 TestStringMatch();
5002 #endif // TEST_STRINGS
5003
5004 #ifdef TEST_ARRAYS
5005 if ( 0 )
5006 {
5007 wxArrayString a1;
5008 a1.Add("tiger");
5009 a1.Add("cat");
5010 a1.Add("lion");
5011 a1.Add("dog");
5012 a1.Add("human");
5013 a1.Add("ape");
5014
5015 puts("*** Initially:");
5016
5017 PrintArray("a1", a1);
5018
5019 wxArrayString a2(a1);
5020 PrintArray("a2", a2);
5021
5022 wxSortedArrayString a3(a1);
5023 PrintArray("a3", a3);
5024
5025 puts("*** After deleting a string from a1");
5026 a1.Remove(2);
5027
5028 PrintArray("a1", a1);
5029 PrintArray("a2", a2);
5030 PrintArray("a3", a3);
5031
5032 puts("*** After reassigning a1 to a2 and a3");
5033 a3 = a2 = a1;
5034 PrintArray("a2", a2);
5035 PrintArray("a3", a3);
5036
5037 puts("*** After sorting a1");
5038 a1.Sort();
5039 PrintArray("a1", a1);
5040
5041 puts("*** After sorting a1 in reverse order");
5042 a1.Sort(TRUE);
5043 PrintArray("a1", a1);
5044
5045 puts("*** After sorting a1 by the string length");
5046 a1.Sort(StringLenCompare);
5047 PrintArray("a1", a1);
5048
5049 TestArrayOfObjects();
5050 }
5051 TestArrayOfInts();
5052 #endif // TEST_ARRAYS
5053
5054 #ifdef TEST_DIR
5055 if ( 0 )
5056 TestDirEnum();
5057 TestDirTraverse();
5058 #endif // TEST_DIR
5059
5060 #ifdef TEST_DLLLOADER
5061 TestDllLoad();
5062 #endif // TEST_DLLLOADER
5063
5064 #ifdef TEST_ENVIRON
5065 TestEnvironment();
5066 #endif // TEST_ENVIRON
5067
5068 #ifdef TEST_EXECUTE
5069 TestExecute();
5070 #endif // TEST_EXECUTE
5071
5072 #ifdef TEST_FILECONF
5073 TestFileConfRead();
5074 #endif // TEST_FILECONF
5075
5076 #ifdef TEST_LIST
5077 TestListCtor();
5078 #endif // TEST_LIST
5079
5080 #ifdef TEST_LOCALE
5081 TestDefaultLang();
5082 #endif // TEST_LOCALE
5083
5084 #ifdef TEST_LOG
5085 wxString s;
5086 for ( size_t n = 0; n < 8000; n++ )
5087 {
5088 s << (char)('A' + (n % 26));
5089 }
5090
5091 wxString msg;
5092 msg.Printf("A very very long message: '%s', the end!\n", s.c_str());
5093
5094 // this one shouldn't be truncated
5095 printf(msg);
5096
5097 // but this one will because log functions use fixed size buffer
5098 // (note that it doesn't need '\n' at the end neither - will be added
5099 // by wxLog anyhow)
5100 wxLogMessage("A very very long message 2: '%s', the end!", s.c_str());
5101 #endif // TEST_LOG
5102
5103 #ifdef TEST_FILE
5104 if ( 0 )
5105 {
5106 TestFileRead();
5107 TestTextFileRead();
5108 }
5109 TestFileCopy();
5110 #endif // TEST_FILE
5111
5112 #ifdef TEST_FILENAME
5113 TestFileNameSplit();
5114 if ( 0 )
5115 {
5116 TestFileNameConstruction();
5117 TestFileNameCwd();
5118 TestFileNameComparison();
5119 TestFileNameOperations();
5120 }
5121 #endif // TEST_FILENAME
5122
5123 #ifdef TEST_FILETIME
5124 TestFileGetTimes();
5125 TestFileSetTimes();
5126 #endif // TEST_FILETIME
5127
5128 #ifdef TEST_FTP
5129 wxLog::AddTraceMask(FTP_TRACE_MASK);
5130 if ( TestFtpConnect() )
5131 {
5132 TestFtpFileSize();
5133 if ( 0 )
5134 {
5135 TestFtpList();
5136 TestFtpDownload();
5137 TestFtpMisc();
5138 TestFtpUpload();
5139 }
5140 if ( 0 )
5141 TestFtpInteractive();
5142 }
5143 //else: connecting to the FTP server failed
5144
5145 if ( 0 )
5146 TestFtpWuFtpd();
5147 #endif // TEST_FTP
5148
5149 #ifdef TEST_THREADS
5150 int nCPUs = wxThread::GetCPUCount();
5151 printf("This system has %d CPUs\n", nCPUs);
5152 if ( nCPUs != -1 )
5153 wxThread::SetConcurrency(nCPUs);
5154
5155 if ( argc > 1 && argv[1][0] == 't' )
5156 wxLog::AddTraceMask("thread");
5157
5158 if ( 1 )
5159 TestDetachedThreads();
5160 if ( 1 )
5161 TestJoinableThreads();
5162 if ( 1 )
5163 TestThreadSuspend();
5164 if ( 1 )
5165 TestThreadDelete();
5166
5167 #endif // TEST_THREADS
5168
5169 #ifdef TEST_LONGLONG
5170 // seed pseudo random generator
5171 srand((unsigned)time(NULL));
5172
5173 if ( 0 )
5174 {
5175 TestSpeed();
5176 }
5177 if ( 0 )
5178 {
5179 TestMultiplication();
5180 TestDivision();
5181 TestAddition();
5182 TestLongLongConversion();
5183 TestBitOperations();
5184 TestLongLongComparison();
5185 }
5186 TestLongLongPrint();
5187 #endif // TEST_LONGLONG
5188
5189 #ifdef TEST_HASH
5190 TestHash();
5191 #endif // TEST_HASH
5192
5193 #ifdef TEST_MIME
5194 wxLog::AddTraceMask(_T("mime"));
5195 if ( 1 )
5196 {
5197 TestMimeEnum();
5198 TestMimeOverride();
5199 TestMimeFilename();
5200 }
5201 else
5202 TestMimeAssociate();
5203 #endif // TEST_MIME
5204
5205 #ifdef TEST_INFO_FUNCTIONS
5206 TestDiskInfo();
5207 if ( 0 )
5208 {
5209 TestOsInfo();
5210 TestUserInfo();
5211 }
5212 #endif // TEST_INFO_FUNCTIONS
5213
5214 #ifdef TEST_PATHLIST
5215 TestPathList();
5216 #endif // TEST_PATHLIST
5217
5218 #ifdef TEST_REGCONF
5219 TestRegConfWrite();
5220 #endif // TEST_REGCONF
5221
5222 #ifdef TEST_REGEX
5223 // TODO: write a real test using src/regex/tests file
5224 if ( 0 )
5225 {
5226 TestRegExCompile();
5227 TestRegExMatch();
5228 TestRegExSubmatch();
5229 TestRegExInteractive();
5230 }
5231 TestRegExReplacement();
5232 #endif // TEST_REGEX
5233
5234 #ifdef TEST_REGISTRY
5235 if ( 0 )
5236 TestRegistryRead();
5237 TestRegistryAssociation();
5238 #endif // TEST_REGISTRY
5239
5240 #ifdef TEST_SOCKETS
5241 if ( 0 )
5242 {
5243 TestSocketServer();
5244 }
5245 TestSocketClient();
5246 #endif // TEST_SOCKETS
5247
5248 #ifdef TEST_STREAMS
5249 if ( 0 )
5250 TestFileStream();
5251 TestMemoryStream();
5252 #endif // TEST_STREAMS
5253
5254 #ifdef TEST_TIMER
5255 TestStopWatch();
5256 #endif // TEST_TIMER
5257
5258 #ifdef TEST_DATETIME
5259 if ( 0 )
5260 {
5261 TestTimeSet();
5262 TestTimeStatic();
5263 TestTimeRange();
5264 TestTimeZones();
5265 TestTimeTicks();
5266 TestTimeJDN();
5267 TestTimeDST();
5268 TestTimeWDays();
5269 TestTimeWNumber();
5270 TestTimeParse();
5271 TestTimeArithmetics();
5272 TestTimeHolidays();
5273 TestTimeFormat();
5274 TestTimeMS();
5275
5276 TestTimeZoneBug();
5277 }
5278 TestTimeSpanFormat();
5279 if ( 0 )
5280 TestDateTimeInteractive();
5281 #endif // TEST_DATETIME
5282
5283 #ifdef TEST_USLEEP
5284 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5285 wxUsleep(3000);
5286 #endif // TEST_USLEEP
5287
5288 #ifdef TEST_VCARD
5289 if ( 0 )
5290 TestVCardRead();
5291 TestVCardWrite();
5292 #endif // TEST_VCARD
5293
5294 #ifdef TEST_WCHAR
5295 TestUtf8();
5296 #endif // TEST_WCHAR
5297
5298 #ifdef TEST_ZIP
5299 if ( 0 )
5300 TestZipStreamRead();
5301 TestZipFileSystem();
5302 #endif // TEST_ZIP
5303
5304 #ifdef TEST_ZLIB
5305 if ( 0 )
5306 TestZlibStreamWrite();
5307 TestZlibStreamRead();
5308 #endif // TEST_ZLIB
5309
5310 return 0;
5311 }
5312