1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
23 #error "This sample can't be compiled in GUI mode."
28 #include "wx/string.h"
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
43 A note about all these conditional compilation macros: this file is used
44 both as a test suite for various non-GUI wxWindows classes and as a
45 scratchpad for quick tests. So there are two compilation modes: if you
46 define TEST_ALL all tests are run, otherwise you may enable the individual
47 tests individually in the "#else" branch below.
50 // what to test (in alphabetic order)? uncomment the line below to do all tests
58 #define TEST_DLLLOADER
68 #define TEST_INFO_FUNCTIONS
85 // #define TEST_VCARD -- don't enable this (VZ)
92 static const bool TEST_ALL
= TRUE
;
96 static const bool TEST_ALL
= FALSE
;
99 // some tests are interactive, define this to run them
100 #ifdef TEST_INTERACTIVE
101 #undef TEST_INTERACTIVE
103 static const bool TEST_INTERACTIVE
= TRUE
;
105 static const bool TEST_INTERACTIVE
= FALSE
;
108 // ----------------------------------------------------------------------------
109 // test class for container objects
110 // ----------------------------------------------------------------------------
112 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
114 class Bar
// Foo is already taken in the hash test
117 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
118 Bar(const Bar
& bar
) : m_name(bar
.m_name
) { ms_bars
++; }
119 ~Bar() { ms_bars
--; }
121 static size_t GetNumber() { return ms_bars
; }
123 const char *GetName() const { return m_name
; }
128 static size_t ms_bars
;
131 size_t Bar::ms_bars
= 0;
133 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
135 // ============================================================================
137 // ============================================================================
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
143 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
145 // replace TABs with \t and CRs with \n
146 static wxString
MakePrintable(const wxChar
*s
)
149 (void)str
.Replace(_T("\t"), _T("\\t"));
150 (void)str
.Replace(_T("\n"), _T("\\n"));
151 (void)str
.Replace(_T("\r"), _T("\\r"));
156 #endif // MakePrintable() is used
158 // ----------------------------------------------------------------------------
159 // wxFontMapper::CharsetToEncoding
160 // ----------------------------------------------------------------------------
164 #include "wx/fontmap.h"
166 static void TestCharset()
168 static const wxChar
*charsets
[] =
170 // some vali charsets
179 // and now some bogus ones
186 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
188 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(charsets
[n
]);
189 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
191 wxFontMapper::Get()->GetEncodingName(enc
).c_str(),
192 wxFontMapper::Get()->GetEncodingDescription(enc
).c_str());
196 #endif // TEST_CHARSET
198 // ----------------------------------------------------------------------------
200 // ----------------------------------------------------------------------------
204 #include "wx/cmdline.h"
205 #include "wx/datetime.h"
207 #if wxUSE_CMDLINE_PARSER
209 static void ShowCmdLine(const wxCmdLineParser
& parser
)
211 wxString s
= "Input files: ";
213 size_t count
= parser
.GetParamCount();
214 for ( size_t param
= 0; param
< count
; param
++ )
216 s
<< parser
.GetParam(param
) << ' ';
220 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
221 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
226 if ( parser
.Found("o", &strVal
) )
227 s
<< "Output file:\t" << strVal
<< '\n';
228 if ( parser
.Found("i", &strVal
) )
229 s
<< "Input dir:\t" << strVal
<< '\n';
230 if ( parser
.Found("s", &lVal
) )
231 s
<< "Size:\t" << lVal
<< '\n';
232 if ( parser
.Found("d", &dt
) )
233 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
234 if ( parser
.Found("project_name", &strVal
) )
235 s
<< "Project:\t" << strVal
<< '\n';
240 #endif // wxUSE_CMDLINE_PARSER
242 static void TestCmdLineConvert()
244 static const char *cmdlines
[] =
247 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
248 "literal \\\" and \"\"",
251 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
253 const char *cmdline
= cmdlines
[n
];
254 printf("Parsing: %s\n", cmdline
);
255 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
257 size_t count
= args
.GetCount();
258 printf("\targc = %u\n", count
);
259 for ( size_t arg
= 0; arg
< count
; arg
++ )
261 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
266 #endif // TEST_CMDLINE
268 // ----------------------------------------------------------------------------
270 // ----------------------------------------------------------------------------
277 static const wxChar
*ROOTDIR
= _T("/");
278 static const wxChar
*TESTDIR
= _T("/usr");
279 #elif defined(__WXMSW__)
280 static const wxChar
*ROOTDIR
= _T("c:\\");
281 static const wxChar
*TESTDIR
= _T("d:\\");
283 #error "don't know where the root directory is"
286 static void TestDirEnumHelper(wxDir
& dir
,
287 int flags
= wxDIR_DEFAULT
,
288 const wxString
& filespec
= wxEmptyString
)
292 if ( !dir
.IsOpened() )
295 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
298 printf("\t%s\n", filename
.c_str());
300 cont
= dir
.GetNext(&filename
);
306 static void TestDirEnum()
308 puts("*** Testing wxDir::GetFirst/GetNext ***");
310 wxDir
dir(wxGetCwd());
312 puts("Enumerating everything in current directory:");
313 TestDirEnumHelper(dir
);
315 puts("Enumerating really everything in current directory:");
316 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
318 puts("Enumerating object files in current directory:");
319 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
321 puts("Enumerating directories in current directory:");
322 TestDirEnumHelper(dir
, wxDIR_DIRS
);
324 puts("Enumerating files in current directory:");
325 TestDirEnumHelper(dir
, wxDIR_FILES
);
327 puts("Enumerating files including hidden in current directory:");
328 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
332 puts("Enumerating everything in root directory:");
333 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
335 puts("Enumerating directories in root directory:");
336 TestDirEnumHelper(dir
, wxDIR_DIRS
);
338 puts("Enumerating files in root directory:");
339 TestDirEnumHelper(dir
, wxDIR_FILES
);
341 puts("Enumerating files including hidden in root directory:");
342 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
344 puts("Enumerating files in non existing directory:");
345 wxDir
dirNo("nosuchdir");
346 TestDirEnumHelper(dirNo
);
349 class DirPrintTraverser
: public wxDirTraverser
352 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
354 return wxDIR_CONTINUE
;
357 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
359 wxString path
, name
, ext
;
360 wxSplitPath(dirname
, &path
, &name
, &ext
);
363 name
<< _T('.') << ext
;
366 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
368 if ( wxIsPathSeparator(*p
) )
372 printf("%s%s\n", indent
.c_str(), name
.c_str());
374 return wxDIR_CONTINUE
;
378 static void TestDirTraverse()
380 puts("*** Testing wxDir::Traverse() ***");
384 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
385 printf("There are %u files under '%s'\n", n
, TESTDIR
);
388 printf("First one is '%s'\n", files
[0u].c_str());
389 printf(" last one is '%s'\n", files
[n
- 1].c_str());
392 // enum again with custom traverser
394 DirPrintTraverser traverser
;
395 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
400 // ----------------------------------------------------------------------------
402 // ----------------------------------------------------------------------------
404 #ifdef TEST_DLLLOADER
406 #include "wx/dynlib.h"
408 static void TestDllLoad()
410 #if defined(__WXMSW__)
411 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
412 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
413 #elif defined(__UNIX__)
414 // weird: using just libc.so does *not* work!
415 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
416 static const wxChar
*FUNC_NAME
= _T("strlen");
418 #error "don't know how to test wxDllLoader on this platform"
421 puts("*** testing wxDllLoader ***\n");
423 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
426 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
430 typedef int (*strlenType
)(const char *);
431 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
434 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
435 FUNC_NAME
, LIB_NAME
);
439 if ( pfnStrlen("foo") != 3 )
441 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
449 wxDllLoader::UnloadLibrary(dllHandle
);
453 #endif // TEST_DLLLOADER
455 // ----------------------------------------------------------------------------
457 // ----------------------------------------------------------------------------
461 #include "wx/utils.h"
463 static wxString
MyGetEnv(const wxString
& var
)
466 if ( !wxGetEnv(var
, &val
) )
469 val
= wxString(_T('\'')) + val
+ _T('\'');
474 static void TestEnvironment()
476 const wxChar
*var
= _T("wxTestVar");
478 puts("*** testing environment access functions ***");
480 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
481 wxSetEnv(var
, _T("value for wxTestVar"));
482 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
483 wxSetEnv(var
, _T("another value"));
484 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
486 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
487 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
490 #endif // TEST_ENVIRON
492 // ----------------------------------------------------------------------------
494 // ----------------------------------------------------------------------------
498 #include "wx/utils.h"
500 static void TestExecute()
502 puts("*** testing wxExecute ***");
505 #define COMMAND "cat -n ../../Makefile" // "echo hi"
506 #define SHELL_COMMAND "echo hi from shell"
507 #define REDIRECT_COMMAND COMMAND // "date"
508 #elif defined(__WXMSW__)
509 #define COMMAND "command.com -c 'echo hi'"
510 #define SHELL_COMMAND "echo hi"
511 #define REDIRECT_COMMAND COMMAND
513 #error "no command to exec"
516 printf("Testing wxShell: ");
518 if ( wxShell(SHELL_COMMAND
) )
523 printf("Testing wxExecute: ");
525 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
530 #if 0 // no, it doesn't work (yet?)
531 printf("Testing async wxExecute: ");
533 if ( wxExecute(COMMAND
) != 0 )
534 puts("Ok (command launched).");
539 printf("Testing wxExecute with redirection:\n");
540 wxArrayString output
;
541 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
547 size_t count
= output
.GetCount();
548 for ( size_t n
= 0; n
< count
; n
++ )
550 printf("\t%s\n", output
[n
].c_str());
557 #endif // TEST_EXECUTE
559 // ----------------------------------------------------------------------------
561 // ----------------------------------------------------------------------------
566 #include "wx/ffile.h"
567 #include "wx/textfile.h"
569 static void TestFileRead()
571 puts("*** wxFile read test ***");
573 wxFile
file(_T("testdata.fc"));
574 if ( file
.IsOpened() )
576 printf("File length: %lu\n", file
.Length());
578 puts("File dump:\n----------");
580 static const off_t len
= 1024;
584 off_t nRead
= file
.Read(buf
, len
);
585 if ( nRead
== wxInvalidOffset
)
587 printf("Failed to read the file.");
591 fwrite(buf
, nRead
, 1, stdout
);
601 printf("ERROR: can't open test file.\n");
607 static void TestTextFileRead()
609 puts("*** wxTextFile read test ***");
611 wxTextFile
file(_T("testdata.fc"));
614 printf("Number of lines: %u\n", file
.GetLineCount());
615 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
619 puts("\nDumping the entire file:");
620 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
622 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
624 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
626 puts("\nAnd now backwards:");
627 for ( s
= file
.GetLastLine();
628 file
.GetCurrentLine() != 0;
629 s
= file
.GetPrevLine() )
631 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
633 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
637 printf("ERROR: can't open '%s'\n", file
.GetName());
643 static void TestFileCopy()
645 puts("*** Testing wxCopyFile ***");
647 static const wxChar
*filename1
= _T("testdata.fc");
648 static const wxChar
*filename2
= _T("test2");
649 if ( !wxCopyFile(filename1
, filename2
) )
651 puts("ERROR: failed to copy file");
655 wxFFile
f1(filename1
, "rb"),
658 if ( !f1
.IsOpened() || !f2
.IsOpened() )
660 puts("ERROR: failed to open file(s)");
665 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
667 puts("ERROR: failed to read file(s)");
671 if ( (s1
.length() != s2
.length()) ||
672 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
674 puts("ERROR: copy error!");
678 puts("File was copied ok.");
684 if ( !wxRemoveFile(filename2
) )
686 puts("ERROR: failed to remove the file");
694 // ----------------------------------------------------------------------------
696 // ----------------------------------------------------------------------------
700 #include "wx/confbase.h"
701 #include "wx/fileconf.h"
703 static const struct FileConfTestData
705 const wxChar
*name
; // value name
706 const wxChar
*value
; // the value from the file
709 { _T("value1"), _T("one") },
710 { _T("value2"), _T("two") },
711 { _T("novalue"), _T("default") },
714 static void TestFileConfRead()
716 puts("*** testing wxFileConfig loading/reading ***");
718 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
719 _T("testdata.fc"), wxEmptyString
,
720 wxCONFIG_USE_RELATIVE_PATH
);
722 // test simple reading
723 puts("\nReading config file:");
724 wxString
defValue(_T("default")), value
;
725 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
727 const FileConfTestData
& data
= fcTestData
[n
];
728 value
= fileconf
.Read(data
.name
, defValue
);
729 printf("\t%s = %s ", data
.name
, value
.c_str());
730 if ( value
== data
.value
)
736 printf("(ERROR: should be %s)\n", data
.value
);
740 // test enumerating the entries
741 puts("\nEnumerating all root entries:");
744 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
747 printf("\t%s = %s\n",
749 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
751 cont
= fileconf
.GetNextEntry(name
, dummy
);
755 #endif // TEST_FILECONF
757 // ----------------------------------------------------------------------------
759 // ----------------------------------------------------------------------------
763 #include "wx/filename.h"
765 static void DumpFileName(const wxFileName
& fn
)
767 wxString full
= fn
.GetFullPath();
769 wxString vol
, path
, name
, ext
;
770 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
772 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
773 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
775 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
776 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
777 path
.c_str(), name
.c_str(), ext
.c_str());
779 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
780 wxPrintf(_T("with volume: \t'%s'\n"),
781 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
782 wxPrintf(_T("with separator:\t'%s'\n"),
783 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
784 wxPrintf(_T("with both: \t'%s'\n"),
785 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
787 wxPuts(_T("The directories in the path are:"));
788 wxArrayString dirs
= fn
.GetDirs();
789 size_t count
= dirs
.GetCount();
790 for ( size_t n
= 0; n
< count
; n
++ )
792 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
796 static struct FileNameInfo
798 const wxChar
*fullname
;
799 const wxChar
*volume
;
808 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
809 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
810 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
811 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
812 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
813 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
814 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
815 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
816 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
818 // Windows file names
819 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
820 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
821 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
822 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
823 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
824 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
826 // wxFileName support for Mac file names is broken currently
829 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
830 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
831 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
832 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
833 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
834 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
838 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
839 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
842 static void TestFileNameConstruction()
844 puts("*** testing wxFileName construction ***");
846 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
848 const FileNameInfo
& fni
= filenames
[n
];
850 wxFileName
fn(fni
.fullname
, fni
.format
);
852 wxString fullname
= fn
.GetFullPath(fni
.format
);
853 if ( fullname
!= fni
.fullname
)
855 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
858 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
859 printf("'%s' is %s (%s)\n\t",
861 isAbsolute
? "absolute" : "relative",
862 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
864 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
866 puts("ERROR (couldn't be normalized)");
870 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
877 static void TestFileNameSplit()
879 puts("*** testing wxFileName splitting ***");
881 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
883 const FileNameInfo
& fni
= filenames
[n
];
884 wxString volume
, path
, name
, ext
;
885 wxFileName::SplitPath(fni
.fullname
,
886 &volume
, &path
, &name
, &ext
, fni
.format
);
888 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
890 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
892 if ( volume
!= fni
.volume
)
893 printf(" (ERROR: volume = '%s')", fni
.volume
);
894 if ( path
!= fni
.path
)
895 printf(" (ERROR: path = '%s')", fni
.path
);
896 if ( name
!= fni
.name
)
897 printf(" (ERROR: name = '%s')", fni
.name
);
898 if ( ext
!= fni
.ext
)
899 printf(" (ERROR: ext = '%s')", fni
.ext
);
905 static void TestFileNameTemp()
907 puts("*** testing wxFileName temp file creation ***");
909 static const char *tmpprefixes
[] =
917 "/tmp/foo/bar", // this one must be an error
921 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
923 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
926 // "error" is not in upper case because it may be ok
927 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
931 printf("Prefix '%s'\t-> temp file '%s'\n",
932 tmpprefixes
[n
], path
.c_str());
934 if ( !wxRemoveFile(path
) )
936 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
942 static void TestFileNameMakeRelative()
944 puts("*** testing wxFileName::MakeRelativeTo() ***");
946 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
948 const FileNameInfo
& fni
= filenames
[n
];
950 wxFileName
fn(fni
.fullname
, fni
.format
);
952 // choose the base dir of the same format
954 switch ( fni
.format
)
966 // TODO: I don't know how this is supposed to work there
969 case wxPATH_NATIVE
: // make gcc happy
971 wxFAIL_MSG( "unexpected path format" );
974 printf("'%s' relative to '%s': ",
975 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
977 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
983 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
988 static void TestFileNameComparison()
993 static void TestFileNameOperations()
998 static void TestFileNameCwd()
1003 #endif // TEST_FILENAME
1005 // ----------------------------------------------------------------------------
1006 // wxFileName time functions
1007 // ----------------------------------------------------------------------------
1009 #ifdef TEST_FILETIME
1011 #include <wx/filename.h>
1012 #include <wx/datetime.h>
1014 static void TestFileGetTimes()
1016 wxFileName
fn(_T("testdata.fc"));
1018 wxDateTime dtAccess
, dtMod
, dtCreate
;
1019 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1021 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1025 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1027 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1028 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1029 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1030 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1034 static void TestFileSetTimes()
1036 wxFileName
fn(_T("testdata.fc"));
1040 wxPrintf(_T("ERROR: Touch() failed.\n"));
1044 #endif // TEST_FILETIME
1046 // ----------------------------------------------------------------------------
1048 // ----------------------------------------------------------------------------
1052 #include "wx/hash.h"
1056 Foo(int n_
) { n
= n_
; count
++; }
1061 static size_t count
;
1064 size_t Foo::count
= 0;
1066 WX_DECLARE_LIST(Foo
, wxListFoos
);
1067 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1069 #include "wx/listimpl.cpp"
1071 WX_DEFINE_LIST(wxListFoos
);
1073 static void TestHash()
1075 puts("*** Testing wxHashTable ***\n");
1079 hash
.DeleteContents(TRUE
);
1081 printf("Hash created: %u foos in hash, %u foos totally\n",
1082 hash
.GetCount(), Foo::count
);
1084 static const int hashTestData
[] =
1086 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1090 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1092 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1095 printf("Hash filled: %u foos in hash, %u foos totally\n",
1096 hash
.GetCount(), Foo::count
);
1098 puts("Hash access test:");
1099 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1101 printf("\tGetting element with key %d, value %d: ",
1102 hashTestData
[n
], n
);
1103 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1106 printf("ERROR, not found.\n");
1110 printf("%d (%s)\n", foo
->n
,
1111 (size_t)foo
->n
== n
? "ok" : "ERROR");
1115 printf("\nTrying to get an element not in hash: ");
1117 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1119 puts("ERROR: found!");
1123 puts("ok (not found)");
1127 printf("Hash destroyed: %u foos left\n", Foo::count
);
1132 // ----------------------------------------------------------------------------
1134 // ----------------------------------------------------------------------------
1138 #include "wx/hashmap.h"
1140 // test compilation of basic map types
1141 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1142 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1143 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1144 myUnsignedHashMap
);
1145 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1147 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1149 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1151 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1155 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1156 // myStringHashMap );
1157 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1159 typedef myStringHashMap::iterator Itor
;
1161 static void TestHashMap()
1163 puts("*** Testing wxHashMap ***\n");
1164 myStringHashMap
sh(0); // as small as possible
1167 const size_t count
= 10000;
1169 // init with some data
1170 for( i
= 0; i
< count
; ++i
)
1172 buf
.Printf(wxT("%d"), i
);
1173 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1176 // test that insertion worked
1177 if( sh
.size() != count
)
1179 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1182 for( i
= 0; i
< count
; ++i
)
1184 buf
.Printf(wxT("%d"), i
);
1185 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1187 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1192 // check that iterators work
1194 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1198 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1202 if( it
->second
!= sh
[it
->first
] )
1204 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1209 if( sh
.size() != i
)
1211 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1214 // test copy ctor, assignment operator
1215 myStringHashMap
h1( sh
), h2( 0 );
1218 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1220 if( h1
[it
->first
] != it
->second
)
1222 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1225 if( h2
[it
->first
] != it
->second
)
1227 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1232 for( i
= 0; i
< count
; ++i
)
1234 buf
.Printf(wxT("%d"), i
);
1235 size_t sz
= sh
.size();
1237 // test find() and erase(it)
1240 it
= sh
.find( buf
);
1241 if( it
!= sh
.end() )
1245 if( sh
.find( buf
) != sh
.end() )
1247 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1251 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1256 size_t c
= sh
.erase( buf
);
1258 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1260 if( sh
.find( buf
) != sh
.end() )
1262 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1266 // count should decrease
1267 if( sh
.size() != sz
- 1 )
1269 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1273 printf("*** Finished testing wxHashMap ***\n");
1276 #endif // TEST_HASHMAP
1278 // ----------------------------------------------------------------------------
1280 // ----------------------------------------------------------------------------
1284 #include "wx/list.h"
1286 WX_DECLARE_LIST(Bar
, wxListBars
);
1287 #include "wx/listimpl.cpp"
1288 WX_DEFINE_LIST(wxListBars
);
1290 static void TestListCtor()
1292 puts("*** Testing wxList construction ***\n");
1296 list1
.Append(new Bar(_T("first")));
1297 list1
.Append(new Bar(_T("second")));
1299 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1300 list1
.GetCount(), Bar::GetNumber());
1305 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1306 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1308 list1
.DeleteContents(TRUE
);
1311 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1316 // ----------------------------------------------------------------------------
1318 // ----------------------------------------------------------------------------
1322 #include "wx/intl.h"
1323 #include "wx/utils.h" // for wxSetEnv
1325 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1327 // find the name of the language from its value
1328 static const char *GetLangName(int lang
)
1330 static const char *languageNames
[] =
1351 "ARABIC_SAUDI_ARABIA",
1376 "CHINESE_SIMPLIFIED",
1377 "CHINESE_TRADITIONAL",
1380 "CHINESE_SINGAPORE",
1391 "ENGLISH_AUSTRALIA",
1395 "ENGLISH_CARIBBEAN",
1399 "ENGLISH_NEW_ZEALAND",
1400 "ENGLISH_PHILIPPINES",
1401 "ENGLISH_SOUTH_AFRICA",
1413 "FRENCH_LUXEMBOURG",
1422 "GERMAN_LIECHTENSTEIN",
1423 "GERMAN_LUXEMBOURG",
1464 "MALAY_BRUNEI_DARUSSALAM",
1476 "NORWEGIAN_NYNORSK",
1483 "PORTUGUESE_BRAZILIAN",
1508 "SPANISH_ARGENTINA",
1512 "SPANISH_COSTA_RICA",
1513 "SPANISH_DOMINICAN_REPUBLIC",
1515 "SPANISH_EL_SALVADOR",
1516 "SPANISH_GUATEMALA",
1520 "SPANISH_NICARAGUA",
1524 "SPANISH_PUERTO_RICO",
1527 "SPANISH_VENEZUELA",
1564 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1565 return languageNames
[lang
];
1570 static void TestDefaultLang()
1572 puts("*** Testing wxLocale::GetSystemLanguage ***");
1574 static const wxChar
*langStrings
[] =
1576 NULL
, // system default
1583 _T("de_DE.iso88591"),
1585 _T("?"), // invalid lang spec
1586 _T("klingonese"), // I bet on some systems it does exist...
1589 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1590 wxLocale::GetSystemEncodingName().c_str(),
1591 wxLocale::GetSystemEncoding());
1593 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1595 const char *langStr
= langStrings
[n
];
1598 // FIXME: this doesn't do anything at all under Windows, we need
1599 // to create a new wxLocale!
1600 wxSetEnv(_T("LC_ALL"), langStr
);
1603 int lang
= gs_localeDefault
.GetSystemLanguage();
1604 printf("Locale for '%s' is %s.\n",
1605 langStr
? langStr
: "system default", GetLangName(lang
));
1609 #endif // TEST_LOCALE
1611 // ----------------------------------------------------------------------------
1613 // ----------------------------------------------------------------------------
1617 #include "wx/mimetype.h"
1619 static void TestMimeEnum()
1621 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1623 wxArrayString mimetypes
;
1625 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1627 printf("*** All %u known filetypes: ***\n", count
);
1632 for ( size_t n
= 0; n
< count
; n
++ )
1634 wxFileType
*filetype
=
1635 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1638 printf("nothing known about the filetype '%s'!\n",
1639 mimetypes
[n
].c_str());
1643 filetype
->GetDescription(&desc
);
1644 filetype
->GetExtensions(exts
);
1646 filetype
->GetIcon(NULL
);
1649 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1652 extsAll
<< _T(", ");
1656 printf("\t%s: %s (%s)\n",
1657 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1663 static void TestMimeOverride()
1665 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1667 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1668 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1670 if ( wxFile::Exists(mailcap
) )
1671 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1673 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1675 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1678 if ( wxFile::Exists(mimetypes
) )
1679 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1681 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1683 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1689 static void TestMimeFilename()
1691 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1693 static const wxChar
*filenames
[] =
1700 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1702 const wxString fname
= filenames
[n
];
1703 wxString ext
= fname
.AfterLast(_T('.'));
1704 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1707 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1712 if ( !ft
->GetDescription(&desc
) )
1713 desc
= _T("<no description>");
1716 if ( !ft
->GetOpenCommand(&cmd
,
1717 wxFileType::MessageParameters(fname
, _T(""))) )
1718 cmd
= _T("<no command available>");
1720 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1721 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1730 static void TestMimeAssociate()
1732 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1734 wxFileTypeInfo
ftInfo(
1735 _T("application/x-xyz"),
1736 _T("xyzview '%s'"), // open cmd
1737 _T(""), // print cmd
1738 _T("XYZ File"), // description
1739 _T(".xyz"), // extensions
1740 NULL
// end of extensions
1742 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1744 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1747 wxPuts(_T("ERROR: failed to create association!"));
1751 // TODO: read it back
1760 // ----------------------------------------------------------------------------
1761 // misc information functions
1762 // ----------------------------------------------------------------------------
1764 #ifdef TEST_INFO_FUNCTIONS
1766 #include "wx/utils.h"
1768 static void TestDiskInfo()
1770 puts("*** Testing wxGetDiskSpace() ***");
1775 printf("\nEnter a directory name: ");
1776 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1779 // kill the last '\n'
1780 pathname
[strlen(pathname
) - 1] = 0;
1782 wxLongLong total
, free
;
1783 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1785 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1789 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1790 (total
/ 1024).ToString().c_str(),
1791 (free
/ 1024).ToString().c_str(),
1797 static void TestOsInfo()
1799 puts("*** Testing OS info functions ***\n");
1802 wxGetOsVersion(&major
, &minor
);
1803 printf("Running under: %s, version %d.%d\n",
1804 wxGetOsDescription().c_str(), major
, minor
);
1806 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1808 printf("Host name is %s (%s).\n",
1809 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1814 static void TestUserInfo()
1816 puts("*** Testing user info functions ***\n");
1818 printf("User id is:\t%s\n", wxGetUserId().c_str());
1819 printf("User name is:\t%s\n", wxGetUserName().c_str());
1820 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1821 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1826 #endif // TEST_INFO_FUNCTIONS
1828 // ----------------------------------------------------------------------------
1830 // ----------------------------------------------------------------------------
1832 #ifdef TEST_LONGLONG
1834 #include "wx/longlong.h"
1835 #include "wx/timer.h"
1837 // make a 64 bit number from 4 16 bit ones
1838 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1840 // get a random 64 bit number
1841 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1843 static const long testLongs
[] =
1854 #if wxUSE_LONGLONG_WX
1855 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1856 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1857 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1858 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1859 #endif // wxUSE_LONGLONG_WX
1861 static void TestSpeed()
1863 static const long max
= 100000000;
1870 for ( n
= 0; n
< max
; n
++ )
1875 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1878 #if wxUSE_LONGLONG_NATIVE
1883 for ( n
= 0; n
< max
; n
++ )
1888 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1890 #endif // wxUSE_LONGLONG_NATIVE
1896 for ( n
= 0; n
< max
; n
++ )
1901 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1905 static void TestLongLongConversion()
1907 puts("*** Testing wxLongLong conversions ***\n");
1911 for ( size_t n
= 0; n
< 100000; n
++ )
1915 #if wxUSE_LONGLONG_NATIVE
1916 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1918 wxASSERT_MSG( a
== b
, "conversions failure" );
1920 puts("Can't do it without native long long type, test skipped.");
1923 #endif // wxUSE_LONGLONG_NATIVE
1925 if ( !(nTested
% 1000) )
1937 static void TestMultiplication()
1939 puts("*** Testing wxLongLong multiplication ***\n");
1943 for ( size_t n
= 0; n
< 100000; n
++ )
1948 #if wxUSE_LONGLONG_NATIVE
1949 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1950 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1952 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1953 #else // !wxUSE_LONGLONG_NATIVE
1954 puts("Can't do it without native long long type, test skipped.");
1957 #endif // wxUSE_LONGLONG_NATIVE
1959 if ( !(nTested
% 1000) )
1971 static void TestDivision()
1973 puts("*** Testing wxLongLong division ***\n");
1977 for ( size_t n
= 0; n
< 100000; n
++ )
1979 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1980 // multiplication will not overflow)
1981 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1983 // get a random (but non null) long (not wxLongLong for now) to divide
1995 #if wxUSE_LONGLONG_NATIVE
1996 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1998 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1999 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
2000 #else // !wxUSE_LONGLONG_NATIVE
2001 // verify the result
2002 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
2003 #endif // wxUSE_LONGLONG_NATIVE
2005 if ( !(nTested
% 1000) )
2017 static void TestAddition()
2019 puts("*** Testing wxLongLong addition ***\n");
2023 for ( size_t n
= 0; n
< 100000; n
++ )
2029 #if wxUSE_LONGLONG_NATIVE
2030 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2031 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2032 "addition failure" );
2033 #else // !wxUSE_LONGLONG_NATIVE
2034 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2035 #endif // wxUSE_LONGLONG_NATIVE
2037 if ( !(nTested
% 1000) )
2049 static void TestBitOperations()
2051 puts("*** Testing wxLongLong bit operation ***\n");
2055 for ( size_t n
= 0; n
< 100000; n
++ )
2059 #if wxUSE_LONGLONG_NATIVE
2060 for ( size_t n
= 0; n
< 33; n
++ )
2063 #else // !wxUSE_LONGLONG_NATIVE
2064 puts("Can't do it without native long long type, test skipped.");
2067 #endif // wxUSE_LONGLONG_NATIVE
2069 if ( !(nTested
% 1000) )
2081 static void TestLongLongComparison()
2083 #if wxUSE_LONGLONG_WX
2084 puts("*** Testing wxLongLong comparison ***\n");
2086 static const long ls
[2] =
2092 wxLongLongWx lls
[2];
2096 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2100 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2102 res
= lls
[m
] > testLongs
[n
];
2103 printf("0x%lx > 0x%lx is %s (%s)\n",
2104 ls
[m
], testLongs
[n
], res
? "true" : "false",
2105 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2107 res
= lls
[m
] < testLongs
[n
];
2108 printf("0x%lx < 0x%lx is %s (%s)\n",
2109 ls
[m
], testLongs
[n
], res
? "true" : "false",
2110 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2112 res
= lls
[m
] == testLongs
[n
];
2113 printf("0x%lx == 0x%lx is %s (%s)\n",
2114 ls
[m
], testLongs
[n
], res
? "true" : "false",
2115 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2118 #endif // wxUSE_LONGLONG_WX
2121 static void TestLongLongPrint()
2123 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2125 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2127 wxLongLong ll
= testLongs
[n
];
2128 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2131 wxLongLong
ll(0x12345678, 0x87654321);
2132 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2135 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2141 #endif // TEST_LONGLONG
2143 // ----------------------------------------------------------------------------
2145 // ----------------------------------------------------------------------------
2147 #ifdef TEST_PATHLIST
2149 static void TestPathList()
2151 puts("*** Testing wxPathList ***\n");
2153 wxPathList pathlist
;
2154 pathlist
.AddEnvList("PATH");
2155 wxString path
= pathlist
.FindValidPath("ls");
2158 printf("ERROR: command not found in the path.\n");
2162 printf("Command found in the path as '%s'.\n", path
.c_str());
2166 #endif // TEST_PATHLIST
2168 // ----------------------------------------------------------------------------
2169 // regular expressions
2170 // ----------------------------------------------------------------------------
2174 #include "wx/regex.h"
2176 static void TestRegExCompile()
2178 wxPuts(_T("*** Testing RE compilation ***\n"));
2180 static struct RegExCompTestData
2182 const wxChar
*pattern
;
2184 } regExCompTestData
[] =
2186 { _T("foo"), TRUE
},
2187 { _T("foo("), FALSE
},
2188 { _T("foo(bar"), FALSE
},
2189 { _T("foo(bar)"), TRUE
},
2190 { _T("foo["), FALSE
},
2191 { _T("foo[bar"), FALSE
},
2192 { _T("foo[bar]"), TRUE
},
2193 { _T("foo{"), TRUE
},
2194 { _T("foo{1"), FALSE
},
2195 { _T("foo{bar"), TRUE
},
2196 { _T("foo{1}"), TRUE
},
2197 { _T("foo{1,2}"), TRUE
},
2198 { _T("foo{bar}"), TRUE
},
2199 { _T("foo*"), TRUE
},
2200 { _T("foo**"), FALSE
},
2201 { _T("foo+"), TRUE
},
2202 { _T("foo++"), FALSE
},
2203 { _T("foo?"), TRUE
},
2204 { _T("foo??"), FALSE
},
2205 { _T("foo?+"), FALSE
},
2209 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2211 const RegExCompTestData
& data
= regExCompTestData
[n
];
2212 bool ok
= re
.Compile(data
.pattern
);
2214 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2216 ok
? _T("") : _T("not "),
2217 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2221 static void TestRegExMatch()
2223 wxPuts(_T("*** Testing RE matching ***\n"));
2225 static struct RegExMatchTestData
2227 const wxChar
*pattern
;
2230 } regExMatchTestData
[] =
2232 { _T("foo"), _T("bar"), FALSE
},
2233 { _T("foo"), _T("foobar"), TRUE
},
2234 { _T("^foo"), _T("foobar"), TRUE
},
2235 { _T("^foo"), _T("barfoo"), FALSE
},
2236 { _T("bar$"), _T("barbar"), TRUE
},
2237 { _T("bar$"), _T("barbar "), FALSE
},
2240 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2242 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2244 wxRegEx
re(data
.pattern
);
2245 bool ok
= re
.Matches(data
.text
);
2247 wxPrintf(_T("'%s' %s %s (%s)\n"),
2249 ok
? _T("matches") : _T("doesn't match"),
2251 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2255 static void TestRegExSubmatch()
2257 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2259 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2260 if ( !re
.IsValid() )
2262 wxPuts(_T("ERROR: compilation failed."));
2266 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2268 if ( !re
.Matches(text
) )
2270 wxPuts(_T("ERROR: match expected."));
2274 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2276 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2277 re
.GetMatch(text
, 3).c_str(),
2278 re
.GetMatch(text
, 2).c_str(),
2279 re
.GetMatch(text
, 4).c_str(),
2280 re
.GetMatch(text
, 1).c_str());
2284 static void TestRegExReplacement()
2286 wxPuts(_T("*** Testing RE replacement ***"));
2288 static struct RegExReplTestData
2292 const wxChar
*result
;
2294 } regExReplTestData
[] =
2296 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2297 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2298 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2299 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2300 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2301 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2302 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2305 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2306 wxRegEx
re(pattern
);
2308 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2310 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2312 const RegExReplTestData
& data
= regExReplTestData
[n
];
2314 wxString text
= data
.text
;
2315 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2317 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2318 data
.text
, data
.repl
,
2319 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2321 if ( text
== data
.result
&& nRepl
== data
.count
)
2327 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2328 data
.count
, data
.result
);
2333 static void TestRegExInteractive()
2335 wxPuts(_T("*** Testing RE interactively ***"));
2340 printf("\nEnter a pattern: ");
2341 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2344 // kill the last '\n'
2345 pattern
[strlen(pattern
) - 1] = 0;
2348 if ( !re
.Compile(pattern
) )
2356 printf("Enter text to match: ");
2357 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2360 // kill the last '\n'
2361 text
[strlen(text
) - 1] = 0;
2363 if ( !re
.Matches(text
) )
2365 printf("No match.\n");
2369 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2372 for ( size_t n
= 1; ; n
++ )
2374 if ( !re
.GetMatch(&start
, &len
, n
) )
2379 printf("Subexpr %u matched '%s'\n",
2380 n
, wxString(text
+ start
, len
).c_str());
2387 #endif // TEST_REGEX
2389 // ----------------------------------------------------------------------------
2391 // ----------------------------------------------------------------------------
2397 static void TestDbOpen()
2405 // ----------------------------------------------------------------------------
2406 // registry and related stuff
2407 // ----------------------------------------------------------------------------
2409 // this is for MSW only
2412 #undef TEST_REGISTRY
2417 #include "wx/confbase.h"
2418 #include "wx/msw/regconf.h"
2420 static void TestRegConfWrite()
2422 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2423 regconf
.Write(_T("Hello"), wxString(_T("world")));
2426 #endif // TEST_REGCONF
2428 #ifdef TEST_REGISTRY
2430 #include "wx/msw/registry.h"
2432 // I chose this one because I liked its name, but it probably only exists under
2434 static const wxChar
*TESTKEY
=
2435 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2437 static void TestRegistryRead()
2439 puts("*** testing registry reading ***");
2441 wxRegKey
key(TESTKEY
);
2442 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2445 puts("ERROR: test key can't be opened, aborting test.");
2450 size_t nSubKeys
, nValues
;
2451 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2453 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2456 printf("Enumerating values:\n");
2460 bool cont
= key
.GetFirstValue(value
, dummy
);
2463 printf("Value '%s': type ", value
.c_str());
2464 switch ( key
.GetValueType(value
) )
2466 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2467 case wxRegKey::Type_String
: printf("SZ"); break;
2468 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2469 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2470 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2471 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2472 default: printf("other (unknown)"); break;
2475 printf(", value = ");
2476 if ( key
.IsNumericValue(value
) )
2479 key
.QueryValue(value
, &val
);
2485 key
.QueryValue(value
, val
);
2486 printf("'%s'", val
.c_str());
2488 key
.QueryRawValue(value
, val
);
2489 printf(" (raw value '%s')", val
.c_str());
2494 cont
= key
.GetNextValue(value
, dummy
);
2498 static void TestRegistryAssociation()
2501 The second call to deleteself genertaes an error message, with a
2502 messagebox saying .flo is crucial to system operation, while the .ddf
2503 call also fails, but with no error message
2508 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2510 key
= "ddxf_auto_file" ;
2511 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2513 key
= "ddxf_auto_file" ;
2514 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2517 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2519 key
= "program \"%1\"" ;
2521 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2523 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2525 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2527 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2531 #endif // TEST_REGISTRY
2533 // ----------------------------------------------------------------------------
2535 // ----------------------------------------------------------------------------
2539 #include "wx/socket.h"
2540 #include "wx/protocol/protocol.h"
2541 #include "wx/protocol/http.h"
2543 static void TestSocketServer()
2545 puts("*** Testing wxSocketServer ***\n");
2547 static const int PORT
= 3000;
2552 wxSocketServer
*server
= new wxSocketServer(addr
);
2553 if ( !server
->Ok() )
2555 puts("ERROR: failed to bind");
2562 printf("Server: waiting for connection on port %d...\n", PORT
);
2564 wxSocketBase
*socket
= server
->Accept();
2567 puts("ERROR: wxSocketServer::Accept() failed.");
2571 puts("Server: got a client.");
2573 server
->SetTimeout(60); // 1 min
2575 while ( socket
->IsConnected() )
2581 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2583 // don't log error if the client just close the connection
2584 if ( socket
->IsConnected() )
2586 puts("ERROR: in wxSocket::Read.");
2606 printf("Server: got '%s'.\n", s
.c_str());
2607 if ( s
== _T("bye") )
2614 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2615 socket
->Write("\r\n", 2);
2616 printf("Server: wrote '%s'.\n", s
.c_str());
2619 puts("Server: lost a client.");
2624 // same as "delete server" but is consistent with GUI programs
2628 static void TestSocketClient()
2630 puts("*** Testing wxSocketClient ***\n");
2632 static const char *hostname
= "www.wxwindows.org";
2635 addr
.Hostname(hostname
);
2638 printf("--- Attempting to connect to %s:80...\n", hostname
);
2640 wxSocketClient client
;
2641 if ( !client
.Connect(addr
) )
2643 printf("ERROR: failed to connect to %s\n", hostname
);
2647 printf("--- Connected to %s:%u...\n",
2648 addr
.Hostname().c_str(), addr
.Service());
2652 // could use simply "GET" here I suppose
2654 wxString::Format("GET http://%s/\r\n", hostname
);
2655 client
.Write(cmdGet
, cmdGet
.length());
2656 printf("--- Sent command '%s' to the server\n",
2657 MakePrintable(cmdGet
).c_str());
2658 client
.Read(buf
, WXSIZEOF(buf
));
2659 printf("--- Server replied:\n%s", buf
);
2663 #endif // TEST_SOCKETS
2665 // ----------------------------------------------------------------------------
2667 // ----------------------------------------------------------------------------
2671 #include "wx/protocol/ftp.h"
2675 #define FTP_ANONYMOUS
2677 #ifdef FTP_ANONYMOUS
2678 static const char *directory
= "/pub";
2679 static const char *filename
= "welcome.msg";
2681 static const char *directory
= "/etc";
2682 static const char *filename
= "issue";
2685 static bool TestFtpConnect()
2687 puts("*** Testing FTP connect ***");
2689 #ifdef FTP_ANONYMOUS
2690 static const char *hostname
= "ftp.wxwindows.org";
2692 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2693 #else // !FTP_ANONYMOUS
2694 static const char *hostname
= "localhost";
2697 fgets(user
, WXSIZEOF(user
), stdin
);
2698 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2702 printf("Password for %s: ", password
);
2703 fgets(password
, WXSIZEOF(password
), stdin
);
2704 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2705 ftp
.SetPassword(password
);
2707 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2708 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2710 if ( !ftp
.Connect(hostname
) )
2712 printf("ERROR: failed to connect to %s\n", hostname
);
2718 printf("--- Connected to %s, current directory is '%s'\n",
2719 hostname
, ftp
.Pwd().c_str());
2725 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2726 static void TestFtpWuFtpd()
2729 static const char *hostname
= "ftp.eudora.com";
2730 if ( !ftp
.Connect(hostname
) )
2732 printf("ERROR: failed to connect to %s\n", hostname
);
2736 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2737 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2740 printf("ERROR: couldn't get input stream for %s\n", filename
);
2744 size_t size
= in
->StreamSize();
2745 printf("Reading file %s (%u bytes)...", filename
, size
);
2747 char *data
= new char[size
];
2748 if ( !in
->Read(data
, size
) )
2750 puts("ERROR: read error");
2754 printf("Successfully retrieved the file.\n");
2763 static void TestFtpList()
2765 puts("*** Testing wxFTP file listing ***\n");
2768 if ( !ftp
.ChDir(directory
) )
2770 printf("ERROR: failed to cd to %s\n", directory
);
2773 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2775 // test NLIST and LIST
2776 wxArrayString files
;
2777 if ( !ftp
.GetFilesList(files
) )
2779 puts("ERROR: failed to get NLIST of files");
2783 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2784 size_t count
= files
.GetCount();
2785 for ( size_t n
= 0; n
< count
; n
++ )
2787 printf("\t%s\n", files
[n
].c_str());
2789 puts("End of the file list");
2792 if ( !ftp
.GetDirList(files
) )
2794 puts("ERROR: failed to get LIST of files");
2798 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2799 size_t count
= files
.GetCount();
2800 for ( size_t n
= 0; n
< count
; n
++ )
2802 printf("\t%s\n", files
[n
].c_str());
2804 puts("End of the file list");
2807 if ( !ftp
.ChDir(_T("..")) )
2809 puts("ERROR: failed to cd to ..");
2812 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2815 static void TestFtpDownload()
2817 puts("*** Testing wxFTP download ***\n");
2820 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2823 printf("ERROR: couldn't get input stream for %s\n", filename
);
2827 size_t size
= in
->StreamSize();
2828 printf("Reading file %s (%u bytes)...", filename
, size
);
2831 char *data
= new char[size
];
2832 if ( !in
->Read(data
, size
) )
2834 puts("ERROR: read error");
2838 printf("\nContents of %s:\n%s\n", filename
, data
);
2846 static void TestFtpFileSize()
2848 puts("*** Testing FTP SIZE command ***");
2850 if ( !ftp
.ChDir(directory
) )
2852 printf("ERROR: failed to cd to %s\n", directory
);
2855 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2857 if ( ftp
.FileExists(filename
) )
2859 int size
= ftp
.GetFileSize(filename
);
2861 printf("ERROR: couldn't get size of '%s'\n", filename
);
2863 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2867 printf("ERROR: '%s' doesn't exist\n", filename
);
2871 static void TestFtpMisc()
2873 puts("*** Testing miscellaneous wxFTP functions ***");
2875 if ( ftp
.SendCommand("STAT") != '2' )
2877 puts("ERROR: STAT failed");
2881 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2884 if ( ftp
.SendCommand("HELP SITE") != '2' )
2886 puts("ERROR: HELP SITE failed");
2890 printf("The list of site-specific commands:\n\n%s\n",
2891 ftp
.GetLastResult().c_str());
2895 static void TestFtpInteractive()
2897 puts("\n*** Interactive wxFTP test ***");
2903 printf("Enter FTP command: ");
2904 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2907 // kill the last '\n'
2908 buf
[strlen(buf
) - 1] = 0;
2910 // special handling of LIST and NLST as they require data connection
2911 wxString
start(buf
, 4);
2913 if ( start
== "LIST" || start
== "NLST" )
2916 if ( strlen(buf
) > 4 )
2919 wxArrayString files
;
2920 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2922 printf("ERROR: failed to get %s of files\n", start
.c_str());
2926 printf("--- %s of '%s' under '%s':\n",
2927 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2928 size_t count
= files
.GetCount();
2929 for ( size_t n
= 0; n
< count
; n
++ )
2931 printf("\t%s\n", files
[n
].c_str());
2933 puts("--- End of the file list");
2938 char ch
= ftp
.SendCommand(buf
);
2939 printf("Command %s", ch
? "succeeded" : "failed");
2942 printf(" (return code %c)", ch
);
2945 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2949 puts("\n*** done ***");
2952 static void TestFtpUpload()
2954 puts("*** Testing wxFTP uploading ***\n");
2957 static const char *file1
= "test1";
2958 static const char *file2
= "test2";
2959 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2962 printf("--- Uploading to %s ---\n", file1
);
2963 out
->Write("First hello", 11);
2967 // send a command to check the remote file
2968 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2970 printf("ERROR: STAT %s failed\n", file1
);
2974 printf("STAT %s returned:\n\n%s\n",
2975 file1
, ftp
.GetLastResult().c_str());
2978 out
= ftp
.GetOutputStream(file2
);
2981 printf("--- Uploading to %s ---\n", file1
);
2982 out
->Write("Second hello", 12);
2989 // ----------------------------------------------------------------------------
2991 // ----------------------------------------------------------------------------
2995 #include "wx/wfstream.h"
2996 #include "wx/mstream.h"
2998 static void TestFileStream()
3000 puts("*** Testing wxFileInputStream ***");
3002 static const wxChar
*filename
= _T("testdata.fs");
3004 wxFileOutputStream
fsOut(filename
);
3005 fsOut
.Write("foo", 3);
3008 wxFileInputStream
fsIn(filename
);
3009 printf("File stream size: %u\n", fsIn
.GetSize());
3010 while ( !fsIn
.Eof() )
3012 putchar(fsIn
.GetC());
3015 if ( !wxRemoveFile(filename
) )
3017 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3020 puts("\n*** wxFileInputStream test done ***");
3023 static void TestMemoryStream()
3025 puts("*** Testing wxMemoryInputStream ***");
3028 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3030 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3031 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3032 while ( !memInpStream
.Eof() )
3034 putchar(memInpStream
.GetC());
3037 puts("\n*** wxMemoryInputStream test done ***");
3040 #endif // TEST_STREAMS
3042 // ----------------------------------------------------------------------------
3044 // ----------------------------------------------------------------------------
3048 #include "wx/timer.h"
3049 #include "wx/utils.h"
3051 static void TestStopWatch()
3053 puts("*** Testing wxStopWatch ***\n");
3057 printf("Initially paused, after 2 seconds time is...");
3060 printf("\t%ldms\n", sw
.Time());
3062 printf("Resuming stopwatch and sleeping 3 seconds...");
3066 printf("\telapsed time: %ldms\n", sw
.Time());
3069 printf("Pausing agan and sleeping 2 more seconds...");
3072 printf("\telapsed time: %ldms\n", sw
.Time());
3075 printf("Finally resuming and sleeping 2 more seconds...");
3078 printf("\telapsed time: %ldms\n", sw
.Time());
3081 puts("\nChecking for 'backwards clock' bug...");
3082 for ( size_t n
= 0; n
< 70; n
++ )
3086 for ( size_t m
= 0; m
< 100000; m
++ )
3088 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3090 puts("\ntime is negative - ERROR!");
3101 #endif // TEST_TIMER
3103 // ----------------------------------------------------------------------------
3105 // ----------------------------------------------------------------------------
3109 #include "wx/vcard.h"
3111 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3114 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3118 wxString(_T('\t'), level
).c_str(),
3119 vcObj
->GetName().c_str());
3122 switch ( vcObj
->GetType() )
3124 case wxVCardObject::String
:
3125 case wxVCardObject::UString
:
3128 vcObj
->GetValue(&val
);
3129 value
<< _T('"') << val
<< _T('"');
3133 case wxVCardObject::Int
:
3136 vcObj
->GetValue(&i
);
3137 value
.Printf(_T("%u"), i
);
3141 case wxVCardObject::Long
:
3144 vcObj
->GetValue(&l
);
3145 value
.Printf(_T("%lu"), l
);
3149 case wxVCardObject::None
:
3152 case wxVCardObject::Object
:
3153 value
= _T("<node>");
3157 value
= _T("<unknown value type>");
3161 printf(" = %s", value
.c_str());
3164 DumpVObject(level
+ 1, *vcObj
);
3167 vcObj
= vcard
.GetNextProp(&cookie
);
3171 static void DumpVCardAddresses(const wxVCard
& vcard
)
3173 puts("\nShowing all addresses from vCard:\n");
3177 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3181 int flags
= addr
->GetFlags();
3182 if ( flags
& wxVCardAddress::Domestic
)
3184 flagsStr
<< _T("domestic ");
3186 if ( flags
& wxVCardAddress::Intl
)
3188 flagsStr
<< _T("international ");
3190 if ( flags
& wxVCardAddress::Postal
)
3192 flagsStr
<< _T("postal ");
3194 if ( flags
& wxVCardAddress::Parcel
)
3196 flagsStr
<< _T("parcel ");
3198 if ( flags
& wxVCardAddress::Home
)
3200 flagsStr
<< _T("home ");
3202 if ( flags
& wxVCardAddress::Work
)
3204 flagsStr
<< _T("work ");
3207 printf("Address %u:\n"
3209 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3212 addr
->GetPostOffice().c_str(),
3213 addr
->GetExtAddress().c_str(),
3214 addr
->GetStreet().c_str(),
3215 addr
->GetLocality().c_str(),
3216 addr
->GetRegion().c_str(),
3217 addr
->GetPostalCode().c_str(),
3218 addr
->GetCountry().c_str()
3222 addr
= vcard
.GetNextAddress(&cookie
);
3226 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3228 puts("\nShowing all phone numbers from vCard:\n");
3232 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3236 int flags
= phone
->GetFlags();
3237 if ( flags
& wxVCardPhoneNumber::Voice
)
3239 flagsStr
<< _T("voice ");
3241 if ( flags
& wxVCardPhoneNumber::Fax
)
3243 flagsStr
<< _T("fax ");
3245 if ( flags
& wxVCardPhoneNumber::Cellular
)
3247 flagsStr
<< _T("cellular ");
3249 if ( flags
& wxVCardPhoneNumber::Modem
)
3251 flagsStr
<< _T("modem ");
3253 if ( flags
& wxVCardPhoneNumber::Home
)
3255 flagsStr
<< _T("home ");
3257 if ( flags
& wxVCardPhoneNumber::Work
)
3259 flagsStr
<< _T("work ");
3262 printf("Phone number %u:\n"
3267 phone
->GetNumber().c_str()
3271 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3275 static void TestVCardRead()
3277 puts("*** Testing wxVCard reading ***\n");
3279 wxVCard
vcard(_T("vcard.vcf"));
3280 if ( !vcard
.IsOk() )
3282 puts("ERROR: couldn't load vCard.");
3286 // read individual vCard properties
3287 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3291 vcObj
->GetValue(&value
);
3296 value
= _T("<none>");
3299 printf("Full name retrieved directly: %s\n", value
.c_str());
3302 if ( !vcard
.GetFullName(&value
) )
3304 value
= _T("<none>");
3307 printf("Full name from wxVCard API: %s\n", value
.c_str());
3309 // now show how to deal with multiply occuring properties
3310 DumpVCardAddresses(vcard
);
3311 DumpVCardPhoneNumbers(vcard
);
3313 // and finally show all
3314 puts("\nNow dumping the entire vCard:\n"
3315 "-----------------------------\n");
3317 DumpVObject(0, vcard
);
3321 static void TestVCardWrite()
3323 puts("*** Testing wxVCard writing ***\n");
3326 if ( !vcard
.IsOk() )
3328 puts("ERROR: couldn't create vCard.");
3333 vcard
.SetName("Zeitlin", "Vadim");
3334 vcard
.SetFullName("Vadim Zeitlin");
3335 vcard
.SetOrganization("wxWindows", "R&D");
3337 // just dump the vCard back
3338 puts("Entire vCard follows:\n");
3339 puts(vcard
.Write());
3343 #endif // TEST_VCARD
3345 // ----------------------------------------------------------------------------
3347 // ----------------------------------------------------------------------------
3355 #include "wx/volume.h"
3357 static const wxChar
*volumeKinds
[] =
3363 _T("network volume"),
3367 static void TestFSVolume()
3369 wxPuts(_T("*** Testing wxFSVolume class ***"));
3371 wxArrayString volumes
= wxFSVolume::GetVolumes();
3372 size_t count
= volumes
.GetCount();
3376 wxPuts(_T("ERROR: no mounted volumes?"));
3380 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3382 for ( size_t n
= 0; n
< count
; n
++ )
3384 wxFSVolume
vol(volumes
[n
]);
3387 wxPuts(_T("ERROR: couldn't create volume"));
3391 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3393 vol
.GetDisplayName().c_str(),
3394 vol
.GetName().c_str(),
3395 volumeKinds
[vol
.GetKind()],
3396 vol
.IsWritable() ? _T("rw") : _T("ro"),
3397 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3402 #endif // TEST_VOLUME
3404 // ----------------------------------------------------------------------------
3405 // wide char (Unicode) support
3406 // ----------------------------------------------------------------------------
3410 #include "wx/strconv.h"
3411 #include "wx/fontenc.h"
3412 #include "wx/encconv.h"
3413 #include "wx/buffer.h"
3415 static const char textInUtf8
[] =
3417 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3418 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3419 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3420 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3421 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3422 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3423 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3426 static void TestUtf8()
3428 puts("*** Testing UTF8 support ***\n");
3432 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3434 puts("ERROR: UTF-8 decoding failed.");
3438 wxCSConv
conv(_T("koi8-r"));
3439 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3441 puts("ERROR: conversion to KOI8-R failed.");
3445 printf("The resulting string (in KOI8-R): %s\n", buf
);
3449 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3451 puts("ERROR: conversion to UTF-8 failed.");
3455 printf("The string in UTF-8: %s\n", buf
);
3461 static void TestEncodingConverter()
3463 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3465 // using wxEncodingConverter should give the same result as above
3468 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3470 puts("ERROR: UTF-8 decoding failed.");
3474 wxEncodingConverter ec
;
3475 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3476 ec
.Convert(wbuf
, buf
);
3477 printf("The same string obtained using wxEC: %s\n", buf
);
3483 #endif // TEST_WCHAR
3485 // ----------------------------------------------------------------------------
3487 // ----------------------------------------------------------------------------
3491 #include "wx/filesys.h"
3492 #include "wx/fs_zip.h"
3493 #include "wx/zipstrm.h"
3495 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3497 static void TestZipStreamRead()
3499 puts("*** Testing ZIP reading ***\n");
3501 static const wxChar
*filename
= _T("foo");
3502 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3503 printf("Archive size: %u\n", istr
.GetSize());
3505 printf("Dumping the file '%s':\n", filename
);
3506 while ( !istr
.Eof() )
3508 putchar(istr
.GetC());
3512 puts("\n----- done ------");
3515 static void DumpZipDirectory(wxFileSystem
& fs
,
3516 const wxString
& dir
,
3517 const wxString
& indent
)
3519 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3520 TESTFILE_ZIP
, dir
.c_str());
3521 wxString wildcard
= prefix
+ _T("/*");
3523 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3524 while ( !dirname
.empty() )
3526 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3528 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3533 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3535 DumpZipDirectory(fs
, dirname
,
3536 indent
+ wxString(_T(' '), 4));
3538 dirname
= fs
.FindNext();
3541 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3542 while ( !filename
.empty() )
3544 if ( !filename
.StartsWith(prefix
, &filename
) )
3546 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3551 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3553 filename
= fs
.FindNext();
3557 static void TestZipFileSystem()
3559 puts("*** Testing ZIP file system ***\n");
3561 wxFileSystem::AddHandler(new wxZipFSHandler
);
3563 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3565 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3570 // ----------------------------------------------------------------------------
3572 // ----------------------------------------------------------------------------
3576 #include "wx/zstream.h"
3577 #include "wx/wfstream.h"
3579 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3580 static const char *TEST_DATA
= "hello and hello again";
3582 static void TestZlibStreamWrite()
3584 puts("*** Testing Zlib stream reading ***\n");
3586 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3587 wxZlibOutputStream
ostr(fileOutStream
, 0);
3588 printf("Compressing the test string... ");
3589 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3592 puts("(ERROR: failed)");
3599 puts("\n----- done ------");
3602 static void TestZlibStreamRead()
3604 puts("*** Testing Zlib stream reading ***\n");
3606 wxFileInputStream
fileInStream(FILENAME_GZ
);
3607 wxZlibInputStream
istr(fileInStream
);
3608 printf("Archive size: %u\n", istr
.GetSize());
3610 puts("Dumping the file:");
3611 while ( !istr
.Eof() )
3613 putchar(istr
.GetC());
3617 puts("\n----- done ------");
3622 // ----------------------------------------------------------------------------
3624 // ----------------------------------------------------------------------------
3626 #ifdef TEST_DATETIME
3630 #include "wx/date.h"
3631 #include "wx/datetime.h"
3636 wxDateTime::wxDateTime_t day
;
3637 wxDateTime::Month month
;
3639 wxDateTime::wxDateTime_t hour
, min
, sec
;
3641 wxDateTime::WeekDay wday
;
3642 time_t gmticks
, ticks
;
3644 void Init(const wxDateTime::Tm
& tm
)
3653 gmticks
= ticks
= -1;
3656 wxDateTime
DT() const
3657 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3659 bool SameDay(const wxDateTime::Tm
& tm
) const
3661 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3664 wxString
Format() const
3667 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3669 wxDateTime::GetMonthName(month
).c_str(),
3671 abs(wxDateTime::ConvertYearToBC(year
)),
3672 year
> 0 ? "AD" : "BC");
3676 wxString
FormatDate() const
3679 s
.Printf("%02d-%s-%4d%s",
3681 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3682 abs(wxDateTime::ConvertYearToBC(year
)),
3683 year
> 0 ? "AD" : "BC");
3688 static const Date testDates
[] =
3690 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3691 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3692 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3693 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3694 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3695 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3696 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3697 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3698 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3699 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3700 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3701 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3702 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3703 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3704 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3707 // this test miscellaneous static wxDateTime functions
3708 static void TestTimeStatic()
3710 puts("\n*** wxDateTime static methods test ***");
3712 // some info about the current date
3713 int year
= wxDateTime::GetCurrentYear();
3714 printf("Current year %d is %sa leap one and has %d days.\n",
3716 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3717 wxDateTime::GetNumberOfDays(year
));
3719 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3720 printf("Current month is '%s' ('%s') and it has %d days\n",
3721 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3722 wxDateTime::GetMonthName(month
).c_str(),
3723 wxDateTime::GetNumberOfDays(month
));
3726 static const size_t nYears
= 5;
3727 static const size_t years
[2][nYears
] =
3729 // first line: the years to test
3730 { 1990, 1976, 2000, 2030, 1984, },
3732 // second line: TRUE if leap, FALSE otherwise
3733 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3736 for ( size_t n
= 0; n
< nYears
; n
++ )
3738 int year
= years
[0][n
];
3739 bool should
= years
[1][n
] != 0,
3740 is
= wxDateTime::IsLeapYear(year
);
3742 printf("Year %d is %sa leap year (%s)\n",
3745 should
== is
? "ok" : "ERROR");
3747 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3751 // test constructing wxDateTime objects
3752 static void TestTimeSet()
3754 puts("\n*** wxDateTime construction test ***");
3756 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3758 const Date
& d1
= testDates
[n
];
3759 wxDateTime dt
= d1
.DT();
3762 d2
.Init(dt
.GetTm());
3764 wxString s1
= d1
.Format(),
3767 printf("Date: %s == %s (%s)\n",
3768 s1
.c_str(), s2
.c_str(),
3769 s1
== s2
? "ok" : "ERROR");
3773 // test time zones stuff
3774 static void TestTimeZones()
3776 puts("\n*** wxDateTime timezone test ***");
3778 wxDateTime now
= wxDateTime::Now();
3780 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3781 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3782 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3783 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3784 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3785 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3787 wxDateTime::Tm tm
= now
.GetTm();
3788 if ( wxDateTime(tm
) != now
)
3790 printf("ERROR: got %s instead of %s\n",
3791 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3795 // test some minimal support for the dates outside the standard range
3796 static void TestTimeRange()
3798 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3800 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3802 printf("Unix epoch:\t%s\n",
3803 wxDateTime(2440587.5).Format(fmt
).c_str());
3804 printf("Feb 29, 0: \t%s\n",
3805 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3806 printf("JDN 0: \t%s\n",
3807 wxDateTime(0.0).Format(fmt
).c_str());
3808 printf("Jan 1, 1AD:\t%s\n",
3809 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3810 printf("May 29, 2099:\t%s\n",
3811 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3814 static void TestTimeTicks()
3816 puts("\n*** wxDateTime ticks test ***");
3818 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3820 const Date
& d
= testDates
[n
];
3821 if ( d
.ticks
== -1 )
3824 wxDateTime dt
= d
.DT();
3825 long ticks
= (dt
.GetValue() / 1000).ToLong();
3826 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3827 if ( ticks
== d
.ticks
)
3833 printf(" (ERROR: should be %ld, delta = %ld)\n",
3834 d
.ticks
, ticks
- d
.ticks
);
3837 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3838 ticks
= (dt
.GetValue() / 1000).ToLong();
3839 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3840 if ( ticks
== d
.gmticks
)
3846 printf(" (ERROR: should be %ld, delta = %ld)\n",
3847 d
.gmticks
, ticks
- d
.gmticks
);
3854 // test conversions to JDN &c
3855 static void TestTimeJDN()
3857 puts("\n*** wxDateTime to JDN test ***");
3859 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3861 const Date
& d
= testDates
[n
];
3862 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3863 double jdn
= dt
.GetJulianDayNumber();
3865 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3872 printf(" (ERROR: should be %f, delta = %f)\n",
3873 d
.jdn
, jdn
- d
.jdn
);
3878 // test week days computation
3879 static void TestTimeWDays()
3881 puts("\n*** wxDateTime weekday test ***");
3883 // test GetWeekDay()
3885 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3887 const Date
& d
= testDates
[n
];
3888 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3890 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3893 wxDateTime::GetWeekDayName(wday
).c_str());
3894 if ( wday
== d
.wday
)
3900 printf(" (ERROR: should be %s)\n",
3901 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3907 // test SetToWeekDay()
3908 struct WeekDateTestData
3910 Date date
; // the real date (precomputed)
3911 int nWeek
; // its week index in the month
3912 wxDateTime::WeekDay wday
; // the weekday
3913 wxDateTime::Month month
; // the month
3914 int year
; // and the year
3916 wxString
Format() const
3919 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3921 case 1: which
= "first"; break;
3922 case 2: which
= "second"; break;
3923 case 3: which
= "third"; break;
3924 case 4: which
= "fourth"; break;
3925 case 5: which
= "fifth"; break;
3927 case -1: which
= "last"; break;
3932 which
+= " from end";
3935 s
.Printf("The %s %s of %s in %d",
3937 wxDateTime::GetWeekDayName(wday
).c_str(),
3938 wxDateTime::GetMonthName(month
).c_str(),
3945 // the array data was generated by the following python program
3947 from DateTime import *
3948 from whrandom import *
3949 from string import *
3951 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3952 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3954 week = DateTimeDelta(7)
3957 year = randint(1900, 2100)
3958 month = randint(1, 12)
3959 day = randint(1, 28)
3960 dt = DateTime(year, month, day)
3961 wday = dt.day_of_week
3963 countFromEnd = choice([-1, 1])
3966 while dt.month is month:
3967 dt = dt - countFromEnd * week
3968 weekNum = weekNum + countFromEnd
3970 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3972 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3973 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3976 static const WeekDateTestData weekDatesTestData
[] =
3978 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3979 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3980 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3981 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3982 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3983 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3984 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3985 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3986 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3987 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3988 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3989 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3990 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3991 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3992 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3993 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3994 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3995 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3996 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3997 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4000 static const char *fmt
= "%d-%b-%Y";
4003 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4005 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4007 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4009 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4011 const Date
& d
= wd
.date
;
4012 if ( d
.SameDay(dt
.GetTm()) )
4018 dt
.Set(d
.day
, d
.month
, d
.year
);
4020 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4025 // test the computation of (ISO) week numbers
4026 static void TestTimeWNumber()
4028 puts("\n*** wxDateTime week number test ***");
4030 struct WeekNumberTestData
4032 Date date
; // the date
4033 wxDateTime::wxDateTime_t week
; // the week number in the year
4034 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4035 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4036 wxDateTime::wxDateTime_t dnum
; // day number in the year
4039 // data generated with the following python script:
4041 from DateTime import *
4042 from whrandom import *
4043 from string import *
4045 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4046 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4048 def GetMonthWeek(dt):
4049 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4050 if weekNumMonth < 0:
4051 weekNumMonth = weekNumMonth + 53
4054 def GetLastSundayBefore(dt):
4055 if dt.iso_week[2] == 7:
4058 return dt - DateTimeDelta(dt.iso_week[2])
4061 year = randint(1900, 2100)
4062 month = randint(1, 12)
4063 day = randint(1, 28)
4064 dt = DateTime(year, month, day)
4065 dayNum = dt.day_of_year
4066 weekNum = dt.iso_week[1]
4067 weekNumMonth = GetMonthWeek(dt)
4070 dtSunday = GetLastSundayBefore(dt)
4072 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4073 weekNumMonth2 = weekNumMonth2 + 1
4074 dtSunday = dtSunday - DateTimeDelta(7)
4076 data = { 'day': rjust(`day`, 2), \
4077 'month': monthNames[month - 1], \
4079 'weekNum': rjust(`weekNum`, 2), \
4080 'weekNumMonth': weekNumMonth, \
4081 'weekNumMonth2': weekNumMonth2, \
4082 'dayNum': rjust(`dayNum`, 3) }
4084 print " { { %(day)s, "\
4085 "wxDateTime::%(month)s, "\
4088 "%(weekNumMonth)s, "\
4089 "%(weekNumMonth2)s, "\
4090 "%(dayNum)s }," % data
4093 static const WeekNumberTestData weekNumberTestDates
[] =
4095 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4096 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4097 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4098 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4099 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4100 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4101 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4102 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4103 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4104 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4105 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4106 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4107 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4108 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4109 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4110 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4111 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4112 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4113 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4114 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4117 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4119 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4120 const Date
& d
= wn
.date
;
4122 wxDateTime dt
= d
.DT();
4124 wxDateTime::wxDateTime_t
4125 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4126 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4127 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4128 dnum
= dt
.GetDayOfYear();
4130 printf("%s: the day number is %d",
4131 d
.FormatDate().c_str(), dnum
);
4132 if ( dnum
== wn
.dnum
)
4138 printf(" (ERROR: should be %d)", wn
.dnum
);
4141 printf(", week in month is %d", wmon
);
4142 if ( wmon
== wn
.wmon
)
4148 printf(" (ERROR: should be %d)", wn
.wmon
);
4151 printf(" or %d", wmon2
);
4152 if ( wmon2
== wn
.wmon2
)
4158 printf(" (ERROR: should be %d)", wn
.wmon2
);
4161 printf(", week in year is %d", week
);
4162 if ( week
== wn
.week
)
4168 printf(" (ERROR: should be %d)\n", wn
.week
);
4173 // test DST calculations
4174 static void TestTimeDST()
4176 puts("\n*** wxDateTime DST test ***");
4178 printf("DST is%s in effect now.\n\n",
4179 wxDateTime::Now().IsDST() ? "" : " not");
4181 // taken from http://www.energy.ca.gov/daylightsaving.html
4182 static const Date datesDST
[2][2004 - 1900 + 1] =
4185 { 1, wxDateTime::Apr
, 1990 },
4186 { 7, wxDateTime::Apr
, 1991 },
4187 { 5, wxDateTime::Apr
, 1992 },
4188 { 4, wxDateTime::Apr
, 1993 },
4189 { 3, wxDateTime::Apr
, 1994 },
4190 { 2, wxDateTime::Apr
, 1995 },
4191 { 7, wxDateTime::Apr
, 1996 },
4192 { 6, wxDateTime::Apr
, 1997 },
4193 { 5, wxDateTime::Apr
, 1998 },
4194 { 4, wxDateTime::Apr
, 1999 },
4195 { 2, wxDateTime::Apr
, 2000 },
4196 { 1, wxDateTime::Apr
, 2001 },
4197 { 7, wxDateTime::Apr
, 2002 },
4198 { 6, wxDateTime::Apr
, 2003 },
4199 { 4, wxDateTime::Apr
, 2004 },
4202 { 28, wxDateTime::Oct
, 1990 },
4203 { 27, wxDateTime::Oct
, 1991 },
4204 { 25, wxDateTime::Oct
, 1992 },
4205 { 31, wxDateTime::Oct
, 1993 },
4206 { 30, wxDateTime::Oct
, 1994 },
4207 { 29, wxDateTime::Oct
, 1995 },
4208 { 27, wxDateTime::Oct
, 1996 },
4209 { 26, wxDateTime::Oct
, 1997 },
4210 { 25, wxDateTime::Oct
, 1998 },
4211 { 31, wxDateTime::Oct
, 1999 },
4212 { 29, wxDateTime::Oct
, 2000 },
4213 { 28, wxDateTime::Oct
, 2001 },
4214 { 27, wxDateTime::Oct
, 2002 },
4215 { 26, wxDateTime::Oct
, 2003 },
4216 { 31, wxDateTime::Oct
, 2004 },
4221 for ( year
= 1990; year
< 2005; year
++ )
4223 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4224 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4226 printf("DST period in the US for year %d: from %s to %s",
4227 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4229 size_t n
= year
- 1990;
4230 const Date
& dBegin
= datesDST
[0][n
];
4231 const Date
& dEnd
= datesDST
[1][n
];
4233 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4239 printf(" (ERROR: should be %s %d to %s %d)\n",
4240 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4241 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4247 for ( year
= 1990; year
< 2005; year
++ )
4249 printf("DST period in Europe for year %d: from %s to %s\n",
4251 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4252 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4256 // test wxDateTime -> text conversion
4257 static void TestTimeFormat()
4259 puts("\n*** wxDateTime formatting test ***");
4261 // some information may be lost during conversion, so store what kind
4262 // of info should we recover after a round trip
4265 CompareNone
, // don't try comparing
4266 CompareBoth
, // dates and times should be identical
4267 CompareDate
, // dates only
4268 CompareTime
// time only
4273 CompareKind compareKind
;
4275 } formatTestFormats
[] =
4277 { CompareBoth
, "---> %c" },
4278 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4279 { CompareBoth
, "Date is %x, time is %X" },
4280 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4281 { CompareNone
, "The day of year: %j, the week of year: %W" },
4282 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4285 static const Date formatTestDates
[] =
4287 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4288 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4290 // this test can't work for other centuries because it uses two digit
4291 // years in formats, so don't even try it
4292 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4293 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4294 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4298 // an extra test (as it doesn't depend on date, don't do it in the loop)
4299 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4301 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4305 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4306 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4308 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4309 printf("%s", s
.c_str());
4311 // what can we recover?
4312 int kind
= formatTestFormats
[n
].compareKind
;
4316 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4319 // converion failed - should it have?
4320 if ( kind
== CompareNone
)
4323 puts(" (ERROR: conversion back failed)");
4327 // should have parsed the entire string
4328 puts(" (ERROR: conversion back stopped too soon)");
4332 bool equal
= FALSE
; // suppress compilaer warning
4340 equal
= dt
.IsSameDate(dt2
);
4344 equal
= dt
.IsSameTime(dt2
);
4350 printf(" (ERROR: got back '%s' instead of '%s')\n",
4351 dt2
.Format().c_str(), dt
.Format().c_str());
4362 // test text -> wxDateTime conversion
4363 static void TestTimeParse()
4365 puts("\n*** wxDateTime parse test ***");
4367 struct ParseTestData
4374 static const ParseTestData parseTestDates
[] =
4376 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4377 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4380 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4382 const char *format
= parseTestDates
[n
].format
;
4384 printf("%s => ", format
);
4387 if ( dt
.ParseRfc822Date(format
) )
4389 printf("%s ", dt
.Format().c_str());
4391 if ( parseTestDates
[n
].good
)
4393 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4400 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4405 puts("(ERROR: bad format)");
4410 printf("bad format (%s)\n",
4411 parseTestDates
[n
].good
? "ERROR" : "ok");
4416 static void TestDateTimeInteractive()
4418 puts("\n*** interactive wxDateTime tests ***");
4424 printf("Enter a date: ");
4425 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4428 // kill the last '\n'
4429 buf
[strlen(buf
) - 1] = 0;
4432 const char *p
= dt
.ParseDate(buf
);
4435 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4441 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4444 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4445 dt
.Format("%b %d, %Y").c_str(),
4447 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4448 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4449 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4452 puts("\n*** done ***");
4455 static void TestTimeMS()
4457 puts("*** testing millisecond-resolution support in wxDateTime ***");
4459 wxDateTime dt1
= wxDateTime::Now(),
4460 dt2
= wxDateTime::UNow();
4462 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4463 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4464 printf("Dummy loop: ");
4465 for ( int i
= 0; i
< 6000; i
++ )
4467 //for ( int j = 0; j < 10; j++ )
4470 s
.Printf("%g", sqrt(i
));
4479 dt2
= wxDateTime::UNow();
4480 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4482 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4484 puts("\n*** done ***");
4487 static void TestTimeArithmetics()
4489 puts("\n*** testing arithmetic operations on wxDateTime ***");
4491 static const struct ArithmData
4493 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4494 : span(sp
), name(nam
) { }
4498 } testArithmData
[] =
4500 ArithmData(wxDateSpan::Day(), "day"),
4501 ArithmData(wxDateSpan::Week(), "week"),
4502 ArithmData(wxDateSpan::Month(), "month"),
4503 ArithmData(wxDateSpan::Year(), "year"),
4504 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4507 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4509 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4511 wxDateSpan span
= testArithmData
[n
].span
;
4515 const char *name
= testArithmData
[n
].name
;
4516 printf("%s + %s = %s, %s - %s = %s\n",
4517 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4518 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4520 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4521 if ( dt1
- span
== dt
)
4527 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4530 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4531 if ( dt2
+ span
== dt
)
4537 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4540 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4541 if ( dt2
+ 2*span
== dt1
)
4547 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4554 static void TestTimeHolidays()
4556 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4558 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4559 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4560 dtEnd
= dtStart
.GetLastMonthDay();
4562 wxDateTimeArray hol
;
4563 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4565 const wxChar
*format
= "%d-%b-%Y (%a)";
4567 printf("All holidays between %s and %s:\n",
4568 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4570 size_t count
= hol
.GetCount();
4571 for ( size_t n
= 0; n
< count
; n
++ )
4573 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4579 static void TestTimeZoneBug()
4581 puts("\n*** testing for DST/timezone bug ***\n");
4583 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4584 for ( int i
= 0; i
< 31; i
++ )
4586 printf("Date %s: week day %s.\n",
4587 date
.Format(_T("%d-%m-%Y")).c_str(),
4588 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4590 date
+= wxDateSpan::Day();
4596 static void TestTimeSpanFormat()
4598 puts("\n*** wxTimeSpan tests ***");
4600 static const char *formats
[] =
4602 _T("(default) %H:%M:%S"),
4603 _T("%E weeks and %D days"),
4604 _T("%l milliseconds"),
4605 _T("(with ms) %H:%M:%S:%l"),
4606 _T("100%% of minutes is %M"), // test "%%"
4607 _T("%D days and %H hours"),
4608 _T("or also %S seconds"),
4611 wxTimeSpan
ts1(1, 2, 3, 4),
4613 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4615 printf("ts1 = %s\tts2 = %s\n",
4616 ts1
.Format(formats
[n
]).c_str(),
4617 ts2
.Format(formats
[n
]).c_str());
4625 // test compatibility with the old wxDate/wxTime classes
4626 static void TestTimeCompatibility()
4628 puts("\n*** wxDateTime compatibility test ***");
4630 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4631 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4633 double jdnNow
= wxDateTime::Now().GetJDN();
4634 long jdnMidnight
= (long)(jdnNow
- 0.5);
4635 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4637 jdnMidnight
= wxDate().Set().GetJulianDate();
4638 printf("wxDateTime for today: %s\n",
4639 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4641 int flags
= wxEUROPEAN
;//wxFULL;
4644 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4645 for ( int n
= 0; n
< 7; n
++ )
4647 printf("Previous %s is %s\n",
4648 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4649 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4655 #endif // TEST_DATETIME
4657 // ----------------------------------------------------------------------------
4659 // ----------------------------------------------------------------------------
4663 #include "wx/thread.h"
4665 static size_t gs_counter
= (size_t)-1;
4666 static wxCriticalSection gs_critsect
;
4667 static wxSemaphore gs_cond
;
4669 class MyJoinableThread
: public wxThread
4672 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4673 { m_n
= n
; Create(); }
4675 // thread execution starts here
4676 virtual ExitCode
Entry();
4682 wxThread::ExitCode
MyJoinableThread::Entry()
4684 unsigned long res
= 1;
4685 for ( size_t n
= 1; n
< m_n
; n
++ )
4689 // it's a loooong calculation :-)
4693 return (ExitCode
)res
;
4696 class MyDetachedThread
: public wxThread
4699 MyDetachedThread(size_t n
, char ch
)
4703 m_cancelled
= FALSE
;
4708 // thread execution starts here
4709 virtual ExitCode
Entry();
4712 virtual void OnExit();
4715 size_t m_n
; // number of characters to write
4716 char m_ch
; // character to write
4718 bool m_cancelled
; // FALSE if we exit normally
4721 wxThread::ExitCode
MyDetachedThread::Entry()
4724 wxCriticalSectionLocker
lock(gs_critsect
);
4725 if ( gs_counter
== (size_t)-1 )
4731 for ( size_t n
= 0; n
< m_n
; n
++ )
4733 if ( TestDestroy() )
4743 wxThread::Sleep(100);
4749 void MyDetachedThread::OnExit()
4751 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4753 wxCriticalSectionLocker
lock(gs_critsect
);
4754 if ( !--gs_counter
&& !m_cancelled
)
4758 static void TestDetachedThreads()
4760 puts("\n*** Testing detached threads ***");
4762 static const size_t nThreads
= 3;
4763 MyDetachedThread
*threads
[nThreads
];
4765 for ( n
= 0; n
< nThreads
; n
++ )
4767 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4770 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4771 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4773 for ( n
= 0; n
< nThreads
; n
++ )
4778 // wait until all threads terminate
4784 static void TestJoinableThreads()
4786 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4788 // calc 10! in the background
4789 MyJoinableThread
thread(10);
4792 printf("\nThread terminated with exit code %lu.\n",
4793 (unsigned long)thread
.Wait());
4796 static void TestThreadSuspend()
4798 puts("\n*** Testing thread suspend/resume functions ***");
4800 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4804 // this is for this demo only, in a real life program we'd use another
4805 // condition variable which would be signaled from wxThread::Entry() to
4806 // tell us that the thread really started running - but here just wait a
4807 // bit and hope that it will be enough (the problem is, of course, that
4808 // the thread might still not run when we call Pause() which will result
4810 wxThread::Sleep(300);
4812 for ( size_t n
= 0; n
< 3; n
++ )
4816 puts("\nThread suspended");
4819 // don't sleep but resume immediately the first time
4820 wxThread::Sleep(300);
4822 puts("Going to resume the thread");
4827 puts("Waiting until it terminates now");
4829 // wait until the thread terminates
4835 static void TestThreadDelete()
4837 // As above, using Sleep() is only for testing here - we must use some
4838 // synchronisation object instead to ensure that the thread is still
4839 // running when we delete it - deleting a detached thread which already
4840 // terminated will lead to a crash!
4842 puts("\n*** Testing thread delete function ***");
4844 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4848 puts("\nDeleted a thread which didn't start to run yet.");
4850 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4854 wxThread::Sleep(300);
4858 puts("\nDeleted a running thread.");
4860 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4864 wxThread::Sleep(300);
4870 puts("\nDeleted a sleeping thread.");
4872 MyJoinableThread
thread3(20);
4877 puts("\nDeleted a joinable thread.");
4879 MyJoinableThread
thread4(2);
4882 wxThread::Sleep(300);
4886 puts("\nDeleted a joinable thread which already terminated.");
4891 class MyWaitingThread
: public wxThread
4894 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4897 m_condition
= condition
;
4902 virtual ExitCode
Entry()
4904 printf("Thread %lu has started running.\n", GetId());
4909 printf("Thread %lu starts to wait...\n", GetId());
4913 m_condition
->Wait();
4916 printf("Thread %lu finished to wait, exiting.\n", GetId());
4924 wxCondition
*m_condition
;
4927 static void TestThreadConditions()
4930 wxCondition
condition(mutex
);
4932 // otherwise its difficult to understand which log messages pertain to
4934 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4935 // condition.GetId(), gs_cond.GetId());
4937 // create and launch threads
4938 MyWaitingThread
*threads
[10];
4941 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4943 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4946 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4951 // wait until all threads run
4952 puts("Main thread is waiting for the other threads to start");
4955 size_t nRunning
= 0;
4956 while ( nRunning
< WXSIZEOF(threads
) )
4962 printf("Main thread: %u already running\n", nRunning
);
4966 puts("Main thread: all threads started up.");
4969 wxThread::Sleep(500);
4972 // now wake one of them up
4973 printf("Main thread: about to signal the condition.\n");
4978 wxThread::Sleep(200);
4980 // wake all the (remaining) threads up, so that they can exit
4981 printf("Main thread: about to broadcast the condition.\n");
4983 condition
.Broadcast();
4985 // give them time to terminate (dirty!)
4986 wxThread::Sleep(500);
4989 #include "wx/utils.h"
4991 class MyExecThread
: public wxThread
4994 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5000 virtual ExitCode
Entry()
5002 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5009 static void TestThreadExec()
5011 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5013 MyExecThread
thread(_T("true"));
5016 wxPrintf(_T("Main program exit code: %ld.\n"),
5017 wxExecute(_T("false"), wxEXEC_SYNC
));
5019 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5023 #include "wx/datetime.h"
5025 class MySemaphoreThread
: public wxThread
5028 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5029 : wxThread(wxTHREAD_JOINABLE
),
5036 virtual ExitCode
Entry()
5038 wxPrintf(_T("%s: Thread %d starting to wait for semaphore...\n"),
5039 wxDateTime::Now().FormatTime().c_str(), m_i
);
5043 wxPrintf(_T("%s: Thread %d acquired the semaphore.\n"),
5044 wxDateTime::Now().FormatTime().c_str(), m_i
);
5048 wxPrintf(_T("%s: Thread %d releasing the semaphore.\n"),
5049 wxDateTime::Now().FormatTime().c_str(), m_i
);
5061 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5063 static void TestSemaphore()
5065 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5067 static const int SEM_LIMIT
= 3;
5069 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5070 ArrayThreads threads
;
5072 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5074 threads
.Add(new MySemaphoreThread(i
, &sem
));
5075 threads
.Last()->Run();
5078 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5085 #endif // TEST_THREADS
5087 // ----------------------------------------------------------------------------
5089 // ----------------------------------------------------------------------------
5093 #include "wx/dynarray.h"
5095 typedef unsigned short ushort
;
5097 #define DefineCompare(name, T) \
5099 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5101 return first - second; \
5104 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5106 return *first - *second; \
5109 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5111 return *second - *first; \
5114 DefineCompare(UShort, ushort);
5115 DefineCompare(Int
, int);
5117 // test compilation of all macros
5118 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5119 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5120 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5121 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5123 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5124 #include "wx/arrimpl.cpp"
5125 WX_DEFINE_OBJARRAY(ArrayBars
);
5127 static void PrintArray(const char* name
, const wxArrayString
& array
)
5129 printf("Dump of the array '%s'\n", name
);
5131 size_t nCount
= array
.GetCount();
5132 for ( size_t n
= 0; n
< nCount
; n
++ )
5134 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5138 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5139 const wxString
& second
)
5141 return first
.length() - second
.length();
5144 #define TestArrayOf(name) \
5146 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5148 printf("Dump of the array '%s'\n", name); \
5150 size_t nCount = array.GetCount(); \
5151 for ( size_t n = 0; n < nCount; n++ ) \
5153 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5157 static void PrintArray(const char* name, const wxArray##name & array) \
5159 printf("Dump of the array '%s'\n", name); \
5161 size_t nCount = array.GetCount(); \
5162 for ( size_t n = 0; n < nCount; n++ ) \
5164 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5168 static void TestArrayOf ## name ## s() \
5170 printf("*** Testing wxArray%s ***\n", #name); \
5178 puts("Initially:"); \
5179 PrintArray("a", a); \
5181 puts("After sort:"); \
5182 a.Sort(name ## Compare); \
5183 PrintArray("a", a); \
5185 puts("After reverse sort:"); \
5186 a.Sort(name ## RevCompare); \
5187 PrintArray("a", a); \
5189 wxSortedArray##name b; \
5195 puts("Sorted array initially:"); \
5196 PrintArray("b", b); \
5199 TestArrayOf(UShort
);
5202 static void TestArrayOfObjects()
5204 puts("*** Testing wxObjArray ***\n");
5208 Bar
bar("second bar (two copies!)");
5210 printf("Initially: %u objects in the array, %u objects total.\n",
5211 bars
.GetCount(), Bar::GetNumber());
5213 bars
.Add(new Bar("first bar"));
5216 printf("Now: %u objects in the array, %u objects total.\n",
5217 bars
.GetCount(), Bar::GetNumber());
5219 bars
.RemoveAt(1, bars
.GetCount() - 1);
5221 printf("After removing all but first element: %u objects in the "
5222 "array, %u objects total.\n",
5223 bars
.GetCount(), Bar::GetNumber());
5227 printf("After Empty(): %u objects in the array, %u objects total.\n",
5228 bars
.GetCount(), Bar::GetNumber());
5231 printf("Finally: no more objects in the array, %u objects total.\n",
5235 #endif // TEST_ARRAYS
5237 // ----------------------------------------------------------------------------
5239 // ----------------------------------------------------------------------------
5243 #include "wx/timer.h"
5244 #include "wx/tokenzr.h"
5246 static void TestStringConstruction()
5248 puts("*** Testing wxString constructores ***");
5250 #define TEST_CTOR(args, res) \
5253 printf("wxString%s = %s ", #args, s.c_str()); \
5260 printf("(ERROR: should be %s)\n", res); \
5264 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5265 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5266 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5267 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5269 static const wxChar
*s
= _T("?really!");
5270 const wxChar
*start
= wxStrchr(s
, _T('r'));
5271 const wxChar
*end
= wxStrchr(s
, _T('!'));
5272 TEST_CTOR((start
, end
), _T("really"));
5277 static void TestString()
5287 for (int i
= 0; i
< 1000000; ++i
)
5291 c
= "! How'ya doin'?";
5294 c
= "Hello world! What's up?";
5299 printf ("TestString elapsed time: %ld\n", sw
.Time());
5302 static void TestPChar()
5310 for (int i
= 0; i
< 1000000; ++i
)
5312 strcpy (a
, "Hello");
5313 strcpy (b
, " world");
5314 strcpy (c
, "! How'ya doin'?");
5317 strcpy (c
, "Hello world! What's up?");
5318 if (strcmp (c
, a
) == 0)
5322 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5325 static void TestStringSub()
5327 wxString
s("Hello, world!");
5329 puts("*** Testing wxString substring extraction ***");
5331 printf("String = '%s'\n", s
.c_str());
5332 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5333 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5334 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5335 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5336 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5337 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5339 static const wxChar
*prefixes
[] =
5343 _T("Hello, world!"),
5344 _T("Hello, world!!!"),
5350 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5352 wxString prefix
= prefixes
[n
], rest
;
5353 bool rc
= s
.StartsWith(prefix
, &rest
);
5354 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5357 printf(" (the rest is '%s')\n", rest
.c_str());
5368 static void TestStringFormat()
5370 puts("*** Testing wxString formatting ***");
5373 s
.Printf("%03d", 18);
5375 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5376 printf("Number 18: %s\n", s
.c_str());
5381 // returns "not found" for npos, value for all others
5382 static wxString
PosToString(size_t res
)
5384 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5385 : wxString::Format(_T("%u"), res
);
5389 static void TestStringFind()
5391 puts("*** Testing wxString find() functions ***");
5393 static const wxChar
*strToFind
= _T("ell");
5394 static const struct StringFindTest
5398 result
; // of searching "ell" in str
5401 { _T("Well, hello world"), 0, 1 },
5402 { _T("Well, hello world"), 6, 7 },
5403 { _T("Well, hello world"), 9, wxString::npos
},
5406 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5408 const StringFindTest
& ft
= findTestData
[n
];
5409 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5411 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5412 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5414 size_t resTrue
= ft
.result
;
5415 if ( res
== resTrue
)
5421 printf(_T("(ERROR: should be %s)\n"),
5422 PosToString(resTrue
).c_str());
5429 static void TestStringTokenizer()
5431 puts("*** Testing wxStringTokenizer ***");
5433 static const wxChar
*modeNames
[] =
5437 _T("return all empty"),
5442 static const struct StringTokenizerTest
5444 const wxChar
*str
; // string to tokenize
5445 const wxChar
*delims
; // delimiters to use
5446 size_t count
; // count of token
5447 wxStringTokenizerMode mode
; // how should we tokenize it
5448 } tokenizerTestData
[] =
5450 { _T(""), _T(" "), 0 },
5451 { _T("Hello, world"), _T(" "), 2 },
5452 { _T("Hello, world "), _T(" "), 2 },
5453 { _T("Hello, world"), _T(","), 2 },
5454 { _T("Hello, world!"), _T(",!"), 2 },
5455 { _T("Hello,, world!"), _T(",!"), 3 },
5456 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5457 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5458 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5459 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5460 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5461 { _T("01/02/99"), _T("/-"), 3 },
5462 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5465 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5467 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5468 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5470 size_t count
= tkz
.CountTokens();
5471 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5472 MakePrintable(tt
.str
).c_str(),
5474 MakePrintable(tt
.delims
).c_str(),
5475 modeNames
[tkz
.GetMode()]);
5476 if ( count
== tt
.count
)
5482 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5487 // if we emulate strtok(), check that we do it correctly
5488 wxChar
*buf
, *s
= NULL
, *last
;
5490 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5492 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5493 wxStrcpy(buf
, tt
.str
);
5495 s
= wxStrtok(buf
, tt
.delims
, &last
);
5502 // now show the tokens themselves
5504 while ( tkz
.HasMoreTokens() )
5506 wxString token
= tkz
.GetNextToken();
5508 printf(_T("\ttoken %u: '%s'"),
5510 MakePrintable(token
).c_str());
5520 printf(" (ERROR: should be %s)\n", s
);
5523 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5527 // nothing to compare with
5532 if ( count2
!= count
)
5534 puts(_T("\tERROR: token count mismatch"));
5543 static void TestStringReplace()
5545 puts("*** Testing wxString::replace ***");
5547 static const struct StringReplaceTestData
5549 const wxChar
*original
; // original test string
5550 size_t start
, len
; // the part to replace
5551 const wxChar
*replacement
; // the replacement string
5552 const wxChar
*result
; // and the expected result
5553 } stringReplaceTestData
[] =
5555 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5556 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5557 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5558 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5559 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5562 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5564 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5566 wxString original
= data
.original
;
5567 original
.replace(data
.start
, data
.len
, data
.replacement
);
5569 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5570 data
.original
, data
.start
, data
.len
, data
.replacement
,
5573 if ( original
== data
.result
)
5579 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5586 static void TestStringMatch()
5588 wxPuts(_T("*** Testing wxString::Matches() ***"));
5590 static const struct StringMatchTestData
5593 const wxChar
*wildcard
;
5595 } stringMatchTestData
[] =
5597 { _T("foobar"), _T("foo*"), 1 },
5598 { _T("foobar"), _T("*oo*"), 1 },
5599 { _T("foobar"), _T("*bar"), 1 },
5600 { _T("foobar"), _T("??????"), 1 },
5601 { _T("foobar"), _T("f??b*"), 1 },
5602 { _T("foobar"), _T("f?b*"), 0 },
5603 { _T("foobar"), _T("*goo*"), 0 },
5604 { _T("foobar"), _T("*foo"), 0 },
5605 { _T("foobarfoo"), _T("*foo"), 1 },
5606 { _T(""), _T("*"), 1 },
5607 { _T(""), _T("?"), 0 },
5610 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5612 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5613 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5614 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5616 matches
? _T("matches") : _T("doesn't match"),
5618 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5624 #endif // TEST_STRINGS
5626 // ----------------------------------------------------------------------------
5628 // ----------------------------------------------------------------------------
5630 #ifdef TEST_SNGLINST
5631 #include "wx/snglinst.h"
5632 #endif // TEST_SNGLINST
5634 int main(int argc
, char **argv
)
5636 wxApp::CheckBuildOptions(wxBuildOptions());
5638 wxInitializer initializer
;
5641 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5646 #ifdef TEST_SNGLINST
5647 wxSingleInstanceChecker checker
;
5648 if ( checker
.Create(_T(".wxconsole.lock")) )
5650 if ( checker
.IsAnotherRunning() )
5652 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5657 // wait some time to give time to launch another instance
5658 wxPrintf(_T("Press \"Enter\" to continue..."));
5661 else // failed to create
5663 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5665 #endif // TEST_SNGLINST
5669 #endif // TEST_CHARSET
5672 TestCmdLineConvert();
5674 #if wxUSE_CMDLINE_PARSER
5675 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5677 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5678 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5679 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5680 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5682 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5683 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5684 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5685 wxCMD_LINE_VAL_NUMBER
},
5686 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5687 wxCMD_LINE_VAL_DATE
},
5689 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5690 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5695 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5697 parser
.AddOption("project_name", "", "full path to project file",
5698 wxCMD_LINE_VAL_STRING
,
5699 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5701 switch ( parser
.Parse() )
5704 wxLogMessage("Help was given, terminating.");
5708 ShowCmdLine(parser
);
5712 wxLogMessage("Syntax error detected, aborting.");
5715 #endif // wxUSE_CMDLINE_PARSER
5717 #endif // TEST_CMDLINE
5725 TestStringConstruction();
5728 TestStringTokenizer();
5729 TestStringReplace();
5735 #endif // TEST_STRINGS
5748 puts("*** Initially:");
5750 PrintArray("a1", a1
);
5752 wxArrayString
a2(a1
);
5753 PrintArray("a2", a2
);
5755 wxSortedArrayString
a3(a1
);
5756 PrintArray("a3", a3
);
5758 puts("*** After deleting three strings from a1");
5761 PrintArray("a1", a1
);
5762 PrintArray("a2", a2
);
5763 PrintArray("a3", a3
);
5765 puts("*** After reassigning a1 to a2 and a3");
5767 PrintArray("a2", a2
);
5768 PrintArray("a3", a3
);
5770 puts("*** After sorting a1");
5772 PrintArray("a1", a1
);
5774 puts("*** After sorting a1 in reverse order");
5776 PrintArray("a1", a1
);
5778 puts("*** After sorting a1 by the string length");
5779 a1
.Sort(StringLenCompare
);
5780 PrintArray("a1", a1
);
5782 TestArrayOfObjects();
5783 TestArrayOfUShorts();
5787 #endif // TEST_ARRAYS
5797 #ifdef TEST_DLLLOADER
5799 #endif // TEST_DLLLOADER
5803 #endif // TEST_ENVIRON
5807 #endif // TEST_EXECUTE
5809 #ifdef TEST_FILECONF
5811 #endif // TEST_FILECONF
5819 #endif // TEST_LOCALE
5823 for ( size_t n
= 0; n
< 8000; n
++ )
5825 s
<< (char)('A' + (n
% 26));
5829 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5831 // this one shouldn't be truncated
5834 // but this one will because log functions use fixed size buffer
5835 // (note that it doesn't need '\n' at the end neither - will be added
5837 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5849 #ifdef TEST_FILENAME
5853 fn
.Assign("c:\\foo", "bar.baz");
5854 fn
.Assign("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc");
5861 TestFileNameConstruction();
5862 TestFileNameMakeRelative();
5863 TestFileNameSplit();
5866 TestFileNameComparison();
5867 TestFileNameOperations();
5869 #endif // TEST_FILENAME
5871 #ifdef TEST_FILETIME
5875 #endif // TEST_FILETIME
5878 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5879 if ( TestFtpConnect() )
5890 if ( TEST_INTERACTIVE
)
5891 TestFtpInteractive();
5893 //else: connecting to the FTP server failed
5899 #ifdef TEST_LONGLONG
5900 // seed pseudo random generator
5901 srand((unsigned)time(NULL
));
5910 TestMultiplication();
5913 TestLongLongConversion();
5914 TestBitOperations();
5915 TestLongLongComparison();
5916 TestLongLongPrint();
5918 #endif // TEST_LONGLONG
5926 #endif // TEST_HASHMAP
5929 wxLog::AddTraceMask(_T("mime"));
5937 TestMimeAssociate();
5940 #ifdef TEST_INFO_FUNCTIONS
5946 if ( TEST_INTERACTIVE
)
5949 #endif // TEST_INFO_FUNCTIONS
5951 #ifdef TEST_PATHLIST
5953 #endif // TEST_PATHLIST
5961 #endif // TEST_REGCONF
5964 // TODO: write a real test using src/regex/tests file
5969 TestRegExSubmatch();
5970 TestRegExReplacement();
5972 if ( TEST_INTERACTIVE
)
5973 TestRegExInteractive();
5975 #endif // TEST_REGEX
5977 #ifdef TEST_REGISTRY
5979 TestRegistryAssociation();
5980 #endif // TEST_REGISTRY
5985 #endif // TEST_SOCKETS
5990 #endif // TEST_STREAMS
5993 int nCPUs
= wxThread::GetCPUCount();
5994 printf("This system has %d CPUs\n", nCPUs
);
5996 wxThread::SetConcurrency(nCPUs
);
6000 TestDetachedThreads();
6001 TestJoinableThreads();
6002 TestThreadSuspend();
6004 TestThreadConditions();
6009 #endif // TEST_THREADS
6013 #endif // TEST_TIMER
6015 #ifdef TEST_DATETIME
6028 TestTimeArithmetics();
6031 TestTimeSpanFormat();
6037 if ( TEST_INTERACTIVE
)
6038 TestDateTimeInteractive();
6039 #endif // TEST_DATETIME
6042 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6044 #endif // TEST_USLEEP
6049 #endif // TEST_VCARD
6053 #endif // TEST_VOLUME
6057 TestEncodingConverter();
6058 #endif // TEST_WCHAR
6061 TestZipStreamRead();
6062 TestZipFileSystem();
6066 TestZlibStreamWrite();
6067 TestZlibStreamRead();