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 // ----------------------------------------------------------------------------
2401 static void TestDbOpen()
2409 // ----------------------------------------------------------------------------
2410 // registry and related stuff
2411 // ----------------------------------------------------------------------------
2413 // this is for MSW only
2416 #undef TEST_REGISTRY
2421 #include "wx/confbase.h"
2422 #include "wx/msw/regconf.h"
2424 static void TestRegConfWrite()
2426 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2427 regconf
.Write(_T("Hello"), wxString(_T("world")));
2430 #endif // TEST_REGCONF
2432 #ifdef TEST_REGISTRY
2434 #include "wx/msw/registry.h"
2436 // I chose this one because I liked its name, but it probably only exists under
2438 static const wxChar
*TESTKEY
=
2439 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2441 static void TestRegistryRead()
2443 puts("*** testing registry reading ***");
2445 wxRegKey
key(TESTKEY
);
2446 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2449 puts("ERROR: test key can't be opened, aborting test.");
2454 size_t nSubKeys
, nValues
;
2455 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2457 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2460 printf("Enumerating values:\n");
2464 bool cont
= key
.GetFirstValue(value
, dummy
);
2467 printf("Value '%s': type ", value
.c_str());
2468 switch ( key
.GetValueType(value
) )
2470 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2471 case wxRegKey::Type_String
: printf("SZ"); break;
2472 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2473 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2474 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2475 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2476 default: printf("other (unknown)"); break;
2479 printf(", value = ");
2480 if ( key
.IsNumericValue(value
) )
2483 key
.QueryValue(value
, &val
);
2489 key
.QueryValue(value
, val
);
2490 printf("'%s'", val
.c_str());
2492 key
.QueryRawValue(value
, val
);
2493 printf(" (raw value '%s')", val
.c_str());
2498 cont
= key
.GetNextValue(value
, dummy
);
2502 static void TestRegistryAssociation()
2505 The second call to deleteself genertaes an error message, with a
2506 messagebox saying .flo is crucial to system operation, while the .ddf
2507 call also fails, but with no error message
2512 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2514 key
= "ddxf_auto_file" ;
2515 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2517 key
= "ddxf_auto_file" ;
2518 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2521 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2523 key
= "program \"%1\"" ;
2525 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2527 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2529 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2531 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2535 #endif // TEST_REGISTRY
2537 // ----------------------------------------------------------------------------
2539 // ----------------------------------------------------------------------------
2543 #include "wx/socket.h"
2544 #include "wx/protocol/protocol.h"
2545 #include "wx/protocol/http.h"
2547 static void TestSocketServer()
2549 puts("*** Testing wxSocketServer ***\n");
2551 static const int PORT
= 3000;
2556 wxSocketServer
*server
= new wxSocketServer(addr
);
2557 if ( !server
->Ok() )
2559 puts("ERROR: failed to bind");
2566 printf("Server: waiting for connection on port %d...\n", PORT
);
2568 wxSocketBase
*socket
= server
->Accept();
2571 puts("ERROR: wxSocketServer::Accept() failed.");
2575 puts("Server: got a client.");
2577 server
->SetTimeout(60); // 1 min
2579 while ( socket
->IsConnected() )
2585 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2587 // don't log error if the client just close the connection
2588 if ( socket
->IsConnected() )
2590 puts("ERROR: in wxSocket::Read.");
2610 printf("Server: got '%s'.\n", s
.c_str());
2611 if ( s
== _T("bye") )
2618 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2619 socket
->Write("\r\n", 2);
2620 printf("Server: wrote '%s'.\n", s
.c_str());
2623 puts("Server: lost a client.");
2628 // same as "delete server" but is consistent with GUI programs
2632 static void TestSocketClient()
2634 puts("*** Testing wxSocketClient ***\n");
2636 static const char *hostname
= "www.wxwindows.org";
2639 addr
.Hostname(hostname
);
2642 printf("--- Attempting to connect to %s:80...\n", hostname
);
2644 wxSocketClient client
;
2645 if ( !client
.Connect(addr
) )
2647 printf("ERROR: failed to connect to %s\n", hostname
);
2651 printf("--- Connected to %s:%u...\n",
2652 addr
.Hostname().c_str(), addr
.Service());
2656 // could use simply "GET" here I suppose
2658 wxString::Format("GET http://%s/\r\n", hostname
);
2659 client
.Write(cmdGet
, cmdGet
.length());
2660 printf("--- Sent command '%s' to the server\n",
2661 MakePrintable(cmdGet
).c_str());
2662 client
.Read(buf
, WXSIZEOF(buf
));
2663 printf("--- Server replied:\n%s", buf
);
2667 #endif // TEST_SOCKETS
2669 // ----------------------------------------------------------------------------
2671 // ----------------------------------------------------------------------------
2675 #include "wx/protocol/ftp.h"
2679 #define FTP_ANONYMOUS
2681 #ifdef FTP_ANONYMOUS
2682 static const char *directory
= "/pub";
2683 static const char *filename
= "welcome.msg";
2685 static const char *directory
= "/etc";
2686 static const char *filename
= "issue";
2689 static bool TestFtpConnect()
2691 puts("*** Testing FTP connect ***");
2693 #ifdef FTP_ANONYMOUS
2694 static const char *hostname
= "ftp.wxwindows.org";
2696 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2697 #else // !FTP_ANONYMOUS
2698 static const char *hostname
= "localhost";
2701 fgets(user
, WXSIZEOF(user
), stdin
);
2702 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2706 printf("Password for %s: ", password
);
2707 fgets(password
, WXSIZEOF(password
), stdin
);
2708 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2709 ftp
.SetPassword(password
);
2711 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2712 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2714 if ( !ftp
.Connect(hostname
) )
2716 printf("ERROR: failed to connect to %s\n", hostname
);
2722 printf("--- Connected to %s, current directory is '%s'\n",
2723 hostname
, ftp
.Pwd().c_str());
2729 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2730 static void TestFtpWuFtpd()
2733 static const char *hostname
= "ftp.eudora.com";
2734 if ( !ftp
.Connect(hostname
) )
2736 printf("ERROR: failed to connect to %s\n", hostname
);
2740 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2741 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2744 printf("ERROR: couldn't get input stream for %s\n", filename
);
2748 size_t size
= in
->StreamSize();
2749 printf("Reading file %s (%u bytes)...", filename
, size
);
2751 char *data
= new char[size
];
2752 if ( !in
->Read(data
, size
) )
2754 puts("ERROR: read error");
2758 printf("Successfully retrieved the file.\n");
2767 static void TestFtpList()
2769 puts("*** Testing wxFTP file listing ***\n");
2772 if ( !ftp
.ChDir(directory
) )
2774 printf("ERROR: failed to cd to %s\n", directory
);
2777 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2779 // test NLIST and LIST
2780 wxArrayString files
;
2781 if ( !ftp
.GetFilesList(files
) )
2783 puts("ERROR: failed to get NLIST of files");
2787 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2788 size_t count
= files
.GetCount();
2789 for ( size_t n
= 0; n
< count
; n
++ )
2791 printf("\t%s\n", files
[n
].c_str());
2793 puts("End of the file list");
2796 if ( !ftp
.GetDirList(files
) )
2798 puts("ERROR: failed to get LIST of files");
2802 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2803 size_t count
= files
.GetCount();
2804 for ( size_t n
= 0; n
< count
; n
++ )
2806 printf("\t%s\n", files
[n
].c_str());
2808 puts("End of the file list");
2811 if ( !ftp
.ChDir(_T("..")) )
2813 puts("ERROR: failed to cd to ..");
2816 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2819 static void TestFtpDownload()
2821 puts("*** Testing wxFTP download ***\n");
2824 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2827 printf("ERROR: couldn't get input stream for %s\n", filename
);
2831 size_t size
= in
->StreamSize();
2832 printf("Reading file %s (%u bytes)...", filename
, size
);
2835 char *data
= new char[size
];
2836 if ( !in
->Read(data
, size
) )
2838 puts("ERROR: read error");
2842 printf("\nContents of %s:\n%s\n", filename
, data
);
2850 static void TestFtpFileSize()
2852 puts("*** Testing FTP SIZE command ***");
2854 if ( !ftp
.ChDir(directory
) )
2856 printf("ERROR: failed to cd to %s\n", directory
);
2859 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2861 if ( ftp
.FileExists(filename
) )
2863 int size
= ftp
.GetFileSize(filename
);
2865 printf("ERROR: couldn't get size of '%s'\n", filename
);
2867 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2871 printf("ERROR: '%s' doesn't exist\n", filename
);
2875 static void TestFtpMisc()
2877 puts("*** Testing miscellaneous wxFTP functions ***");
2879 if ( ftp
.SendCommand("STAT") != '2' )
2881 puts("ERROR: STAT failed");
2885 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2888 if ( ftp
.SendCommand("HELP SITE") != '2' )
2890 puts("ERROR: HELP SITE failed");
2894 printf("The list of site-specific commands:\n\n%s\n",
2895 ftp
.GetLastResult().c_str());
2899 static void TestFtpInteractive()
2901 puts("\n*** Interactive wxFTP test ***");
2907 printf("Enter FTP command: ");
2908 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2911 // kill the last '\n'
2912 buf
[strlen(buf
) - 1] = 0;
2914 // special handling of LIST and NLST as they require data connection
2915 wxString
start(buf
, 4);
2917 if ( start
== "LIST" || start
== "NLST" )
2920 if ( strlen(buf
) > 4 )
2923 wxArrayString files
;
2924 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2926 printf("ERROR: failed to get %s of files\n", start
.c_str());
2930 printf("--- %s of '%s' under '%s':\n",
2931 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2932 size_t count
= files
.GetCount();
2933 for ( size_t n
= 0; n
< count
; n
++ )
2935 printf("\t%s\n", files
[n
].c_str());
2937 puts("--- End of the file list");
2942 char ch
= ftp
.SendCommand(buf
);
2943 printf("Command %s", ch
? "succeeded" : "failed");
2946 printf(" (return code %c)", ch
);
2949 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2953 puts("\n*** done ***");
2956 static void TestFtpUpload()
2958 puts("*** Testing wxFTP uploading ***\n");
2961 static const char *file1
= "test1";
2962 static const char *file2
= "test2";
2963 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2966 printf("--- Uploading to %s ---\n", file1
);
2967 out
->Write("First hello", 11);
2971 // send a command to check the remote file
2972 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2974 printf("ERROR: STAT %s failed\n", file1
);
2978 printf("STAT %s returned:\n\n%s\n",
2979 file1
, ftp
.GetLastResult().c_str());
2982 out
= ftp
.GetOutputStream(file2
);
2985 printf("--- Uploading to %s ---\n", file1
);
2986 out
->Write("Second hello", 12);
2993 // ----------------------------------------------------------------------------
2995 // ----------------------------------------------------------------------------
2999 #include "wx/wfstream.h"
3000 #include "wx/mstream.h"
3002 static void TestFileStream()
3004 puts("*** Testing wxFileInputStream ***");
3006 static const wxChar
*filename
= _T("testdata.fs");
3008 wxFileOutputStream
fsOut(filename
);
3009 fsOut
.Write("foo", 3);
3012 wxFileInputStream
fsIn(filename
);
3013 printf("File stream size: %u\n", fsIn
.GetSize());
3014 while ( !fsIn
.Eof() )
3016 putchar(fsIn
.GetC());
3019 if ( !wxRemoveFile(filename
) )
3021 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3024 puts("\n*** wxFileInputStream test done ***");
3027 static void TestMemoryStream()
3029 puts("*** Testing wxMemoryInputStream ***");
3032 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3034 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3035 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3036 while ( !memInpStream
.Eof() )
3038 putchar(memInpStream
.GetC());
3041 puts("\n*** wxMemoryInputStream test done ***");
3044 #endif // TEST_STREAMS
3046 // ----------------------------------------------------------------------------
3048 // ----------------------------------------------------------------------------
3052 #include "wx/timer.h"
3053 #include "wx/utils.h"
3055 static void TestStopWatch()
3057 puts("*** Testing wxStopWatch ***\n");
3061 printf("Initially paused, after 2 seconds time is...");
3064 printf("\t%ldms\n", sw
.Time());
3066 printf("Resuming stopwatch and sleeping 3 seconds...");
3070 printf("\telapsed time: %ldms\n", sw
.Time());
3073 printf("Pausing agan and sleeping 2 more seconds...");
3076 printf("\telapsed time: %ldms\n", sw
.Time());
3079 printf("Finally resuming and sleeping 2 more seconds...");
3082 printf("\telapsed time: %ldms\n", sw
.Time());
3085 puts("\nChecking for 'backwards clock' bug...");
3086 for ( size_t n
= 0; n
< 70; n
++ )
3090 for ( size_t m
= 0; m
< 100000; m
++ )
3092 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3094 puts("\ntime is negative - ERROR!");
3105 #endif // TEST_TIMER
3107 // ----------------------------------------------------------------------------
3109 // ----------------------------------------------------------------------------
3113 #include "wx/vcard.h"
3115 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3118 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3122 wxString(_T('\t'), level
).c_str(),
3123 vcObj
->GetName().c_str());
3126 switch ( vcObj
->GetType() )
3128 case wxVCardObject::String
:
3129 case wxVCardObject::UString
:
3132 vcObj
->GetValue(&val
);
3133 value
<< _T('"') << val
<< _T('"');
3137 case wxVCardObject::Int
:
3140 vcObj
->GetValue(&i
);
3141 value
.Printf(_T("%u"), i
);
3145 case wxVCardObject::Long
:
3148 vcObj
->GetValue(&l
);
3149 value
.Printf(_T("%lu"), l
);
3153 case wxVCardObject::None
:
3156 case wxVCardObject::Object
:
3157 value
= _T("<node>");
3161 value
= _T("<unknown value type>");
3165 printf(" = %s", value
.c_str());
3168 DumpVObject(level
+ 1, *vcObj
);
3171 vcObj
= vcard
.GetNextProp(&cookie
);
3175 static void DumpVCardAddresses(const wxVCard
& vcard
)
3177 puts("\nShowing all addresses from vCard:\n");
3181 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3185 int flags
= addr
->GetFlags();
3186 if ( flags
& wxVCardAddress::Domestic
)
3188 flagsStr
<< _T("domestic ");
3190 if ( flags
& wxVCardAddress::Intl
)
3192 flagsStr
<< _T("international ");
3194 if ( flags
& wxVCardAddress::Postal
)
3196 flagsStr
<< _T("postal ");
3198 if ( flags
& wxVCardAddress::Parcel
)
3200 flagsStr
<< _T("parcel ");
3202 if ( flags
& wxVCardAddress::Home
)
3204 flagsStr
<< _T("home ");
3206 if ( flags
& wxVCardAddress::Work
)
3208 flagsStr
<< _T("work ");
3211 printf("Address %u:\n"
3213 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3216 addr
->GetPostOffice().c_str(),
3217 addr
->GetExtAddress().c_str(),
3218 addr
->GetStreet().c_str(),
3219 addr
->GetLocality().c_str(),
3220 addr
->GetRegion().c_str(),
3221 addr
->GetPostalCode().c_str(),
3222 addr
->GetCountry().c_str()
3226 addr
= vcard
.GetNextAddress(&cookie
);
3230 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3232 puts("\nShowing all phone numbers from vCard:\n");
3236 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3240 int flags
= phone
->GetFlags();
3241 if ( flags
& wxVCardPhoneNumber::Voice
)
3243 flagsStr
<< _T("voice ");
3245 if ( flags
& wxVCardPhoneNumber::Fax
)
3247 flagsStr
<< _T("fax ");
3249 if ( flags
& wxVCardPhoneNumber::Cellular
)
3251 flagsStr
<< _T("cellular ");
3253 if ( flags
& wxVCardPhoneNumber::Modem
)
3255 flagsStr
<< _T("modem ");
3257 if ( flags
& wxVCardPhoneNumber::Home
)
3259 flagsStr
<< _T("home ");
3261 if ( flags
& wxVCardPhoneNumber::Work
)
3263 flagsStr
<< _T("work ");
3266 printf("Phone number %u:\n"
3271 phone
->GetNumber().c_str()
3275 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3279 static void TestVCardRead()
3281 puts("*** Testing wxVCard reading ***\n");
3283 wxVCard
vcard(_T("vcard.vcf"));
3284 if ( !vcard
.IsOk() )
3286 puts("ERROR: couldn't load vCard.");
3290 // read individual vCard properties
3291 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3295 vcObj
->GetValue(&value
);
3300 value
= _T("<none>");
3303 printf("Full name retrieved directly: %s\n", value
.c_str());
3306 if ( !vcard
.GetFullName(&value
) )
3308 value
= _T("<none>");
3311 printf("Full name from wxVCard API: %s\n", value
.c_str());
3313 // now show how to deal with multiply occuring properties
3314 DumpVCardAddresses(vcard
);
3315 DumpVCardPhoneNumbers(vcard
);
3317 // and finally show all
3318 puts("\nNow dumping the entire vCard:\n"
3319 "-----------------------------\n");
3321 DumpVObject(0, vcard
);
3325 static void TestVCardWrite()
3327 puts("*** Testing wxVCard writing ***\n");
3330 if ( !vcard
.IsOk() )
3332 puts("ERROR: couldn't create vCard.");
3337 vcard
.SetName("Zeitlin", "Vadim");
3338 vcard
.SetFullName("Vadim Zeitlin");
3339 vcard
.SetOrganization("wxWindows", "R&D");
3341 // just dump the vCard back
3342 puts("Entire vCard follows:\n");
3343 puts(vcard
.Write());
3347 #endif // TEST_VCARD
3349 // ----------------------------------------------------------------------------
3351 // ----------------------------------------------------------------------------
3353 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3359 #include "wx/volume.h"
3361 static const wxChar
*volumeKinds
[] =
3367 _T("network volume"),
3371 static void TestFSVolume()
3373 wxPuts(_T("*** Testing wxFSVolume class ***"));
3375 wxArrayString volumes
= wxFSVolume::GetVolumes();
3376 size_t count
= volumes
.GetCount();
3380 wxPuts(_T("ERROR: no mounted volumes?"));
3384 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3386 for ( size_t n
= 0; n
< count
; n
++ )
3388 wxFSVolume
vol(volumes
[n
]);
3391 wxPuts(_T("ERROR: couldn't create volume"));
3395 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3397 vol
.GetDisplayName().c_str(),
3398 vol
.GetName().c_str(),
3399 volumeKinds
[vol
.GetKind()],
3400 vol
.IsWritable() ? _T("rw") : _T("ro"),
3401 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3406 #endif // TEST_VOLUME
3408 // ----------------------------------------------------------------------------
3409 // wide char (Unicode) support
3410 // ----------------------------------------------------------------------------
3414 #include "wx/strconv.h"
3415 #include "wx/fontenc.h"
3416 #include "wx/encconv.h"
3417 #include "wx/buffer.h"
3419 static const char textInUtf8
[] =
3421 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3422 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3423 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3424 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3425 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3426 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3427 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3430 static void TestUtf8()
3432 puts("*** Testing UTF8 support ***\n");
3436 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3438 puts("ERROR: UTF-8 decoding failed.");
3442 wxCSConv
conv(_T("koi8-r"));
3443 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3445 puts("ERROR: conversion to KOI8-R failed.");
3449 printf("The resulting string (in KOI8-R): %s\n", buf
);
3453 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3455 puts("ERROR: conversion to UTF-8 failed.");
3459 printf("The string in UTF-8: %s\n", buf
);
3465 static void TestEncodingConverter()
3467 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3469 // using wxEncodingConverter should give the same result as above
3472 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3474 puts("ERROR: UTF-8 decoding failed.");
3478 wxEncodingConverter ec
;
3479 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3480 ec
.Convert(wbuf
, buf
);
3481 printf("The same string obtained using wxEC: %s\n", buf
);
3487 #endif // TEST_WCHAR
3489 // ----------------------------------------------------------------------------
3491 // ----------------------------------------------------------------------------
3495 #include "wx/filesys.h"
3496 #include "wx/fs_zip.h"
3497 #include "wx/zipstrm.h"
3499 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3501 static void TestZipStreamRead()
3503 puts("*** Testing ZIP reading ***\n");
3505 static const wxChar
*filename
= _T("foo");
3506 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3507 printf("Archive size: %u\n", istr
.GetSize());
3509 printf("Dumping the file '%s':\n", filename
);
3510 while ( !istr
.Eof() )
3512 putchar(istr
.GetC());
3516 puts("\n----- done ------");
3519 static void DumpZipDirectory(wxFileSystem
& fs
,
3520 const wxString
& dir
,
3521 const wxString
& indent
)
3523 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3524 TESTFILE_ZIP
, dir
.c_str());
3525 wxString wildcard
= prefix
+ _T("/*");
3527 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3528 while ( !dirname
.empty() )
3530 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3532 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3537 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3539 DumpZipDirectory(fs
, dirname
,
3540 indent
+ wxString(_T(' '), 4));
3542 dirname
= fs
.FindNext();
3545 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3546 while ( !filename
.empty() )
3548 if ( !filename
.StartsWith(prefix
, &filename
) )
3550 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3555 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3557 filename
= fs
.FindNext();
3561 static void TestZipFileSystem()
3563 puts("*** Testing ZIP file system ***\n");
3565 wxFileSystem::AddHandler(new wxZipFSHandler
);
3567 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3569 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3574 // ----------------------------------------------------------------------------
3576 // ----------------------------------------------------------------------------
3580 #include "wx/zstream.h"
3581 #include "wx/wfstream.h"
3583 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3584 static const char *TEST_DATA
= "hello and hello and hello and hello and hello";
3586 static void TestZlibStreamWrite()
3588 puts("*** Testing Zlib stream reading ***\n");
3590 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3591 wxZlibOutputStream
ostr(fileOutStream
);
3592 printf("Compressing the test string... ");
3593 ostr
.Write(TEST_DATA
, strlen(TEST_DATA
) + 1);
3596 puts("(ERROR: failed)");
3603 puts("\n----- done ------");
3606 static void TestZlibStreamRead()
3608 puts("*** Testing Zlib stream reading ***\n");
3610 wxFileInputStream
fileInStream(FILENAME_GZ
);
3611 wxZlibInputStream
istr(fileInStream
);
3612 printf("Archive size: %u\n", istr
.GetSize());
3614 puts("Dumping the file:");
3615 while ( !istr
.Eof() )
3617 putchar(istr
.GetC());
3621 puts("\n----- done ------");
3626 // ----------------------------------------------------------------------------
3628 // ----------------------------------------------------------------------------
3630 #ifdef TEST_DATETIME
3634 #include "wx/date.h"
3635 #include "wx/datetime.h"
3640 wxDateTime::wxDateTime_t day
;
3641 wxDateTime::Month month
;
3643 wxDateTime::wxDateTime_t hour
, min
, sec
;
3645 wxDateTime::WeekDay wday
;
3646 time_t gmticks
, ticks
;
3648 void Init(const wxDateTime::Tm
& tm
)
3657 gmticks
= ticks
= -1;
3660 wxDateTime
DT() const
3661 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3663 bool SameDay(const wxDateTime::Tm
& tm
) const
3665 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3668 wxString
Format() const
3671 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3673 wxDateTime::GetMonthName(month
).c_str(),
3675 abs(wxDateTime::ConvertYearToBC(year
)),
3676 year
> 0 ? "AD" : "BC");
3680 wxString
FormatDate() const
3683 s
.Printf("%02d-%s-%4d%s",
3685 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3686 abs(wxDateTime::ConvertYearToBC(year
)),
3687 year
> 0 ? "AD" : "BC");
3692 static const Date testDates
[] =
3694 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3695 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3696 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3697 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3698 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3699 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3700 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3701 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3702 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3703 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3704 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3705 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3706 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3707 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3708 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3711 // this test miscellaneous static wxDateTime functions
3712 static void TestTimeStatic()
3714 puts("\n*** wxDateTime static methods test ***");
3716 // some info about the current date
3717 int year
= wxDateTime::GetCurrentYear();
3718 printf("Current year %d is %sa leap one and has %d days.\n",
3720 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3721 wxDateTime::GetNumberOfDays(year
));
3723 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3724 printf("Current month is '%s' ('%s') and it has %d days\n",
3725 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3726 wxDateTime::GetMonthName(month
).c_str(),
3727 wxDateTime::GetNumberOfDays(month
));
3730 static const size_t nYears
= 5;
3731 static const size_t years
[2][nYears
] =
3733 // first line: the years to test
3734 { 1990, 1976, 2000, 2030, 1984, },
3736 // second line: TRUE if leap, FALSE otherwise
3737 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3740 for ( size_t n
= 0; n
< nYears
; n
++ )
3742 int year
= years
[0][n
];
3743 bool should
= years
[1][n
] != 0,
3744 is
= wxDateTime::IsLeapYear(year
);
3746 printf("Year %d is %sa leap year (%s)\n",
3749 should
== is
? "ok" : "ERROR");
3751 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3755 // test constructing wxDateTime objects
3756 static void TestTimeSet()
3758 puts("\n*** wxDateTime construction test ***");
3760 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3762 const Date
& d1
= testDates
[n
];
3763 wxDateTime dt
= d1
.DT();
3766 d2
.Init(dt
.GetTm());
3768 wxString s1
= d1
.Format(),
3771 printf("Date: %s == %s (%s)\n",
3772 s1
.c_str(), s2
.c_str(),
3773 s1
== s2
? "ok" : "ERROR");
3777 // test time zones stuff
3778 static void TestTimeZones()
3780 puts("\n*** wxDateTime timezone test ***");
3782 wxDateTime now
= wxDateTime::Now();
3784 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3785 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3786 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3787 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3788 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3789 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3791 wxDateTime::Tm tm
= now
.GetTm();
3792 if ( wxDateTime(tm
) != now
)
3794 printf("ERROR: got %s instead of %s\n",
3795 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3799 // test some minimal support for the dates outside the standard range
3800 static void TestTimeRange()
3802 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3804 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3806 printf("Unix epoch:\t%s\n",
3807 wxDateTime(2440587.5).Format(fmt
).c_str());
3808 printf("Feb 29, 0: \t%s\n",
3809 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3810 printf("JDN 0: \t%s\n",
3811 wxDateTime(0.0).Format(fmt
).c_str());
3812 printf("Jan 1, 1AD:\t%s\n",
3813 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3814 printf("May 29, 2099:\t%s\n",
3815 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3818 static void TestTimeTicks()
3820 puts("\n*** wxDateTime ticks test ***");
3822 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3824 const Date
& d
= testDates
[n
];
3825 if ( d
.ticks
== -1 )
3828 wxDateTime dt
= d
.DT();
3829 long ticks
= (dt
.GetValue() / 1000).ToLong();
3830 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3831 if ( ticks
== d
.ticks
)
3837 printf(" (ERROR: should be %ld, delta = %ld)\n",
3838 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
3841 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3842 ticks
= (dt
.GetValue() / 1000).ToLong();
3843 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3844 if ( ticks
== d
.gmticks
)
3850 printf(" (ERROR: should be %ld, delta = %ld)\n",
3851 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
3858 // test conversions to JDN &c
3859 static void TestTimeJDN()
3861 puts("\n*** wxDateTime to JDN test ***");
3863 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3865 const Date
& d
= testDates
[n
];
3866 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3867 double jdn
= dt
.GetJulianDayNumber();
3869 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3876 printf(" (ERROR: should be %f, delta = %f)\n",
3877 d
.jdn
, jdn
- d
.jdn
);
3882 // test week days computation
3883 static void TestTimeWDays()
3885 puts("\n*** wxDateTime weekday test ***");
3887 // test GetWeekDay()
3889 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3891 const Date
& d
= testDates
[n
];
3892 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3894 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3897 wxDateTime::GetWeekDayName(wday
).c_str());
3898 if ( wday
== d
.wday
)
3904 printf(" (ERROR: should be %s)\n",
3905 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3911 // test SetToWeekDay()
3912 struct WeekDateTestData
3914 Date date
; // the real date (precomputed)
3915 int nWeek
; // its week index in the month
3916 wxDateTime::WeekDay wday
; // the weekday
3917 wxDateTime::Month month
; // the month
3918 int year
; // and the year
3920 wxString
Format() const
3923 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3925 case 1: which
= "first"; break;
3926 case 2: which
= "second"; break;
3927 case 3: which
= "third"; break;
3928 case 4: which
= "fourth"; break;
3929 case 5: which
= "fifth"; break;
3931 case -1: which
= "last"; break;
3936 which
+= " from end";
3939 s
.Printf("The %s %s of %s in %d",
3941 wxDateTime::GetWeekDayName(wday
).c_str(),
3942 wxDateTime::GetMonthName(month
).c_str(),
3949 // the array data was generated by the following python program
3951 from DateTime import *
3952 from whrandom import *
3953 from string import *
3955 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3956 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3958 week = DateTimeDelta(7)
3961 year = randint(1900, 2100)
3962 month = randint(1, 12)
3963 day = randint(1, 28)
3964 dt = DateTime(year, month, day)
3965 wday = dt.day_of_week
3967 countFromEnd = choice([-1, 1])
3970 while dt.month is month:
3971 dt = dt - countFromEnd * week
3972 weekNum = weekNum + countFromEnd
3974 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3976 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3977 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3980 static const WeekDateTestData weekDatesTestData
[] =
3982 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3983 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3984 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3985 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3986 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3987 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3988 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3989 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3990 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3991 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3992 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3993 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3994 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3995 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3996 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3997 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3998 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3999 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
4000 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
4001 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4004 static const char *fmt
= "%d-%b-%Y";
4007 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4009 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4011 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4013 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4015 const Date
& d
= wd
.date
;
4016 if ( d
.SameDay(dt
.GetTm()) )
4022 dt
.Set(d
.day
, d
.month
, d
.year
);
4024 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4029 // test the computation of (ISO) week numbers
4030 static void TestTimeWNumber()
4032 puts("\n*** wxDateTime week number test ***");
4034 struct WeekNumberTestData
4036 Date date
; // the date
4037 wxDateTime::wxDateTime_t week
; // the week number in the year
4038 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4039 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4040 wxDateTime::wxDateTime_t dnum
; // day number in the year
4043 // data generated with the following python script:
4045 from DateTime import *
4046 from whrandom import *
4047 from string import *
4049 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4050 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4052 def GetMonthWeek(dt):
4053 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4054 if weekNumMonth < 0:
4055 weekNumMonth = weekNumMonth + 53
4058 def GetLastSundayBefore(dt):
4059 if dt.iso_week[2] == 7:
4062 return dt - DateTimeDelta(dt.iso_week[2])
4065 year = randint(1900, 2100)
4066 month = randint(1, 12)
4067 day = randint(1, 28)
4068 dt = DateTime(year, month, day)
4069 dayNum = dt.day_of_year
4070 weekNum = dt.iso_week[1]
4071 weekNumMonth = GetMonthWeek(dt)
4074 dtSunday = GetLastSundayBefore(dt)
4076 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4077 weekNumMonth2 = weekNumMonth2 + 1
4078 dtSunday = dtSunday - DateTimeDelta(7)
4080 data = { 'day': rjust(`day`, 2), \
4081 'month': monthNames[month - 1], \
4083 'weekNum': rjust(`weekNum`, 2), \
4084 'weekNumMonth': weekNumMonth, \
4085 'weekNumMonth2': weekNumMonth2, \
4086 'dayNum': rjust(`dayNum`, 3) }
4088 print " { { %(day)s, "\
4089 "wxDateTime::%(month)s, "\
4092 "%(weekNumMonth)s, "\
4093 "%(weekNumMonth2)s, "\
4094 "%(dayNum)s }," % data
4097 static const WeekNumberTestData weekNumberTestDates
[] =
4099 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4100 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4101 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4102 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4103 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4104 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4105 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4106 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4107 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4108 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4109 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4110 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4111 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4112 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4113 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4114 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4115 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4116 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4117 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4118 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4121 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4123 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4124 const Date
& d
= wn
.date
;
4126 wxDateTime dt
= d
.DT();
4128 wxDateTime::wxDateTime_t
4129 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4130 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4131 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4132 dnum
= dt
.GetDayOfYear();
4134 printf("%s: the day number is %d",
4135 d
.FormatDate().c_str(), dnum
);
4136 if ( dnum
== wn
.dnum
)
4142 printf(" (ERROR: should be %d)", wn
.dnum
);
4145 printf(", week in month is %d", wmon
);
4146 if ( wmon
== wn
.wmon
)
4152 printf(" (ERROR: should be %d)", wn
.wmon
);
4155 printf(" or %d", wmon2
);
4156 if ( wmon2
== wn
.wmon2
)
4162 printf(" (ERROR: should be %d)", wn
.wmon2
);
4165 printf(", week in year is %d", week
);
4166 if ( week
== wn
.week
)
4172 printf(" (ERROR: should be %d)\n", wn
.week
);
4177 // test DST calculations
4178 static void TestTimeDST()
4180 puts("\n*** wxDateTime DST test ***");
4182 printf("DST is%s in effect now.\n\n",
4183 wxDateTime::Now().IsDST() ? "" : " not");
4185 // taken from http://www.energy.ca.gov/daylightsaving.html
4186 static const Date datesDST
[2][2004 - 1900 + 1] =
4189 { 1, wxDateTime::Apr
, 1990 },
4190 { 7, wxDateTime::Apr
, 1991 },
4191 { 5, wxDateTime::Apr
, 1992 },
4192 { 4, wxDateTime::Apr
, 1993 },
4193 { 3, wxDateTime::Apr
, 1994 },
4194 { 2, wxDateTime::Apr
, 1995 },
4195 { 7, wxDateTime::Apr
, 1996 },
4196 { 6, wxDateTime::Apr
, 1997 },
4197 { 5, wxDateTime::Apr
, 1998 },
4198 { 4, wxDateTime::Apr
, 1999 },
4199 { 2, wxDateTime::Apr
, 2000 },
4200 { 1, wxDateTime::Apr
, 2001 },
4201 { 7, wxDateTime::Apr
, 2002 },
4202 { 6, wxDateTime::Apr
, 2003 },
4203 { 4, wxDateTime::Apr
, 2004 },
4206 { 28, wxDateTime::Oct
, 1990 },
4207 { 27, wxDateTime::Oct
, 1991 },
4208 { 25, wxDateTime::Oct
, 1992 },
4209 { 31, wxDateTime::Oct
, 1993 },
4210 { 30, wxDateTime::Oct
, 1994 },
4211 { 29, wxDateTime::Oct
, 1995 },
4212 { 27, wxDateTime::Oct
, 1996 },
4213 { 26, wxDateTime::Oct
, 1997 },
4214 { 25, wxDateTime::Oct
, 1998 },
4215 { 31, wxDateTime::Oct
, 1999 },
4216 { 29, wxDateTime::Oct
, 2000 },
4217 { 28, wxDateTime::Oct
, 2001 },
4218 { 27, wxDateTime::Oct
, 2002 },
4219 { 26, wxDateTime::Oct
, 2003 },
4220 { 31, wxDateTime::Oct
, 2004 },
4225 for ( year
= 1990; year
< 2005; year
++ )
4227 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4228 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4230 printf("DST period in the US for year %d: from %s to %s",
4231 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4233 size_t n
= year
- 1990;
4234 const Date
& dBegin
= datesDST
[0][n
];
4235 const Date
& dEnd
= datesDST
[1][n
];
4237 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4243 printf(" (ERROR: should be %s %d to %s %d)\n",
4244 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4245 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4251 for ( year
= 1990; year
< 2005; year
++ )
4253 printf("DST period in Europe for year %d: from %s to %s\n",
4255 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4256 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4260 // test wxDateTime -> text conversion
4261 static void TestTimeFormat()
4263 puts("\n*** wxDateTime formatting test ***");
4265 // some information may be lost during conversion, so store what kind
4266 // of info should we recover after a round trip
4269 CompareNone
, // don't try comparing
4270 CompareBoth
, // dates and times should be identical
4271 CompareDate
, // dates only
4272 CompareTime
// time only
4277 CompareKind compareKind
;
4279 } formatTestFormats
[] =
4281 { CompareBoth
, "---> %c" },
4282 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4283 { CompareBoth
, "Date is %x, time is %X" },
4284 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4285 { CompareNone
, "The day of year: %j, the week of year: %W" },
4286 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4289 static const Date formatTestDates
[] =
4291 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4292 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4294 // this test can't work for other centuries because it uses two digit
4295 // years in formats, so don't even try it
4296 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4297 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4298 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4302 // an extra test (as it doesn't depend on date, don't do it in the loop)
4303 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4305 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4309 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4310 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4312 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4313 printf("%s", s
.c_str());
4315 // what can we recover?
4316 int kind
= formatTestFormats
[n
].compareKind
;
4320 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4323 // converion failed - should it have?
4324 if ( kind
== CompareNone
)
4327 puts(" (ERROR: conversion back failed)");
4331 // should have parsed the entire string
4332 puts(" (ERROR: conversion back stopped too soon)");
4336 bool equal
= FALSE
; // suppress compilaer warning
4344 equal
= dt
.IsSameDate(dt2
);
4348 equal
= dt
.IsSameTime(dt2
);
4354 printf(" (ERROR: got back '%s' instead of '%s')\n",
4355 dt2
.Format().c_str(), dt
.Format().c_str());
4366 // test text -> wxDateTime conversion
4367 static void TestTimeParse()
4369 puts("\n*** wxDateTime parse test ***");
4371 struct ParseTestData
4378 static const ParseTestData parseTestDates
[] =
4380 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4381 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4384 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4386 const char *format
= parseTestDates
[n
].format
;
4388 printf("%s => ", format
);
4391 if ( dt
.ParseRfc822Date(format
) )
4393 printf("%s ", dt
.Format().c_str());
4395 if ( parseTestDates
[n
].good
)
4397 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4404 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4409 puts("(ERROR: bad format)");
4414 printf("bad format (%s)\n",
4415 parseTestDates
[n
].good
? "ERROR" : "ok");
4420 static void TestDateTimeInteractive()
4422 puts("\n*** interactive wxDateTime tests ***");
4428 printf("Enter a date: ");
4429 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4432 // kill the last '\n'
4433 buf
[strlen(buf
) - 1] = 0;
4436 const char *p
= dt
.ParseDate(buf
);
4439 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4445 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4448 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4449 dt
.Format("%b %d, %Y").c_str(),
4451 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4452 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4453 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4456 puts("\n*** done ***");
4459 static void TestTimeMS()
4461 puts("*** testing millisecond-resolution support in wxDateTime ***");
4463 wxDateTime dt1
= wxDateTime::Now(),
4464 dt2
= wxDateTime::UNow();
4466 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4467 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4468 printf("Dummy loop: ");
4469 for ( int i
= 0; i
< 6000; i
++ )
4471 //for ( int j = 0; j < 10; j++ )
4474 s
.Printf("%g", sqrt(i
));
4483 dt2
= wxDateTime::UNow();
4484 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4486 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4488 puts("\n*** done ***");
4491 static void TestTimeArithmetics()
4493 puts("\n*** testing arithmetic operations on wxDateTime ***");
4495 static const struct ArithmData
4497 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4498 : span(sp
), name(nam
) { }
4502 } testArithmData
[] =
4504 ArithmData(wxDateSpan::Day(), "day"),
4505 ArithmData(wxDateSpan::Week(), "week"),
4506 ArithmData(wxDateSpan::Month(), "month"),
4507 ArithmData(wxDateSpan::Year(), "year"),
4508 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4511 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4513 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4515 wxDateSpan span
= testArithmData
[n
].span
;
4519 const char *name
= testArithmData
[n
].name
;
4520 printf("%s + %s = %s, %s - %s = %s\n",
4521 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4522 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4524 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4525 if ( dt1
- span
== dt
)
4531 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4534 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4535 if ( dt2
+ span
== dt
)
4541 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4544 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4545 if ( dt2
+ 2*span
== dt1
)
4551 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4558 static void TestTimeHolidays()
4560 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4562 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4563 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4564 dtEnd
= dtStart
.GetLastMonthDay();
4566 wxDateTimeArray hol
;
4567 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4569 const wxChar
*format
= "%d-%b-%Y (%a)";
4571 printf("All holidays between %s and %s:\n",
4572 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4574 size_t count
= hol
.GetCount();
4575 for ( size_t n
= 0; n
< count
; n
++ )
4577 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4583 static void TestTimeZoneBug()
4585 puts("\n*** testing for DST/timezone bug ***\n");
4587 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4588 for ( int i
= 0; i
< 31; i
++ )
4590 printf("Date %s: week day %s.\n",
4591 date
.Format(_T("%d-%m-%Y")).c_str(),
4592 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4594 date
+= wxDateSpan::Day();
4600 static void TestTimeSpanFormat()
4602 puts("\n*** wxTimeSpan tests ***");
4604 static const char *formats
[] =
4606 _T("(default) %H:%M:%S"),
4607 _T("%E weeks and %D days"),
4608 _T("%l milliseconds"),
4609 _T("(with ms) %H:%M:%S:%l"),
4610 _T("100%% of minutes is %M"), // test "%%"
4611 _T("%D days and %H hours"),
4612 _T("or also %S seconds"),
4615 wxTimeSpan
ts1(1, 2, 3, 4),
4617 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4619 printf("ts1 = %s\tts2 = %s\n",
4620 ts1
.Format(formats
[n
]).c_str(),
4621 ts2
.Format(formats
[n
]).c_str());
4629 // test compatibility with the old wxDate/wxTime classes
4630 static void TestTimeCompatibility()
4632 puts("\n*** wxDateTime compatibility test ***");
4634 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4635 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4637 double jdnNow
= wxDateTime::Now().GetJDN();
4638 long jdnMidnight
= (long)(jdnNow
- 0.5);
4639 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4641 jdnMidnight
= wxDate().Set().GetJulianDate();
4642 printf("wxDateTime for today: %s\n",
4643 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4645 int flags
= wxEUROPEAN
;//wxFULL;
4648 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4649 for ( int n
= 0; n
< 7; n
++ )
4651 printf("Previous %s is %s\n",
4652 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4653 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4659 #endif // TEST_DATETIME
4661 // ----------------------------------------------------------------------------
4663 // ----------------------------------------------------------------------------
4667 #include "wx/thread.h"
4669 static size_t gs_counter
= (size_t)-1;
4670 static wxCriticalSection gs_critsect
;
4671 static wxSemaphore gs_cond
;
4673 class MyJoinableThread
: public wxThread
4676 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4677 { m_n
= n
; Create(); }
4679 // thread execution starts here
4680 virtual ExitCode
Entry();
4686 wxThread::ExitCode
MyJoinableThread::Entry()
4688 unsigned long res
= 1;
4689 for ( size_t n
= 1; n
< m_n
; n
++ )
4693 // it's a loooong calculation :-)
4697 return (ExitCode
)res
;
4700 class MyDetachedThread
: public wxThread
4703 MyDetachedThread(size_t n
, char ch
)
4707 m_cancelled
= FALSE
;
4712 // thread execution starts here
4713 virtual ExitCode
Entry();
4716 virtual void OnExit();
4719 size_t m_n
; // number of characters to write
4720 char m_ch
; // character to write
4722 bool m_cancelled
; // FALSE if we exit normally
4725 wxThread::ExitCode
MyDetachedThread::Entry()
4728 wxCriticalSectionLocker
lock(gs_critsect
);
4729 if ( gs_counter
== (size_t)-1 )
4735 for ( size_t n
= 0; n
< m_n
; n
++ )
4737 if ( TestDestroy() )
4747 wxThread::Sleep(100);
4753 void MyDetachedThread::OnExit()
4755 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4757 wxCriticalSectionLocker
lock(gs_critsect
);
4758 if ( !--gs_counter
&& !m_cancelled
)
4762 static void TestDetachedThreads()
4764 puts("\n*** Testing detached threads ***");
4766 static const size_t nThreads
= 3;
4767 MyDetachedThread
*threads
[nThreads
];
4769 for ( n
= 0; n
< nThreads
; n
++ )
4771 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4774 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4775 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4777 for ( n
= 0; n
< nThreads
; n
++ )
4782 // wait until all threads terminate
4788 static void TestJoinableThreads()
4790 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4792 // calc 10! in the background
4793 MyJoinableThread
thread(10);
4796 printf("\nThread terminated with exit code %lu.\n",
4797 (unsigned long)thread
.Wait());
4800 static void TestThreadSuspend()
4802 puts("\n*** Testing thread suspend/resume functions ***");
4804 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4808 // this is for this demo only, in a real life program we'd use another
4809 // condition variable which would be signaled from wxThread::Entry() to
4810 // tell us that the thread really started running - but here just wait a
4811 // bit and hope that it will be enough (the problem is, of course, that
4812 // the thread might still not run when we call Pause() which will result
4814 wxThread::Sleep(300);
4816 for ( size_t n
= 0; n
< 3; n
++ )
4820 puts("\nThread suspended");
4823 // don't sleep but resume immediately the first time
4824 wxThread::Sleep(300);
4826 puts("Going to resume the thread");
4831 puts("Waiting until it terminates now");
4833 // wait until the thread terminates
4839 static void TestThreadDelete()
4841 // As above, using Sleep() is only for testing here - we must use some
4842 // synchronisation object instead to ensure that the thread is still
4843 // running when we delete it - deleting a detached thread which already
4844 // terminated will lead to a crash!
4846 puts("\n*** Testing thread delete function ***");
4848 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4852 puts("\nDeleted a thread which didn't start to run yet.");
4854 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4858 wxThread::Sleep(300);
4862 puts("\nDeleted a running thread.");
4864 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4868 wxThread::Sleep(300);
4874 puts("\nDeleted a sleeping thread.");
4876 MyJoinableThread
thread3(20);
4881 puts("\nDeleted a joinable thread.");
4883 MyJoinableThread
thread4(2);
4886 wxThread::Sleep(300);
4890 puts("\nDeleted a joinable thread which already terminated.");
4895 class MyWaitingThread
: public wxThread
4898 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4901 m_condition
= condition
;
4906 virtual ExitCode
Entry()
4908 printf("Thread %lu has started running.\n", GetId());
4913 printf("Thread %lu starts to wait...\n", GetId());
4917 m_condition
->Wait();
4920 printf("Thread %lu finished to wait, exiting.\n", GetId());
4928 wxCondition
*m_condition
;
4931 static void TestThreadConditions()
4934 wxCondition
condition(mutex
);
4936 // otherwise its difficult to understand which log messages pertain to
4938 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4939 // condition.GetId(), gs_cond.GetId());
4941 // create and launch threads
4942 MyWaitingThread
*threads
[10];
4945 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4947 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4950 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4955 // wait until all threads run
4956 puts("Main thread is waiting for the other threads to start");
4959 size_t nRunning
= 0;
4960 while ( nRunning
< WXSIZEOF(threads
) )
4966 printf("Main thread: %u already running\n", nRunning
);
4970 puts("Main thread: all threads started up.");
4973 wxThread::Sleep(500);
4976 // now wake one of them up
4977 printf("Main thread: about to signal the condition.\n");
4982 wxThread::Sleep(200);
4984 // wake all the (remaining) threads up, so that they can exit
4985 printf("Main thread: about to broadcast the condition.\n");
4987 condition
.Broadcast();
4989 // give them time to terminate (dirty!)
4990 wxThread::Sleep(500);
4993 #include "wx/utils.h"
4995 class MyExecThread
: public wxThread
4998 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5004 virtual ExitCode
Entry()
5006 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5013 static void TestThreadExec()
5015 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5017 MyExecThread
thread(_T("true"));
5020 wxPrintf(_T("Main program exit code: %ld.\n"),
5021 wxExecute(_T("false"), wxEXEC_SYNC
));
5023 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5027 #include "wx/datetime.h"
5029 class MySemaphoreThread
: public wxThread
5032 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5033 : wxThread(wxTHREAD_JOINABLE
),
5040 virtual ExitCode
Entry()
5042 wxPrintf(_T("%s: Thread %d starting to wait for semaphore...\n"),
5043 wxDateTime::Now().FormatTime().c_str(), m_i
);
5047 wxPrintf(_T("%s: Thread %d acquired the semaphore.\n"),
5048 wxDateTime::Now().FormatTime().c_str(), m_i
);
5052 wxPrintf(_T("%s: Thread %d releasing the semaphore.\n"),
5053 wxDateTime::Now().FormatTime().c_str(), m_i
);
5065 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5067 static void TestSemaphore()
5069 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5071 static const int SEM_LIMIT
= 3;
5073 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5074 ArrayThreads threads
;
5076 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5078 threads
.Add(new MySemaphoreThread(i
, &sem
));
5079 threads
.Last()->Run();
5082 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5089 #endif // TEST_THREADS
5091 // ----------------------------------------------------------------------------
5093 // ----------------------------------------------------------------------------
5097 #include "wx/dynarray.h"
5099 typedef unsigned short ushort
;
5101 #define DefineCompare(name, T) \
5103 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5105 return first - second; \
5108 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5110 return *first - *second; \
5113 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5115 return *second - *first; \
5118 DefineCompare(UShort, ushort);
5119 DefineCompare(Int
, int);
5121 // test compilation of all macros
5122 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5123 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5124 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5125 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5127 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5128 #include "wx/arrimpl.cpp"
5129 WX_DEFINE_OBJARRAY(ArrayBars
);
5131 static void PrintArray(const char* name
, const wxArrayString
& array
)
5133 printf("Dump of the array '%s'\n", name
);
5135 size_t nCount
= array
.GetCount();
5136 for ( size_t n
= 0; n
< nCount
; n
++ )
5138 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5142 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5143 const wxString
& second
)
5145 return first
.length() - second
.length();
5148 #define TestArrayOf(name) \
5150 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5152 printf("Dump of the array '%s'\n", name); \
5154 size_t nCount = array.GetCount(); \
5155 for ( size_t n = 0; n < nCount; n++ ) \
5157 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5161 static void PrintArray(const char* name, const wxArray##name & array) \
5163 printf("Dump of the array '%s'\n", name); \
5165 size_t nCount = array.GetCount(); \
5166 for ( size_t n = 0; n < nCount; n++ ) \
5168 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5172 static void TestArrayOf ## name ## s() \
5174 printf("*** Testing wxArray%s ***\n", #name); \
5182 puts("Initially:"); \
5183 PrintArray("a", a); \
5185 puts("After sort:"); \
5186 a.Sort(name ## Compare); \
5187 PrintArray("a", a); \
5189 puts("After reverse sort:"); \
5190 a.Sort(name ## RevCompare); \
5191 PrintArray("a", a); \
5193 wxSortedArray##name b; \
5199 puts("Sorted array initially:"); \
5200 PrintArray("b", b); \
5203 TestArrayOf(UShort
);
5206 static void TestArrayOfObjects()
5208 puts("*** Testing wxObjArray ***\n");
5212 Bar
bar("second bar (two copies!)");
5214 printf("Initially: %u objects in the array, %u objects total.\n",
5215 bars
.GetCount(), Bar::GetNumber());
5217 bars
.Add(new Bar("first bar"));
5220 printf("Now: %u objects in the array, %u objects total.\n",
5221 bars
.GetCount(), Bar::GetNumber());
5223 bars
.RemoveAt(1, bars
.GetCount() - 1);
5225 printf("After removing all but first element: %u objects in the "
5226 "array, %u objects total.\n",
5227 bars
.GetCount(), Bar::GetNumber());
5231 printf("After Empty(): %u objects in the array, %u objects total.\n",
5232 bars
.GetCount(), Bar::GetNumber());
5235 printf("Finally: no more objects in the array, %u objects total.\n",
5239 #endif // TEST_ARRAYS
5241 // ----------------------------------------------------------------------------
5243 // ----------------------------------------------------------------------------
5247 #include "wx/timer.h"
5248 #include "wx/tokenzr.h"
5250 static void TestStringConstruction()
5252 puts("*** Testing wxString constructores ***");
5254 #define TEST_CTOR(args, res) \
5257 printf("wxString%s = %s ", #args, s.c_str()); \
5264 printf("(ERROR: should be %s)\n", res); \
5268 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5269 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5270 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5271 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5273 static const wxChar
*s
= _T("?really!");
5274 const wxChar
*start
= wxStrchr(s
, _T('r'));
5275 const wxChar
*end
= wxStrchr(s
, _T('!'));
5276 TEST_CTOR((start
, end
), _T("really"));
5281 static void TestString()
5291 for (int i
= 0; i
< 1000000; ++i
)
5295 c
= "! How'ya doin'?";
5298 c
= "Hello world! What's up?";
5303 printf ("TestString elapsed time: %ld\n", sw
.Time());
5306 static void TestPChar()
5314 for (int i
= 0; i
< 1000000; ++i
)
5316 strcpy (a
, "Hello");
5317 strcpy (b
, " world");
5318 strcpy (c
, "! How'ya doin'?");
5321 strcpy (c
, "Hello world! What's up?");
5322 if (strcmp (c
, a
) == 0)
5326 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5329 static void TestStringSub()
5331 wxString
s("Hello, world!");
5333 puts("*** Testing wxString substring extraction ***");
5335 printf("String = '%s'\n", s
.c_str());
5336 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5337 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5338 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5339 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5340 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5341 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5343 static const wxChar
*prefixes
[] =
5347 _T("Hello, world!"),
5348 _T("Hello, world!!!"),
5354 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5356 wxString prefix
= prefixes
[n
], rest
;
5357 bool rc
= s
.StartsWith(prefix
, &rest
);
5358 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5361 printf(" (the rest is '%s')\n", rest
.c_str());
5372 static void TestStringFormat()
5374 puts("*** Testing wxString formatting ***");
5377 s
.Printf("%03d", 18);
5379 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5380 printf("Number 18: %s\n", s
.c_str());
5385 // returns "not found" for npos, value for all others
5386 static wxString
PosToString(size_t res
)
5388 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5389 : wxString::Format(_T("%u"), res
);
5393 static void TestStringFind()
5395 puts("*** Testing wxString find() functions ***");
5397 static const wxChar
*strToFind
= _T("ell");
5398 static const struct StringFindTest
5402 result
; // of searching "ell" in str
5405 { _T("Well, hello world"), 0, 1 },
5406 { _T("Well, hello world"), 6, 7 },
5407 { _T("Well, hello world"), 9, wxString::npos
},
5410 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5412 const StringFindTest
& ft
= findTestData
[n
];
5413 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5415 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5416 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5418 size_t resTrue
= ft
.result
;
5419 if ( res
== resTrue
)
5425 printf(_T("(ERROR: should be %s)\n"),
5426 PosToString(resTrue
).c_str());
5433 static void TestStringTokenizer()
5435 puts("*** Testing wxStringTokenizer ***");
5437 static const wxChar
*modeNames
[] =
5441 _T("return all empty"),
5446 static const struct StringTokenizerTest
5448 const wxChar
*str
; // string to tokenize
5449 const wxChar
*delims
; // delimiters to use
5450 size_t count
; // count of token
5451 wxStringTokenizerMode mode
; // how should we tokenize it
5452 } tokenizerTestData
[] =
5454 { _T(""), _T(" "), 0 },
5455 { _T("Hello, world"), _T(" "), 2 },
5456 { _T("Hello, world "), _T(" "), 2 },
5457 { _T("Hello, world"), _T(","), 2 },
5458 { _T("Hello, world!"), _T(",!"), 2 },
5459 { _T("Hello,, world!"), _T(",!"), 3 },
5460 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5461 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5462 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5463 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5464 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5465 { _T("01/02/99"), _T("/-"), 3 },
5466 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5469 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5471 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5472 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5474 size_t count
= tkz
.CountTokens();
5475 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5476 MakePrintable(tt
.str
).c_str(),
5478 MakePrintable(tt
.delims
).c_str(),
5479 modeNames
[tkz
.GetMode()]);
5480 if ( count
== tt
.count
)
5486 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5491 // if we emulate strtok(), check that we do it correctly
5492 wxChar
*buf
, *s
= NULL
, *last
;
5494 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5496 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5497 wxStrcpy(buf
, tt
.str
);
5499 s
= wxStrtok(buf
, tt
.delims
, &last
);
5506 // now show the tokens themselves
5508 while ( tkz
.HasMoreTokens() )
5510 wxString token
= tkz
.GetNextToken();
5512 printf(_T("\ttoken %u: '%s'"),
5514 MakePrintable(token
).c_str());
5524 printf(" (ERROR: should be %s)\n", s
);
5527 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5531 // nothing to compare with
5536 if ( count2
!= count
)
5538 puts(_T("\tERROR: token count mismatch"));
5547 static void TestStringReplace()
5549 puts("*** Testing wxString::replace ***");
5551 static const struct StringReplaceTestData
5553 const wxChar
*original
; // original test string
5554 size_t start
, len
; // the part to replace
5555 const wxChar
*replacement
; // the replacement string
5556 const wxChar
*result
; // and the expected result
5557 } stringReplaceTestData
[] =
5559 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5560 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5561 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5562 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5563 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5566 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5568 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5570 wxString original
= data
.original
;
5571 original
.replace(data
.start
, data
.len
, data
.replacement
);
5573 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5574 data
.original
, data
.start
, data
.len
, data
.replacement
,
5577 if ( original
== data
.result
)
5583 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5590 static void TestStringMatch()
5592 wxPuts(_T("*** Testing wxString::Matches() ***"));
5594 static const struct StringMatchTestData
5597 const wxChar
*wildcard
;
5599 } stringMatchTestData
[] =
5601 { _T("foobar"), _T("foo*"), 1 },
5602 { _T("foobar"), _T("*oo*"), 1 },
5603 { _T("foobar"), _T("*bar"), 1 },
5604 { _T("foobar"), _T("??????"), 1 },
5605 { _T("foobar"), _T("f??b*"), 1 },
5606 { _T("foobar"), _T("f?b*"), 0 },
5607 { _T("foobar"), _T("*goo*"), 0 },
5608 { _T("foobar"), _T("*foo"), 0 },
5609 { _T("foobarfoo"), _T("*foo"), 1 },
5610 { _T(""), _T("*"), 1 },
5611 { _T(""), _T("?"), 0 },
5614 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5616 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5617 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5618 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5620 matches
? _T("matches") : _T("doesn't match"),
5622 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5628 #endif // TEST_STRINGS
5630 // ----------------------------------------------------------------------------
5632 // ----------------------------------------------------------------------------
5634 #ifdef TEST_SNGLINST
5635 #include "wx/snglinst.h"
5636 #endif // TEST_SNGLINST
5638 int main(int argc
, char **argv
)
5640 wxApp::CheckBuildOptions(wxBuildOptions());
5642 wxInitializer initializer
;
5645 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5650 #ifdef TEST_SNGLINST
5651 wxSingleInstanceChecker checker
;
5652 if ( checker
.Create(_T(".wxconsole.lock")) )
5654 if ( checker
.IsAnotherRunning() )
5656 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5661 // wait some time to give time to launch another instance
5662 wxPrintf(_T("Press \"Enter\" to continue..."));
5665 else // failed to create
5667 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5669 #endif // TEST_SNGLINST
5673 #endif // TEST_CHARSET
5676 TestCmdLineConvert();
5678 #if wxUSE_CMDLINE_PARSER
5679 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5681 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5682 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5683 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5684 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5686 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5687 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5688 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5689 wxCMD_LINE_VAL_NUMBER
},
5690 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5691 wxCMD_LINE_VAL_DATE
},
5693 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5694 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5699 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5701 parser
.AddOption("project_name", "", "full path to project file",
5702 wxCMD_LINE_VAL_STRING
,
5703 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5705 switch ( parser
.Parse() )
5708 wxLogMessage("Help was given, terminating.");
5712 ShowCmdLine(parser
);
5716 wxLogMessage("Syntax error detected, aborting.");
5719 #endif // wxUSE_CMDLINE_PARSER
5721 #endif // TEST_CMDLINE
5729 TestStringConstruction();
5732 TestStringTokenizer();
5733 TestStringReplace();
5739 #endif // TEST_STRINGS
5752 puts("*** Initially:");
5754 PrintArray("a1", a1
);
5756 wxArrayString
a2(a1
);
5757 PrintArray("a2", a2
);
5759 wxSortedArrayString
a3(a1
);
5760 PrintArray("a3", a3
);
5762 puts("*** After deleting three strings from a1");
5765 PrintArray("a1", a1
);
5766 PrintArray("a2", a2
);
5767 PrintArray("a3", a3
);
5769 puts("*** After reassigning a1 to a2 and a3");
5771 PrintArray("a2", a2
);
5772 PrintArray("a3", a3
);
5774 puts("*** After sorting a1");
5776 PrintArray("a1", a1
);
5778 puts("*** After sorting a1 in reverse order");
5780 PrintArray("a1", a1
);
5782 puts("*** After sorting a1 by the string length");
5783 a1
.Sort(StringLenCompare
);
5784 PrintArray("a1", a1
);
5786 TestArrayOfObjects();
5787 TestArrayOfUShorts();
5791 #endif // TEST_ARRAYS
5801 #ifdef TEST_DLLLOADER
5803 #endif // TEST_DLLLOADER
5807 #endif // TEST_ENVIRON
5811 #endif // TEST_EXECUTE
5813 #ifdef TEST_FILECONF
5815 #endif // TEST_FILECONF
5823 #endif // TEST_LOCALE
5827 for ( size_t n
= 0; n
< 8000; n
++ )
5829 s
<< (char)('A' + (n
% 26));
5833 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5835 // this one shouldn't be truncated
5838 // but this one will because log functions use fixed size buffer
5839 // (note that it doesn't need '\n' at the end neither - will be added
5841 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5853 #ifdef TEST_FILENAME
5857 fn
.Assign("c:\\foo", "bar.baz");
5858 fn
.Assign("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc");
5865 TestFileNameConstruction();
5866 TestFileNameMakeRelative();
5867 TestFileNameSplit();
5870 TestFileNameComparison();
5871 TestFileNameOperations();
5873 #endif // TEST_FILENAME
5875 #ifdef TEST_FILETIME
5879 #endif // TEST_FILETIME
5882 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5883 if ( TestFtpConnect() )
5894 if ( TEST_INTERACTIVE
)
5895 TestFtpInteractive();
5897 //else: connecting to the FTP server failed
5903 #ifdef TEST_LONGLONG
5904 // seed pseudo random generator
5905 srand((unsigned)time(NULL
));
5914 TestMultiplication();
5917 TestLongLongConversion();
5918 TestBitOperations();
5919 TestLongLongComparison();
5920 TestLongLongPrint();
5922 #endif // TEST_LONGLONG
5930 #endif // TEST_HASHMAP
5933 wxLog::AddTraceMask(_T("mime"));
5941 TestMimeAssociate();
5944 #ifdef TEST_INFO_FUNCTIONS
5950 if ( TEST_INTERACTIVE
)
5953 #endif // TEST_INFO_FUNCTIONS
5955 #ifdef TEST_PATHLIST
5957 #endif // TEST_PATHLIST
5965 #endif // TEST_REGCONF
5968 // TODO: write a real test using src/regex/tests file
5973 TestRegExSubmatch();
5974 TestRegExReplacement();
5976 if ( TEST_INTERACTIVE
)
5977 TestRegExInteractive();
5979 #endif // TEST_REGEX
5981 #ifdef TEST_REGISTRY
5983 TestRegistryAssociation();
5984 #endif // TEST_REGISTRY
5989 #endif // TEST_SOCKETS
5994 #endif // TEST_STREAMS
5997 int nCPUs
= wxThread::GetCPUCount();
5998 printf("This system has %d CPUs\n", nCPUs
);
6000 wxThread::SetConcurrency(nCPUs
);
6004 TestDetachedThreads();
6005 TestJoinableThreads();
6006 TestThreadSuspend();
6008 TestThreadConditions();
6013 #endif // TEST_THREADS
6017 #endif // TEST_TIMER
6019 #ifdef TEST_DATETIME
6032 TestTimeArithmetics();
6035 TestTimeSpanFormat();
6041 if ( TEST_INTERACTIVE
)
6042 TestDateTimeInteractive();
6043 #endif // TEST_DATETIME
6046 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6048 #endif // TEST_USLEEP
6053 #endif // TEST_VCARD
6057 #endif // TEST_VOLUME
6061 TestEncodingConverter();
6062 #endif // TEST_WCHAR
6065 TestZipStreamRead();
6066 TestZipFileSystem();
6070 TestZlibStreamWrite();
6071 TestZlibStreamRead();