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 wxString cwd
= wxGetCwd();
311 if ( wxDir::Exists(cwd
) )
313 printf("ERROR: current directory '%s' doesn't exist?\n", cwd
.c_str());
318 if ( !dir
.IsOpened() )
320 printf("ERROR: failed to open current directory '%s'.\n", cwd
.c_str());
324 puts("Enumerating everything in current directory:");
325 TestDirEnumHelper(dir
);
327 puts("Enumerating really everything in current directory:");
328 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
330 puts("Enumerating object files in current directory:");
331 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
333 puts("Enumerating directories in current directory:");
334 TestDirEnumHelper(dir
, wxDIR_DIRS
);
336 puts("Enumerating files in current directory:");
337 TestDirEnumHelper(dir
, wxDIR_FILES
);
339 puts("Enumerating files including hidden in current directory:");
340 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
344 puts("Enumerating everything in root directory:");
345 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
347 puts("Enumerating directories in root directory:");
348 TestDirEnumHelper(dir
, wxDIR_DIRS
);
350 puts("Enumerating files in root directory:");
351 TestDirEnumHelper(dir
, wxDIR_FILES
);
353 puts("Enumerating files including hidden in root directory:");
354 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
356 puts("Enumerating files in non existing directory:");
357 wxDir
dirNo("nosuchdir");
358 TestDirEnumHelper(dirNo
);
361 class DirPrintTraverser
: public wxDirTraverser
364 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
366 return wxDIR_CONTINUE
;
369 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
371 wxString path
, name
, ext
;
372 wxSplitPath(dirname
, &path
, &name
, &ext
);
375 name
<< _T('.') << ext
;
378 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
380 if ( wxIsPathSeparator(*p
) )
384 printf("%s%s\n", indent
.c_str(), name
.c_str());
386 return wxDIR_CONTINUE
;
390 static void TestDirTraverse()
392 puts("*** Testing wxDir::Traverse() ***");
396 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
397 printf("There are %u files under '%s'\n", n
, TESTDIR
);
400 printf("First one is '%s'\n", files
[0u].c_str());
401 printf(" last one is '%s'\n", files
[n
- 1].c_str());
404 // enum again with custom traverser
406 DirPrintTraverser traverser
;
407 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
410 static void TestDirExists()
412 wxPuts(_T("*** Testing wxDir::Exists() ***"));
414 static const char *dirnames
[] =
417 #if defined(__WXMSW__)
420 _T("\\\\share\\file"),
424 _T("c:\\autoexec.bat"),
425 #elif defined(__UNIX__)
434 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
436 printf(_T("%-40s: %s\n"),
438 wxDir::Exists(dirnames
[n
]) ? _T("exists") : _T("doesn't exist"));
444 // ----------------------------------------------------------------------------
446 // ----------------------------------------------------------------------------
448 #ifdef TEST_DLLLOADER
450 #include "wx/dynlib.h"
452 static void TestDllLoad()
454 #if defined(__WXMSW__)
455 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
456 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
457 #elif defined(__UNIX__)
458 // weird: using just libc.so does *not* work!
459 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
460 static const wxChar
*FUNC_NAME
= _T("strlen");
462 #error "don't know how to test wxDllLoader on this platform"
465 puts("*** testing wxDllLoader ***\n");
467 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
470 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
474 typedef int (*strlenType
)(const char *);
475 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
478 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
479 FUNC_NAME
, LIB_NAME
);
483 if ( pfnStrlen("foo") != 3 )
485 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
493 wxDllLoader::UnloadLibrary(dllHandle
);
497 #endif // TEST_DLLLOADER
499 // ----------------------------------------------------------------------------
501 // ----------------------------------------------------------------------------
505 #include "wx/utils.h"
507 static wxString
MyGetEnv(const wxString
& var
)
510 if ( !wxGetEnv(var
, &val
) )
513 val
= wxString(_T('\'')) + val
+ _T('\'');
518 static void TestEnvironment()
520 const wxChar
*var
= _T("wxTestVar");
522 puts("*** testing environment access functions ***");
524 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
525 wxSetEnv(var
, _T("value for wxTestVar"));
526 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
527 wxSetEnv(var
, _T("another value"));
528 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
530 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
531 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
534 #endif // TEST_ENVIRON
536 // ----------------------------------------------------------------------------
538 // ----------------------------------------------------------------------------
542 #include "wx/utils.h"
544 static void TestExecute()
546 puts("*** testing wxExecute ***");
549 #define COMMAND "cat -n ../../Makefile" // "echo hi"
550 #define SHELL_COMMAND "echo hi from shell"
551 #define REDIRECT_COMMAND COMMAND // "date"
552 #elif defined(__WXMSW__)
553 #define COMMAND "command.com -c 'echo hi'"
554 #define SHELL_COMMAND "echo hi"
555 #define REDIRECT_COMMAND COMMAND
557 #error "no command to exec"
560 printf("Testing wxShell: ");
562 if ( wxShell(SHELL_COMMAND
) )
567 printf("Testing wxExecute: ");
569 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
574 #if 0 // no, it doesn't work (yet?)
575 printf("Testing async wxExecute: ");
577 if ( wxExecute(COMMAND
) != 0 )
578 puts("Ok (command launched).");
583 printf("Testing wxExecute with redirection:\n");
584 wxArrayString output
;
585 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
591 size_t count
= output
.GetCount();
592 for ( size_t n
= 0; n
< count
; n
++ )
594 printf("\t%s\n", output
[n
].c_str());
601 #endif // TEST_EXECUTE
603 // ----------------------------------------------------------------------------
605 // ----------------------------------------------------------------------------
610 #include "wx/ffile.h"
611 #include "wx/textfile.h"
613 static void TestFileRead()
615 puts("*** wxFile read test ***");
617 wxFile
file(_T("testdata.fc"));
618 if ( file
.IsOpened() )
620 printf("File length: %lu\n", file
.Length());
622 puts("File dump:\n----------");
624 static const off_t len
= 1024;
628 off_t nRead
= file
.Read(buf
, len
);
629 if ( nRead
== wxInvalidOffset
)
631 printf("Failed to read the file.");
635 fwrite(buf
, nRead
, 1, stdout
);
645 printf("ERROR: can't open test file.\n");
651 static void TestTextFileRead()
653 puts("*** wxTextFile read test ***");
655 wxTextFile
file(_T("testdata.fc"));
658 printf("Number of lines: %u\n", file
.GetLineCount());
659 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
663 puts("\nDumping the entire file:");
664 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
666 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
668 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
670 puts("\nAnd now backwards:");
671 for ( s
= file
.GetLastLine();
672 file
.GetCurrentLine() != 0;
673 s
= file
.GetPrevLine() )
675 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
677 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
681 printf("ERROR: can't open '%s'\n", file
.GetName());
687 static void TestFileCopy()
689 puts("*** Testing wxCopyFile ***");
691 static const wxChar
*filename1
= _T("testdata.fc");
692 static const wxChar
*filename2
= _T("test2");
693 if ( !wxCopyFile(filename1
, filename2
) )
695 puts("ERROR: failed to copy file");
699 wxFFile
f1(filename1
, "rb"),
702 if ( !f1
.IsOpened() || !f2
.IsOpened() )
704 puts("ERROR: failed to open file(s)");
709 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
711 puts("ERROR: failed to read file(s)");
715 if ( (s1
.length() != s2
.length()) ||
716 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
718 puts("ERROR: copy error!");
722 puts("File was copied ok.");
728 if ( !wxRemoveFile(filename2
) )
730 puts("ERROR: failed to remove the file");
738 // ----------------------------------------------------------------------------
740 // ----------------------------------------------------------------------------
744 #include "wx/confbase.h"
745 #include "wx/fileconf.h"
747 static const struct FileConfTestData
749 const wxChar
*name
; // value name
750 const wxChar
*value
; // the value from the file
753 { _T("value1"), _T("one") },
754 { _T("value2"), _T("two") },
755 { _T("novalue"), _T("default") },
758 static void TestFileConfRead()
760 puts("*** testing wxFileConfig loading/reading ***");
762 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
763 _T("testdata.fc"), wxEmptyString
,
764 wxCONFIG_USE_RELATIVE_PATH
);
766 // test simple reading
767 puts("\nReading config file:");
768 wxString
defValue(_T("default")), value
;
769 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
771 const FileConfTestData
& data
= fcTestData
[n
];
772 value
= fileconf
.Read(data
.name
, defValue
);
773 printf("\t%s = %s ", data
.name
, value
.c_str());
774 if ( value
== data
.value
)
780 printf("(ERROR: should be %s)\n", data
.value
);
784 // test enumerating the entries
785 puts("\nEnumerating all root entries:");
788 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
791 printf("\t%s = %s\n",
793 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
795 cont
= fileconf
.GetNextEntry(name
, dummy
);
799 #endif // TEST_FILECONF
801 // ----------------------------------------------------------------------------
803 // ----------------------------------------------------------------------------
807 #include "wx/filename.h"
809 static void DumpFileName(const wxFileName
& fn
)
811 wxString full
= fn
.GetFullPath();
813 wxString vol
, path
, name
, ext
;
814 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
816 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
817 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
819 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
820 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
821 path
.c_str(), name
.c_str(), ext
.c_str());
823 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
824 wxPrintf(_T("with volume: \t'%s'\n"),
825 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
826 wxPrintf(_T("with separator:\t'%s'\n"),
827 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
828 wxPrintf(_T("with both: \t'%s'\n"),
829 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
831 wxPuts(_T("The directories in the path are:"));
832 wxArrayString dirs
= fn
.GetDirs();
833 size_t count
= dirs
.GetCount();
834 for ( size_t n
= 0; n
< count
; n
++ )
836 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
840 static struct FileNameInfo
842 const wxChar
*fullname
;
843 const wxChar
*volume
;
852 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
853 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
854 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
855 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
856 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
857 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
858 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
859 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
860 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
862 // Windows file names
863 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
864 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
865 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
866 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
867 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
868 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
869 { _T("\\\\server\\dir\\foo.bar"), _T("server"), _T("\\dir"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
871 // wxFileName support for Mac file names is broken currently
874 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
875 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
876 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
877 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
878 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
879 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
883 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
884 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
887 static void TestFileNameConstruction()
889 puts("*** testing wxFileName construction ***");
891 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
893 const FileNameInfo
& fni
= filenames
[n
];
895 wxFileName
fn(fni
.fullname
, fni
.format
);
897 wxString fullname
= fn
.GetFullPath(fni
.format
);
898 if ( fullname
!= fni
.fullname
)
900 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
903 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
904 printf("'%s' is %s (%s)\n\t",
906 isAbsolute
? "absolute" : "relative",
907 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
909 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
911 puts("ERROR (couldn't be normalized)");
915 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
922 static void TestFileNameSplit()
924 puts("*** testing wxFileName splitting ***");
926 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
928 const FileNameInfo
& fni
= filenames
[n
];
929 wxString volume
, path
, name
, ext
;
930 wxFileName::SplitPath(fni
.fullname
,
931 &volume
, &path
, &name
, &ext
, fni
.format
);
933 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
935 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
937 if ( volume
!= fni
.volume
)
938 printf(" (ERROR: volume = '%s')", fni
.volume
);
939 if ( path
!= fni
.path
)
940 printf(" (ERROR: path = '%s')", fni
.path
);
941 if ( name
!= fni
.name
)
942 printf(" (ERROR: name = '%s')", fni
.name
);
943 if ( ext
!= fni
.ext
)
944 printf(" (ERROR: ext = '%s')", fni
.ext
);
950 static void TestFileNameTemp()
952 puts("*** testing wxFileName temp file creation ***");
954 static const char *tmpprefixes
[] =
962 "/tmp/foo/bar", // this one must be an error
966 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
968 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
971 // "error" is not in upper case because it may be ok
972 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
976 printf("Prefix '%s'\t-> temp file '%s'\n",
977 tmpprefixes
[n
], path
.c_str());
979 if ( !wxRemoveFile(path
) )
981 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
987 static void TestFileNameMakeRelative()
989 puts("*** testing wxFileName::MakeRelativeTo() ***");
991 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
993 const FileNameInfo
& fni
= filenames
[n
];
995 wxFileName
fn(fni
.fullname
, fni
.format
);
997 // choose the base dir of the same format
999 switch ( fni
.format
)
1011 // TODO: I don't know how this is supposed to work there
1014 case wxPATH_NATIVE
: // make gcc happy
1016 wxFAIL_MSG( "unexpected path format" );
1019 printf("'%s' relative to '%s': ",
1020 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
1022 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
1028 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
1033 static void TestFileNameComparison()
1038 static void TestFileNameOperations()
1043 static void TestFileNameCwd()
1048 #endif // TEST_FILENAME
1050 // ----------------------------------------------------------------------------
1051 // wxFileName time functions
1052 // ----------------------------------------------------------------------------
1054 #ifdef TEST_FILETIME
1056 #include <wx/filename.h>
1057 #include <wx/datetime.h>
1059 static void TestFileGetTimes()
1061 wxFileName
fn(_T("testdata.fc"));
1063 wxDateTime dtAccess
, dtMod
, dtCreate
;
1064 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1066 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1070 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1072 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1073 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1074 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1075 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1079 static void TestFileSetTimes()
1081 wxFileName
fn(_T("testdata.fc"));
1085 wxPrintf(_T("ERROR: Touch() failed.\n"));
1089 #endif // TEST_FILETIME
1091 // ----------------------------------------------------------------------------
1093 // ----------------------------------------------------------------------------
1097 #include "wx/hash.h"
1101 Foo(int n_
) { n
= n_
; count
++; }
1106 static size_t count
;
1109 size_t Foo::count
= 0;
1111 WX_DECLARE_LIST(Foo
, wxListFoos
);
1112 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1114 #include "wx/listimpl.cpp"
1116 WX_DEFINE_LIST(wxListFoos
);
1118 static void TestHash()
1120 puts("*** Testing wxHashTable ***\n");
1124 hash
.DeleteContents(TRUE
);
1126 printf("Hash created: %u foos in hash, %u foos totally\n",
1127 hash
.GetCount(), Foo::count
);
1129 static const int hashTestData
[] =
1131 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1135 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1137 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1140 printf("Hash filled: %u foos in hash, %u foos totally\n",
1141 hash
.GetCount(), Foo::count
);
1143 puts("Hash access test:");
1144 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1146 printf("\tGetting element with key %d, value %d: ",
1147 hashTestData
[n
], n
);
1148 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1151 printf("ERROR, not found.\n");
1155 printf("%d (%s)\n", foo
->n
,
1156 (size_t)foo
->n
== n
? "ok" : "ERROR");
1160 printf("\nTrying to get an element not in hash: ");
1162 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1164 puts("ERROR: found!");
1168 puts("ok (not found)");
1172 printf("Hash destroyed: %u foos left\n", Foo::count
);
1177 // ----------------------------------------------------------------------------
1179 // ----------------------------------------------------------------------------
1183 #include "wx/hashmap.h"
1185 // test compilation of basic map types
1186 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1187 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1188 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1189 myUnsignedHashMap
);
1190 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1192 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1194 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1196 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1200 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1201 // myStringHashMap );
1202 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1204 typedef myStringHashMap::iterator Itor
;
1206 static void TestHashMap()
1208 puts("*** Testing wxHashMap ***\n");
1209 myStringHashMap
sh(0); // as small as possible
1212 const size_t count
= 10000;
1214 // init with some data
1215 for( i
= 0; i
< count
; ++i
)
1217 buf
.Printf(wxT("%d"), i
);
1218 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1221 // test that insertion worked
1222 if( sh
.size() != count
)
1224 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1227 for( i
= 0; i
< count
; ++i
)
1229 buf
.Printf(wxT("%d"), i
);
1230 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1232 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1237 // check that iterators work
1239 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1243 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1247 if( it
->second
!= sh
[it
->first
] )
1249 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1254 if( sh
.size() != i
)
1256 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1259 // test copy ctor, assignment operator
1260 myStringHashMap
h1( sh
), h2( 0 );
1263 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1265 if( h1
[it
->first
] != it
->second
)
1267 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1270 if( h2
[it
->first
] != it
->second
)
1272 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1277 for( i
= 0; i
< count
; ++i
)
1279 buf
.Printf(wxT("%d"), i
);
1280 size_t sz
= sh
.size();
1282 // test find() and erase(it)
1285 it
= sh
.find( buf
);
1286 if( it
!= sh
.end() )
1290 if( sh
.find( buf
) != sh
.end() )
1292 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1296 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1301 size_t c
= sh
.erase( buf
);
1303 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1305 if( sh
.find( buf
) != sh
.end() )
1307 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1311 // count should decrease
1312 if( sh
.size() != sz
- 1 )
1314 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1318 printf("*** Finished testing wxHashMap ***\n");
1321 #endif // TEST_HASHMAP
1323 // ----------------------------------------------------------------------------
1325 // ----------------------------------------------------------------------------
1329 #include "wx/list.h"
1331 WX_DECLARE_LIST(Bar
, wxListBars
);
1332 #include "wx/listimpl.cpp"
1333 WX_DEFINE_LIST(wxListBars
);
1335 static void TestListCtor()
1337 puts("*** Testing wxList construction ***\n");
1341 list1
.Append(new Bar(_T("first")));
1342 list1
.Append(new Bar(_T("second")));
1344 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1345 list1
.GetCount(), Bar::GetNumber());
1350 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1351 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1353 list1
.DeleteContents(TRUE
);
1356 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1361 // ----------------------------------------------------------------------------
1363 // ----------------------------------------------------------------------------
1367 #include "wx/intl.h"
1368 #include "wx/utils.h" // for wxSetEnv
1370 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1372 // find the name of the language from its value
1373 static const char *GetLangName(int lang
)
1375 static const char *languageNames
[] =
1396 "ARABIC_SAUDI_ARABIA",
1421 "CHINESE_SIMPLIFIED",
1422 "CHINESE_TRADITIONAL",
1425 "CHINESE_SINGAPORE",
1436 "ENGLISH_AUSTRALIA",
1440 "ENGLISH_CARIBBEAN",
1444 "ENGLISH_NEW_ZEALAND",
1445 "ENGLISH_PHILIPPINES",
1446 "ENGLISH_SOUTH_AFRICA",
1458 "FRENCH_LUXEMBOURG",
1467 "GERMAN_LIECHTENSTEIN",
1468 "GERMAN_LUXEMBOURG",
1509 "MALAY_BRUNEI_DARUSSALAM",
1521 "NORWEGIAN_NYNORSK",
1528 "PORTUGUESE_BRAZILIAN",
1553 "SPANISH_ARGENTINA",
1557 "SPANISH_COSTA_RICA",
1558 "SPANISH_DOMINICAN_REPUBLIC",
1560 "SPANISH_EL_SALVADOR",
1561 "SPANISH_GUATEMALA",
1565 "SPANISH_NICARAGUA",
1569 "SPANISH_PUERTO_RICO",
1572 "SPANISH_VENEZUELA",
1609 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1610 return languageNames
[lang
];
1615 static void TestDefaultLang()
1617 puts("*** Testing wxLocale::GetSystemLanguage ***");
1619 static const wxChar
*langStrings
[] =
1621 NULL
, // system default
1628 _T("de_DE.iso88591"),
1630 _T("?"), // invalid lang spec
1631 _T("klingonese"), // I bet on some systems it does exist...
1634 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1635 wxLocale::GetSystemEncodingName().c_str(),
1636 wxLocale::GetSystemEncoding());
1638 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1640 const char *langStr
= langStrings
[n
];
1643 // FIXME: this doesn't do anything at all under Windows, we need
1644 // to create a new wxLocale!
1645 wxSetEnv(_T("LC_ALL"), langStr
);
1648 int lang
= gs_localeDefault
.GetSystemLanguage();
1649 printf("Locale for '%s' is %s.\n",
1650 langStr
? langStr
: "system default", GetLangName(lang
));
1654 #endif // TEST_LOCALE
1656 // ----------------------------------------------------------------------------
1658 // ----------------------------------------------------------------------------
1662 #include "wx/mimetype.h"
1664 static void TestMimeEnum()
1666 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1668 wxArrayString mimetypes
;
1670 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1672 printf("*** All %u known filetypes: ***\n", count
);
1677 for ( size_t n
= 0; n
< count
; n
++ )
1679 wxFileType
*filetype
=
1680 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1683 printf("nothing known about the filetype '%s'!\n",
1684 mimetypes
[n
].c_str());
1688 filetype
->GetDescription(&desc
);
1689 filetype
->GetExtensions(exts
);
1691 filetype
->GetIcon(NULL
);
1694 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1697 extsAll
<< _T(", ");
1701 printf("\t%s: %s (%s)\n",
1702 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1708 static void TestMimeOverride()
1710 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1712 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1713 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1715 if ( wxFile::Exists(mailcap
) )
1716 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1718 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1720 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1723 if ( wxFile::Exists(mimetypes
) )
1724 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1726 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1728 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1734 static void TestMimeFilename()
1736 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1738 static const wxChar
*filenames
[] =
1746 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1748 const wxString fname
= filenames
[n
];
1749 wxString ext
= fname
.AfterLast(_T('.'));
1750 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1753 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1758 if ( !ft
->GetDescription(&desc
) )
1759 desc
= _T("<no description>");
1762 if ( !ft
->GetOpenCommand(&cmd
,
1763 wxFileType::MessageParameters(fname
, _T(""))) )
1764 cmd
= _T("<no command available>");
1766 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1767 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1776 static void TestMimeAssociate()
1778 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1780 wxFileTypeInfo
ftInfo(
1781 _T("application/x-xyz"),
1782 _T("xyzview '%s'"), // open cmd
1783 _T(""), // print cmd
1784 _T("XYZ File"), // description
1785 _T(".xyz"), // extensions
1786 NULL
// end of extensions
1788 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1790 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1793 wxPuts(_T("ERROR: failed to create association!"));
1797 // TODO: read it back
1806 // ----------------------------------------------------------------------------
1807 // misc information functions
1808 // ----------------------------------------------------------------------------
1810 #ifdef TEST_INFO_FUNCTIONS
1812 #include "wx/utils.h"
1814 static void TestDiskInfo()
1816 puts("*** Testing wxGetDiskSpace() ***");
1821 printf("\nEnter a directory name: ");
1822 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1825 // kill the last '\n'
1826 pathname
[strlen(pathname
) - 1] = 0;
1828 wxLongLong total
, free
;
1829 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1831 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1835 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1836 (total
/ 1024).ToString().c_str(),
1837 (free
/ 1024).ToString().c_str(),
1843 static void TestOsInfo()
1845 puts("*** Testing OS info functions ***\n");
1848 wxGetOsVersion(&major
, &minor
);
1849 printf("Running under: %s, version %d.%d\n",
1850 wxGetOsDescription().c_str(), major
, minor
);
1852 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1854 printf("Host name is %s (%s).\n",
1855 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1860 static void TestUserInfo()
1862 puts("*** Testing user info functions ***\n");
1864 printf("User id is:\t%s\n", wxGetUserId().c_str());
1865 printf("User name is:\t%s\n", wxGetUserName().c_str());
1866 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1867 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1872 #endif // TEST_INFO_FUNCTIONS
1874 // ----------------------------------------------------------------------------
1876 // ----------------------------------------------------------------------------
1878 #ifdef TEST_LONGLONG
1880 #include "wx/longlong.h"
1881 #include "wx/timer.h"
1883 // make a 64 bit number from 4 16 bit ones
1884 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1886 // get a random 64 bit number
1887 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1889 static const long testLongs
[] =
1900 #if wxUSE_LONGLONG_WX
1901 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1902 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1903 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1904 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1905 #endif // wxUSE_LONGLONG_WX
1907 static void TestSpeed()
1909 static const long max
= 100000000;
1916 for ( n
= 0; n
< max
; n
++ )
1921 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1924 #if wxUSE_LONGLONG_NATIVE
1929 for ( n
= 0; n
< max
; n
++ )
1934 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1936 #endif // wxUSE_LONGLONG_NATIVE
1942 for ( n
= 0; n
< max
; n
++ )
1947 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1951 static void TestLongLongConversion()
1953 puts("*** Testing wxLongLong conversions ***\n");
1957 for ( size_t n
= 0; n
< 100000; n
++ )
1961 #if wxUSE_LONGLONG_NATIVE
1962 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1964 wxASSERT_MSG( a
== b
, "conversions failure" );
1966 puts("Can't do it without native long long type, test skipped.");
1969 #endif // wxUSE_LONGLONG_NATIVE
1971 if ( !(nTested
% 1000) )
1983 static void TestMultiplication()
1985 puts("*** Testing wxLongLong multiplication ***\n");
1989 for ( size_t n
= 0; n
< 100000; n
++ )
1994 #if wxUSE_LONGLONG_NATIVE
1995 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1996 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1998 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1999 #else // !wxUSE_LONGLONG_NATIVE
2000 puts("Can't do it without native long long type, test skipped.");
2003 #endif // wxUSE_LONGLONG_NATIVE
2005 if ( !(nTested
% 1000) )
2017 static void TestDivision()
2019 puts("*** Testing wxLongLong division ***\n");
2023 for ( size_t n
= 0; n
< 100000; n
++ )
2025 // get a random wxLongLong (shifting by 12 the MSB ensures that the
2026 // multiplication will not overflow)
2027 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
2029 // get a random (but non null) long (not wxLongLong for now) to divide
2041 #if wxUSE_LONGLONG_NATIVE
2042 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
2044 wxLongLongNative p
= m
/ l
, s
= m
% l
;
2045 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
2046 #else // !wxUSE_LONGLONG_NATIVE
2047 // verify the result
2048 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
2049 #endif // wxUSE_LONGLONG_NATIVE
2051 if ( !(nTested
% 1000) )
2063 static void TestAddition()
2065 puts("*** Testing wxLongLong addition ***\n");
2069 for ( size_t n
= 0; n
< 100000; n
++ )
2075 #if wxUSE_LONGLONG_NATIVE
2076 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2077 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2078 "addition failure" );
2079 #else // !wxUSE_LONGLONG_NATIVE
2080 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2081 #endif // wxUSE_LONGLONG_NATIVE
2083 if ( !(nTested
% 1000) )
2095 static void TestBitOperations()
2097 puts("*** Testing wxLongLong bit operation ***\n");
2101 for ( size_t n
= 0; n
< 100000; n
++ )
2105 #if wxUSE_LONGLONG_NATIVE
2106 for ( size_t n
= 0; n
< 33; n
++ )
2109 #else // !wxUSE_LONGLONG_NATIVE
2110 puts("Can't do it without native long long type, test skipped.");
2113 #endif // wxUSE_LONGLONG_NATIVE
2115 if ( !(nTested
% 1000) )
2127 static void TestLongLongComparison()
2129 #if wxUSE_LONGLONG_WX
2130 puts("*** Testing wxLongLong comparison ***\n");
2132 static const long ls
[2] =
2138 wxLongLongWx lls
[2];
2142 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2146 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2148 res
= lls
[m
] > testLongs
[n
];
2149 printf("0x%lx > 0x%lx is %s (%s)\n",
2150 ls
[m
], testLongs
[n
], res
? "true" : "false",
2151 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2153 res
= lls
[m
] < testLongs
[n
];
2154 printf("0x%lx < 0x%lx is %s (%s)\n",
2155 ls
[m
], testLongs
[n
], res
? "true" : "false",
2156 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2158 res
= lls
[m
] == testLongs
[n
];
2159 printf("0x%lx == 0x%lx is %s (%s)\n",
2160 ls
[m
], testLongs
[n
], res
? "true" : "false",
2161 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2164 #endif // wxUSE_LONGLONG_WX
2167 static void TestLongLongPrint()
2169 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2171 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2173 wxLongLong ll
= testLongs
[n
];
2174 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2177 wxLongLong
ll(0x12345678, 0x87654321);
2178 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2181 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2187 #endif // TEST_LONGLONG
2189 // ----------------------------------------------------------------------------
2191 // ----------------------------------------------------------------------------
2193 #ifdef TEST_PATHLIST
2195 static void TestPathList()
2197 puts("*** Testing wxPathList ***\n");
2199 wxPathList pathlist
;
2200 pathlist
.AddEnvList("PATH");
2201 wxString path
= pathlist
.FindValidPath("ls");
2204 printf("ERROR: command not found in the path.\n");
2208 printf("Command found in the path as '%s'.\n", path
.c_str());
2212 #endif // TEST_PATHLIST
2214 // ----------------------------------------------------------------------------
2215 // regular expressions
2216 // ----------------------------------------------------------------------------
2220 #include "wx/regex.h"
2222 static void TestRegExCompile()
2224 wxPuts(_T("*** Testing RE compilation ***\n"));
2226 static struct RegExCompTestData
2228 const wxChar
*pattern
;
2230 } regExCompTestData
[] =
2232 { _T("foo"), TRUE
},
2233 { _T("foo("), FALSE
},
2234 { _T("foo(bar"), FALSE
},
2235 { _T("foo(bar)"), TRUE
},
2236 { _T("foo["), FALSE
},
2237 { _T("foo[bar"), FALSE
},
2238 { _T("foo[bar]"), TRUE
},
2239 { _T("foo{"), TRUE
},
2240 { _T("foo{1"), FALSE
},
2241 { _T("foo{bar"), TRUE
},
2242 { _T("foo{1}"), TRUE
},
2243 { _T("foo{1,2}"), TRUE
},
2244 { _T("foo{bar}"), TRUE
},
2245 { _T("foo*"), TRUE
},
2246 { _T("foo**"), FALSE
},
2247 { _T("foo+"), TRUE
},
2248 { _T("foo++"), FALSE
},
2249 { _T("foo?"), TRUE
},
2250 { _T("foo??"), FALSE
},
2251 { _T("foo?+"), FALSE
},
2255 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2257 const RegExCompTestData
& data
= regExCompTestData
[n
];
2258 bool ok
= re
.Compile(data
.pattern
);
2260 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2262 ok
? _T("") : _T("not "),
2263 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2267 static void TestRegExMatch()
2269 wxPuts(_T("*** Testing RE matching ***\n"));
2271 static struct RegExMatchTestData
2273 const wxChar
*pattern
;
2276 } regExMatchTestData
[] =
2278 { _T("foo"), _T("bar"), FALSE
},
2279 { _T("foo"), _T("foobar"), TRUE
},
2280 { _T("^foo"), _T("foobar"), TRUE
},
2281 { _T("^foo"), _T("barfoo"), FALSE
},
2282 { _T("bar$"), _T("barbar"), TRUE
},
2283 { _T("bar$"), _T("barbar "), FALSE
},
2286 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2288 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2290 wxRegEx
re(data
.pattern
);
2291 bool ok
= re
.Matches(data
.text
);
2293 wxPrintf(_T("'%s' %s %s (%s)\n"),
2295 ok
? _T("matches") : _T("doesn't match"),
2297 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2301 static void TestRegExSubmatch()
2303 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2305 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2306 if ( !re
.IsValid() )
2308 wxPuts(_T("ERROR: compilation failed."));
2312 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2314 if ( !re
.Matches(text
) )
2316 wxPuts(_T("ERROR: match expected."));
2320 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2322 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2323 re
.GetMatch(text
, 3).c_str(),
2324 re
.GetMatch(text
, 2).c_str(),
2325 re
.GetMatch(text
, 4).c_str(),
2326 re
.GetMatch(text
, 1).c_str());
2330 static void TestRegExReplacement()
2332 wxPuts(_T("*** Testing RE replacement ***"));
2334 static struct RegExReplTestData
2338 const wxChar
*result
;
2340 } regExReplTestData
[] =
2342 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2343 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2344 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2345 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2346 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2347 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2348 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2351 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2352 wxRegEx
re(pattern
);
2354 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2356 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2358 const RegExReplTestData
& data
= regExReplTestData
[n
];
2360 wxString text
= data
.text
;
2361 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2363 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2364 data
.text
, data
.repl
,
2365 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2367 if ( text
== data
.result
&& nRepl
== data
.count
)
2373 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2374 data
.count
, data
.result
);
2379 static void TestRegExInteractive()
2381 wxPuts(_T("*** Testing RE interactively ***"));
2386 printf("\nEnter a pattern: ");
2387 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2390 // kill the last '\n'
2391 pattern
[strlen(pattern
) - 1] = 0;
2394 if ( !re
.Compile(pattern
) )
2402 printf("Enter text to match: ");
2403 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2406 // kill the last '\n'
2407 text
[strlen(text
) - 1] = 0;
2409 if ( !re
.Matches(text
) )
2411 printf("No match.\n");
2415 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2418 for ( size_t n
= 1; ; n
++ )
2420 if ( !re
.GetMatch(&start
, &len
, n
) )
2425 printf("Subexpr %u matched '%s'\n",
2426 n
, wxString(text
+ start
, len
).c_str());
2433 #endif // TEST_REGEX
2435 // ----------------------------------------------------------------------------
2437 // ----------------------------------------------------------------------------
2447 static void TestDbOpen()
2455 // ----------------------------------------------------------------------------
2456 // registry and related stuff
2457 // ----------------------------------------------------------------------------
2459 // this is for MSW only
2462 #undef TEST_REGISTRY
2467 #include "wx/confbase.h"
2468 #include "wx/msw/regconf.h"
2470 static void TestRegConfWrite()
2472 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2473 regconf
.Write(_T("Hello"), wxString(_T("world")));
2476 #endif // TEST_REGCONF
2478 #ifdef TEST_REGISTRY
2480 #include "wx/msw/registry.h"
2482 // I chose this one because I liked its name, but it probably only exists under
2484 static const wxChar
*TESTKEY
=
2485 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2487 static void TestRegistryRead()
2489 puts("*** testing registry reading ***");
2491 wxRegKey
key(TESTKEY
);
2492 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2495 puts("ERROR: test key can't be opened, aborting test.");
2500 size_t nSubKeys
, nValues
;
2501 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2503 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2506 printf("Enumerating values:\n");
2510 bool cont
= key
.GetFirstValue(value
, dummy
);
2513 printf("Value '%s': type ", value
.c_str());
2514 switch ( key
.GetValueType(value
) )
2516 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2517 case wxRegKey::Type_String
: printf("SZ"); break;
2518 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2519 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2520 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2521 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2522 default: printf("other (unknown)"); break;
2525 printf(", value = ");
2526 if ( key
.IsNumericValue(value
) )
2529 key
.QueryValue(value
, &val
);
2535 key
.QueryValue(value
, val
);
2536 printf("'%s'", val
.c_str());
2538 key
.QueryRawValue(value
, val
);
2539 printf(" (raw value '%s')", val
.c_str());
2544 cont
= key
.GetNextValue(value
, dummy
);
2548 static void TestRegistryAssociation()
2551 The second call to deleteself genertaes an error message, with a
2552 messagebox saying .flo is crucial to system operation, while the .ddf
2553 call also fails, but with no error message
2558 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2560 key
= "ddxf_auto_file" ;
2561 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2563 key
= "ddxf_auto_file" ;
2564 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2567 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2569 key
= "program \"%1\"" ;
2571 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2573 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2575 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2577 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2581 #endif // TEST_REGISTRY
2583 // ----------------------------------------------------------------------------
2585 // ----------------------------------------------------------------------------
2589 #include "wx/socket.h"
2590 #include "wx/protocol/protocol.h"
2591 #include "wx/protocol/http.h"
2593 static void TestSocketServer()
2595 puts("*** Testing wxSocketServer ***\n");
2597 static const int PORT
= 3000;
2602 wxSocketServer
*server
= new wxSocketServer(addr
);
2603 if ( !server
->Ok() )
2605 puts("ERROR: failed to bind");
2612 printf("Server: waiting for connection on port %d...\n", PORT
);
2614 wxSocketBase
*socket
= server
->Accept();
2617 puts("ERROR: wxSocketServer::Accept() failed.");
2621 puts("Server: got a client.");
2623 server
->SetTimeout(60); // 1 min
2625 while ( socket
->IsConnected() )
2631 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2633 // don't log error if the client just close the connection
2634 if ( socket
->IsConnected() )
2636 puts("ERROR: in wxSocket::Read.");
2656 printf("Server: got '%s'.\n", s
.c_str());
2657 if ( s
== _T("bye") )
2664 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2665 socket
->Write("\r\n", 2);
2666 printf("Server: wrote '%s'.\n", s
.c_str());
2669 puts("Server: lost a client.");
2674 // same as "delete server" but is consistent with GUI programs
2678 static void TestSocketClient()
2680 puts("*** Testing wxSocketClient ***\n");
2682 static const char *hostname
= "www.wxwindows.org";
2685 addr
.Hostname(hostname
);
2688 printf("--- Attempting to connect to %s:80...\n", hostname
);
2690 wxSocketClient client
;
2691 if ( !client
.Connect(addr
) )
2693 printf("ERROR: failed to connect to %s\n", hostname
);
2697 printf("--- Connected to %s:%u...\n",
2698 addr
.Hostname().c_str(), addr
.Service());
2702 // could use simply "GET" here I suppose
2704 wxString::Format("GET http://%s/\r\n", hostname
);
2705 client
.Write(cmdGet
, cmdGet
.length());
2706 printf("--- Sent command '%s' to the server\n",
2707 MakePrintable(cmdGet
).c_str());
2708 client
.Read(buf
, WXSIZEOF(buf
));
2709 printf("--- Server replied:\n%s", buf
);
2713 #endif // TEST_SOCKETS
2715 // ----------------------------------------------------------------------------
2717 // ----------------------------------------------------------------------------
2721 #include "wx/protocol/ftp.h"
2725 #define FTP_ANONYMOUS
2727 #ifdef FTP_ANONYMOUS
2728 static const char *directory
= "/pub";
2729 static const char *filename
= "welcome.msg";
2731 static const char *directory
= "/etc";
2732 static const char *filename
= "issue";
2735 static bool TestFtpConnect()
2737 puts("*** Testing FTP connect ***");
2739 #ifdef FTP_ANONYMOUS
2740 static const char *hostname
= "ftp.wxwindows.org";
2742 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2743 #else // !FTP_ANONYMOUS
2744 static const char *hostname
= "localhost";
2747 fgets(user
, WXSIZEOF(user
), stdin
);
2748 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2752 printf("Password for %s: ", password
);
2753 fgets(password
, WXSIZEOF(password
), stdin
);
2754 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2755 ftp
.SetPassword(password
);
2757 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2758 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2760 if ( !ftp
.Connect(hostname
) )
2762 printf("ERROR: failed to connect to %s\n", hostname
);
2768 printf("--- Connected to %s, current directory is '%s'\n",
2769 hostname
, ftp
.Pwd().c_str());
2775 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2776 static void TestFtpWuFtpd()
2779 static const char *hostname
= "ftp.eudora.com";
2780 if ( !ftp
.Connect(hostname
) )
2782 printf("ERROR: failed to connect to %s\n", hostname
);
2786 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2787 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2790 printf("ERROR: couldn't get input stream for %s\n", filename
);
2794 size_t size
= in
->StreamSize();
2795 printf("Reading file %s (%u bytes)...", filename
, size
);
2797 char *data
= new char[size
];
2798 if ( !in
->Read(data
, size
) )
2800 puts("ERROR: read error");
2804 printf("Successfully retrieved the file.\n");
2813 static void TestFtpList()
2815 puts("*** Testing wxFTP file listing ***\n");
2818 if ( !ftp
.ChDir(directory
) )
2820 printf("ERROR: failed to cd to %s\n", directory
);
2823 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2825 // test NLIST and LIST
2826 wxArrayString files
;
2827 if ( !ftp
.GetFilesList(files
) )
2829 puts("ERROR: failed to get NLIST of files");
2833 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2834 size_t count
= files
.GetCount();
2835 for ( size_t n
= 0; n
< count
; n
++ )
2837 printf("\t%s\n", files
[n
].c_str());
2839 puts("End of the file list");
2842 if ( !ftp
.GetDirList(files
) )
2844 puts("ERROR: failed to get LIST of files");
2848 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2849 size_t count
= files
.GetCount();
2850 for ( size_t n
= 0; n
< count
; n
++ )
2852 printf("\t%s\n", files
[n
].c_str());
2854 puts("End of the file list");
2857 if ( !ftp
.ChDir(_T("..")) )
2859 puts("ERROR: failed to cd to ..");
2862 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2865 static void TestFtpDownload()
2867 puts("*** Testing wxFTP download ***\n");
2870 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2873 printf("ERROR: couldn't get input stream for %s\n", filename
);
2877 size_t size
= in
->StreamSize();
2878 printf("Reading file %s (%u bytes)...", filename
, size
);
2881 char *data
= new char[size
];
2882 if ( !in
->Read(data
, size
) )
2884 puts("ERROR: read error");
2888 printf("\nContents of %s:\n%s\n", filename
, data
);
2896 static void TestFtpFileSize()
2898 puts("*** Testing FTP SIZE command ***");
2900 if ( !ftp
.ChDir(directory
) )
2902 printf("ERROR: failed to cd to %s\n", directory
);
2905 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2907 if ( ftp
.FileExists(filename
) )
2909 int size
= ftp
.GetFileSize(filename
);
2911 printf("ERROR: couldn't get size of '%s'\n", filename
);
2913 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2917 printf("ERROR: '%s' doesn't exist\n", filename
);
2921 static void TestFtpMisc()
2923 puts("*** Testing miscellaneous wxFTP functions ***");
2925 if ( ftp
.SendCommand("STAT") != '2' )
2927 puts("ERROR: STAT failed");
2931 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2934 if ( ftp
.SendCommand("HELP SITE") != '2' )
2936 puts("ERROR: HELP SITE failed");
2940 printf("The list of site-specific commands:\n\n%s\n",
2941 ftp
.GetLastResult().c_str());
2945 static void TestFtpInteractive()
2947 puts("\n*** Interactive wxFTP test ***");
2953 printf("Enter FTP command: ");
2954 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2957 // kill the last '\n'
2958 buf
[strlen(buf
) - 1] = 0;
2960 // special handling of LIST and NLST as they require data connection
2961 wxString
start(buf
, 4);
2963 if ( start
== "LIST" || start
== "NLST" )
2966 if ( strlen(buf
) > 4 )
2969 wxArrayString files
;
2970 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2972 printf("ERROR: failed to get %s of files\n", start
.c_str());
2976 printf("--- %s of '%s' under '%s':\n",
2977 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2978 size_t count
= files
.GetCount();
2979 for ( size_t n
= 0; n
< count
; n
++ )
2981 printf("\t%s\n", files
[n
].c_str());
2983 puts("--- End of the file list");
2988 char ch
= ftp
.SendCommand(buf
);
2989 printf("Command %s", ch
? "succeeded" : "failed");
2992 printf(" (return code %c)", ch
);
2995 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2999 puts("\n*** done ***");
3002 static void TestFtpUpload()
3004 puts("*** Testing wxFTP uploading ***\n");
3007 static const char *file1
= "test1";
3008 static const char *file2
= "test2";
3009 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
3012 printf("--- Uploading to %s ---\n", file1
);
3013 out
->Write("First hello", 11);
3017 // send a command to check the remote file
3018 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
3020 printf("ERROR: STAT %s failed\n", file1
);
3024 printf("STAT %s returned:\n\n%s\n",
3025 file1
, ftp
.GetLastResult().c_str());
3028 out
= ftp
.GetOutputStream(file2
);
3031 printf("--- Uploading to %s ---\n", file1
);
3032 out
->Write("Second hello", 12);
3039 // ----------------------------------------------------------------------------
3041 // ----------------------------------------------------------------------------
3045 #include "wx/wfstream.h"
3046 #include "wx/mstream.h"
3048 static void TestFileStream()
3050 puts("*** Testing wxFileInputStream ***");
3052 static const wxChar
*filename
= _T("testdata.fs");
3054 wxFileOutputStream
fsOut(filename
);
3055 fsOut
.Write("foo", 3);
3058 wxFileInputStream
fsIn(filename
);
3059 printf("File stream size: %u\n", fsIn
.GetSize());
3060 while ( !fsIn
.Eof() )
3062 putchar(fsIn
.GetC());
3065 if ( !wxRemoveFile(filename
) )
3067 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3070 puts("\n*** wxFileInputStream test done ***");
3073 static void TestMemoryStream()
3075 puts("*** Testing wxMemoryInputStream ***");
3078 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3080 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3081 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3082 while ( !memInpStream
.Eof() )
3084 putchar(memInpStream
.GetC());
3087 puts("\n*** wxMemoryInputStream test done ***");
3090 #endif // TEST_STREAMS
3092 // ----------------------------------------------------------------------------
3094 // ----------------------------------------------------------------------------
3098 #include "wx/timer.h"
3099 #include "wx/utils.h"
3101 static void TestStopWatch()
3103 puts("*** Testing wxStopWatch ***\n");
3107 printf("Initially paused, after 2 seconds time is...");
3110 printf("\t%ldms\n", sw
.Time());
3112 printf("Resuming stopwatch and sleeping 3 seconds...");
3116 printf("\telapsed time: %ldms\n", sw
.Time());
3119 printf("Pausing agan and sleeping 2 more seconds...");
3122 printf("\telapsed time: %ldms\n", sw
.Time());
3125 printf("Finally resuming and sleeping 2 more seconds...");
3128 printf("\telapsed time: %ldms\n", sw
.Time());
3131 puts("\nChecking for 'backwards clock' bug...");
3132 for ( size_t n
= 0; n
< 70; n
++ )
3136 for ( size_t m
= 0; m
< 100000; m
++ )
3138 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3140 puts("\ntime is negative - ERROR!");
3151 #endif // TEST_TIMER
3153 // ----------------------------------------------------------------------------
3155 // ----------------------------------------------------------------------------
3159 #include "wx/vcard.h"
3161 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3164 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3168 wxString(_T('\t'), level
).c_str(),
3169 vcObj
->GetName().c_str());
3172 switch ( vcObj
->GetType() )
3174 case wxVCardObject::String
:
3175 case wxVCardObject::UString
:
3178 vcObj
->GetValue(&val
);
3179 value
<< _T('"') << val
<< _T('"');
3183 case wxVCardObject::Int
:
3186 vcObj
->GetValue(&i
);
3187 value
.Printf(_T("%u"), i
);
3191 case wxVCardObject::Long
:
3194 vcObj
->GetValue(&l
);
3195 value
.Printf(_T("%lu"), l
);
3199 case wxVCardObject::None
:
3202 case wxVCardObject::Object
:
3203 value
= _T("<node>");
3207 value
= _T("<unknown value type>");
3211 printf(" = %s", value
.c_str());
3214 DumpVObject(level
+ 1, *vcObj
);
3217 vcObj
= vcard
.GetNextProp(&cookie
);
3221 static void DumpVCardAddresses(const wxVCard
& vcard
)
3223 puts("\nShowing all addresses from vCard:\n");
3227 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3231 int flags
= addr
->GetFlags();
3232 if ( flags
& wxVCardAddress::Domestic
)
3234 flagsStr
<< _T("domestic ");
3236 if ( flags
& wxVCardAddress::Intl
)
3238 flagsStr
<< _T("international ");
3240 if ( flags
& wxVCardAddress::Postal
)
3242 flagsStr
<< _T("postal ");
3244 if ( flags
& wxVCardAddress::Parcel
)
3246 flagsStr
<< _T("parcel ");
3248 if ( flags
& wxVCardAddress::Home
)
3250 flagsStr
<< _T("home ");
3252 if ( flags
& wxVCardAddress::Work
)
3254 flagsStr
<< _T("work ");
3257 printf("Address %u:\n"
3259 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3262 addr
->GetPostOffice().c_str(),
3263 addr
->GetExtAddress().c_str(),
3264 addr
->GetStreet().c_str(),
3265 addr
->GetLocality().c_str(),
3266 addr
->GetRegion().c_str(),
3267 addr
->GetPostalCode().c_str(),
3268 addr
->GetCountry().c_str()
3272 addr
= vcard
.GetNextAddress(&cookie
);
3276 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3278 puts("\nShowing all phone numbers from vCard:\n");
3282 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3286 int flags
= phone
->GetFlags();
3287 if ( flags
& wxVCardPhoneNumber::Voice
)
3289 flagsStr
<< _T("voice ");
3291 if ( flags
& wxVCardPhoneNumber::Fax
)
3293 flagsStr
<< _T("fax ");
3295 if ( flags
& wxVCardPhoneNumber::Cellular
)
3297 flagsStr
<< _T("cellular ");
3299 if ( flags
& wxVCardPhoneNumber::Modem
)
3301 flagsStr
<< _T("modem ");
3303 if ( flags
& wxVCardPhoneNumber::Home
)
3305 flagsStr
<< _T("home ");
3307 if ( flags
& wxVCardPhoneNumber::Work
)
3309 flagsStr
<< _T("work ");
3312 printf("Phone number %u:\n"
3317 phone
->GetNumber().c_str()
3321 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3325 static void TestVCardRead()
3327 puts("*** Testing wxVCard reading ***\n");
3329 wxVCard
vcard(_T("vcard.vcf"));
3330 if ( !vcard
.IsOk() )
3332 puts("ERROR: couldn't load vCard.");
3336 // read individual vCard properties
3337 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3341 vcObj
->GetValue(&value
);
3346 value
= _T("<none>");
3349 printf("Full name retrieved directly: %s\n", value
.c_str());
3352 if ( !vcard
.GetFullName(&value
) )
3354 value
= _T("<none>");
3357 printf("Full name from wxVCard API: %s\n", value
.c_str());
3359 // now show how to deal with multiply occuring properties
3360 DumpVCardAddresses(vcard
);
3361 DumpVCardPhoneNumbers(vcard
);
3363 // and finally show all
3364 puts("\nNow dumping the entire vCard:\n"
3365 "-----------------------------\n");
3367 DumpVObject(0, vcard
);
3371 static void TestVCardWrite()
3373 puts("*** Testing wxVCard writing ***\n");
3376 if ( !vcard
.IsOk() )
3378 puts("ERROR: couldn't create vCard.");
3383 vcard
.SetName("Zeitlin", "Vadim");
3384 vcard
.SetFullName("Vadim Zeitlin");
3385 vcard
.SetOrganization("wxWindows", "R&D");
3387 // just dump the vCard back
3388 puts("Entire vCard follows:\n");
3389 puts(vcard
.Write());
3393 #endif // TEST_VCARD
3395 // ----------------------------------------------------------------------------
3397 // ----------------------------------------------------------------------------
3399 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3405 #include "wx/volume.h"
3407 static const wxChar
*volumeKinds
[] =
3413 _T("network volume"),
3417 static void TestFSVolume()
3419 wxPuts(_T("*** Testing wxFSVolume class ***"));
3421 wxArrayString volumes
= wxFSVolume::GetVolumes();
3422 size_t count
= volumes
.GetCount();
3426 wxPuts(_T("ERROR: no mounted volumes?"));
3430 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3432 for ( size_t n
= 0; n
< count
; n
++ )
3434 wxFSVolume
vol(volumes
[n
]);
3437 wxPuts(_T("ERROR: couldn't create volume"));
3441 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3443 vol
.GetDisplayName().c_str(),
3444 vol
.GetName().c_str(),
3445 volumeKinds
[vol
.GetKind()],
3446 vol
.IsWritable() ? _T("rw") : _T("ro"),
3447 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3452 #endif // TEST_VOLUME
3454 // ----------------------------------------------------------------------------
3455 // wide char (Unicode) support
3456 // ----------------------------------------------------------------------------
3460 #include "wx/strconv.h"
3461 #include "wx/fontenc.h"
3462 #include "wx/encconv.h"
3463 #include "wx/buffer.h"
3465 static const char textInUtf8
[] =
3467 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3468 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3469 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3470 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3471 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3472 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3473 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3476 static void TestUtf8()
3478 puts("*** Testing UTF8 support ***\n");
3482 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3484 puts("ERROR: UTF-8 decoding failed.");
3488 wxCSConv
conv(_T("koi8-r"));
3489 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3491 puts("ERROR: conversion to KOI8-R failed.");
3495 printf("The resulting string (in KOI8-R): %s\n", buf
);
3499 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3501 puts("ERROR: conversion to UTF-8 failed.");
3505 printf("The string in UTF-8: %s\n", buf
);
3511 static void TestEncodingConverter()
3513 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3515 // using wxEncodingConverter should give the same result as above
3518 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3520 puts("ERROR: UTF-8 decoding failed.");
3524 wxEncodingConverter ec
;
3525 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3526 ec
.Convert(wbuf
, buf
);
3527 printf("The same string obtained using wxEC: %s\n", buf
);
3533 #endif // TEST_WCHAR
3535 // ----------------------------------------------------------------------------
3537 // ----------------------------------------------------------------------------
3541 #include "wx/filesys.h"
3542 #include "wx/fs_zip.h"
3543 #include "wx/zipstrm.h"
3545 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3547 static void TestZipStreamRead()
3549 puts("*** Testing ZIP reading ***\n");
3551 static const wxChar
*filename
= _T("foo");
3552 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3553 printf("Archive size: %u\n", istr
.GetSize());
3555 printf("Dumping the file '%s':\n", filename
);
3556 while ( !istr
.Eof() )
3558 putchar(istr
.GetC());
3562 puts("\n----- done ------");
3565 static void DumpZipDirectory(wxFileSystem
& fs
,
3566 const wxString
& dir
,
3567 const wxString
& indent
)
3569 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3570 TESTFILE_ZIP
, dir
.c_str());
3571 wxString wildcard
= prefix
+ _T("/*");
3573 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3574 while ( !dirname
.empty() )
3576 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3578 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3583 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3585 DumpZipDirectory(fs
, dirname
,
3586 indent
+ wxString(_T(' '), 4));
3588 dirname
= fs
.FindNext();
3591 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3592 while ( !filename
.empty() )
3594 if ( !filename
.StartsWith(prefix
, &filename
) )
3596 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3601 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3603 filename
= fs
.FindNext();
3607 static void TestZipFileSystem()
3609 puts("*** Testing ZIP file system ***\n");
3611 wxFileSystem::AddHandler(new wxZipFSHandler
);
3613 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3615 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3620 // ----------------------------------------------------------------------------
3622 // ----------------------------------------------------------------------------
3626 #include "wx/zstream.h"
3627 #include "wx/wfstream.h"
3629 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3630 static const char *TEST_DATA
= "hello and hello and hello and hello and hello";
3632 static void TestZlibStreamWrite()
3634 puts("*** Testing Zlib stream reading ***\n");
3636 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3637 wxZlibOutputStream
ostr(fileOutStream
);
3638 printf("Compressing the test string... ");
3639 ostr
.Write(TEST_DATA
, strlen(TEST_DATA
) + 1);
3642 puts("(ERROR: failed)");
3649 puts("\n----- done ------");
3652 static void TestZlibStreamRead()
3654 puts("*** Testing Zlib stream reading ***\n");
3656 wxFileInputStream
fileInStream(FILENAME_GZ
);
3657 wxZlibInputStream
istr(fileInStream
);
3658 printf("Archive size: %u\n", istr
.GetSize());
3660 puts("Dumping the file:");
3661 while ( !istr
.Eof() )
3663 putchar(istr
.GetC());
3667 puts("\n----- done ------");
3672 // ----------------------------------------------------------------------------
3674 // ----------------------------------------------------------------------------
3676 #ifdef TEST_DATETIME
3680 #include "wx/date.h"
3681 #include "wx/datetime.h"
3686 wxDateTime::wxDateTime_t day
;
3687 wxDateTime::Month month
;
3689 wxDateTime::wxDateTime_t hour
, min
, sec
;
3691 wxDateTime::WeekDay wday
;
3692 time_t gmticks
, ticks
;
3694 void Init(const wxDateTime::Tm
& tm
)
3703 gmticks
= ticks
= -1;
3706 wxDateTime
DT() const
3707 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3709 bool SameDay(const wxDateTime::Tm
& tm
) const
3711 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3714 wxString
Format() const
3717 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3719 wxDateTime::GetMonthName(month
).c_str(),
3721 abs(wxDateTime::ConvertYearToBC(year
)),
3722 year
> 0 ? "AD" : "BC");
3726 wxString
FormatDate() const
3729 s
.Printf("%02d-%s-%4d%s",
3731 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3732 abs(wxDateTime::ConvertYearToBC(year
)),
3733 year
> 0 ? "AD" : "BC");
3738 static const Date testDates
[] =
3740 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3741 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3742 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3743 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3744 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3745 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3746 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3747 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3748 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3749 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3750 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3751 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3752 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3753 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3754 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3757 // this test miscellaneous static wxDateTime functions
3758 static void TestTimeStatic()
3760 puts("\n*** wxDateTime static methods test ***");
3762 // some info about the current date
3763 int year
= wxDateTime::GetCurrentYear();
3764 printf("Current year %d is %sa leap one and has %d days.\n",
3766 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3767 wxDateTime::GetNumberOfDays(year
));
3769 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3770 printf("Current month is '%s' ('%s') and it has %d days\n",
3771 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3772 wxDateTime::GetMonthName(month
).c_str(),
3773 wxDateTime::GetNumberOfDays(month
));
3776 static const size_t nYears
= 5;
3777 static const size_t years
[2][nYears
] =
3779 // first line: the years to test
3780 { 1990, 1976, 2000, 2030, 1984, },
3782 // second line: TRUE if leap, FALSE otherwise
3783 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3786 for ( size_t n
= 0; n
< nYears
; n
++ )
3788 int year
= years
[0][n
];
3789 bool should
= years
[1][n
] != 0,
3790 is
= wxDateTime::IsLeapYear(year
);
3792 printf("Year %d is %sa leap year (%s)\n",
3795 should
== is
? "ok" : "ERROR");
3797 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3801 // test constructing wxDateTime objects
3802 static void TestTimeSet()
3804 puts("\n*** wxDateTime construction test ***");
3806 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3808 const Date
& d1
= testDates
[n
];
3809 wxDateTime dt
= d1
.DT();
3812 d2
.Init(dt
.GetTm());
3814 wxString s1
= d1
.Format(),
3817 printf("Date: %s == %s (%s)\n",
3818 s1
.c_str(), s2
.c_str(),
3819 s1
== s2
? "ok" : "ERROR");
3823 // test time zones stuff
3824 static void TestTimeZones()
3826 puts("\n*** wxDateTime timezone test ***");
3828 wxDateTime now
= wxDateTime::Now();
3830 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3831 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3832 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3833 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3834 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3835 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3837 wxDateTime::Tm tm
= now
.GetTm();
3838 if ( wxDateTime(tm
) != now
)
3840 printf("ERROR: got %s instead of %s\n",
3841 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3845 // test some minimal support for the dates outside the standard range
3846 static void TestTimeRange()
3848 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3850 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3852 printf("Unix epoch:\t%s\n",
3853 wxDateTime(2440587.5).Format(fmt
).c_str());
3854 printf("Feb 29, 0: \t%s\n",
3855 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3856 printf("JDN 0: \t%s\n",
3857 wxDateTime(0.0).Format(fmt
).c_str());
3858 printf("Jan 1, 1AD:\t%s\n",
3859 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3860 printf("May 29, 2099:\t%s\n",
3861 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3864 static void TestTimeTicks()
3866 puts("\n*** wxDateTime ticks test ***");
3868 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3870 const Date
& d
= testDates
[n
];
3871 if ( d
.ticks
== -1 )
3874 wxDateTime dt
= d
.DT();
3875 long ticks
= (dt
.GetValue() / 1000).ToLong();
3876 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3877 if ( ticks
== d
.ticks
)
3883 printf(" (ERROR: should be %ld, delta = %ld)\n",
3884 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
3887 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3888 ticks
= (dt
.GetValue() / 1000).ToLong();
3889 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3890 if ( ticks
== d
.gmticks
)
3896 printf(" (ERROR: should be %ld, delta = %ld)\n",
3897 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
3904 // test conversions to JDN &c
3905 static void TestTimeJDN()
3907 puts("\n*** wxDateTime to JDN test ***");
3909 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3911 const Date
& d
= testDates
[n
];
3912 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3913 double jdn
= dt
.GetJulianDayNumber();
3915 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3922 printf(" (ERROR: should be %f, delta = %f)\n",
3923 d
.jdn
, jdn
- d
.jdn
);
3928 // test week days computation
3929 static void TestTimeWDays()
3931 puts("\n*** wxDateTime weekday test ***");
3933 // test GetWeekDay()
3935 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3937 const Date
& d
= testDates
[n
];
3938 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3940 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3943 wxDateTime::GetWeekDayName(wday
).c_str());
3944 if ( wday
== d
.wday
)
3950 printf(" (ERROR: should be %s)\n",
3951 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3957 // test SetToWeekDay()
3958 struct WeekDateTestData
3960 Date date
; // the real date (precomputed)
3961 int nWeek
; // its week index in the month
3962 wxDateTime::WeekDay wday
; // the weekday
3963 wxDateTime::Month month
; // the month
3964 int year
; // and the year
3966 wxString
Format() const
3969 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3971 case 1: which
= "first"; break;
3972 case 2: which
= "second"; break;
3973 case 3: which
= "third"; break;
3974 case 4: which
= "fourth"; break;
3975 case 5: which
= "fifth"; break;
3977 case -1: which
= "last"; break;
3982 which
+= " from end";
3985 s
.Printf("The %s %s of %s in %d",
3987 wxDateTime::GetWeekDayName(wday
).c_str(),
3988 wxDateTime::GetMonthName(month
).c_str(),
3995 // the array data was generated by the following python program
3997 from DateTime import *
3998 from whrandom import *
3999 from string import *
4001 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4002 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4004 week = DateTimeDelta(7)
4007 year = randint(1900, 2100)
4008 month = randint(1, 12)
4009 day = randint(1, 28)
4010 dt = DateTime(year, month, day)
4011 wday = dt.day_of_week
4013 countFromEnd = choice([-1, 1])
4016 while dt.month is month:
4017 dt = dt - countFromEnd * week
4018 weekNum = weekNum + countFromEnd
4020 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
4022 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
4023 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
4026 static const WeekDateTestData weekDatesTestData
[] =
4028 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
4029 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
4030 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
4031 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
4032 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
4033 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
4034 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
4035 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
4036 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
4037 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
4038 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
4039 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
4040 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
4041 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
4042 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
4043 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
4044 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
4045 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
4046 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
4047 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4050 static const char *fmt
= "%d-%b-%Y";
4053 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4055 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4057 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4059 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4061 const Date
& d
= wd
.date
;
4062 if ( d
.SameDay(dt
.GetTm()) )
4068 dt
.Set(d
.day
, d
.month
, d
.year
);
4070 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4075 // test the computation of (ISO) week numbers
4076 static void TestTimeWNumber()
4078 puts("\n*** wxDateTime week number test ***");
4080 struct WeekNumberTestData
4082 Date date
; // the date
4083 wxDateTime::wxDateTime_t week
; // the week number in the year
4084 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4085 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4086 wxDateTime::wxDateTime_t dnum
; // day number in the year
4089 // data generated with the following python script:
4091 from DateTime import *
4092 from whrandom import *
4093 from string import *
4095 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4096 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4098 def GetMonthWeek(dt):
4099 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4100 if weekNumMonth < 0:
4101 weekNumMonth = weekNumMonth + 53
4104 def GetLastSundayBefore(dt):
4105 if dt.iso_week[2] == 7:
4108 return dt - DateTimeDelta(dt.iso_week[2])
4111 year = randint(1900, 2100)
4112 month = randint(1, 12)
4113 day = randint(1, 28)
4114 dt = DateTime(year, month, day)
4115 dayNum = dt.day_of_year
4116 weekNum = dt.iso_week[1]
4117 weekNumMonth = GetMonthWeek(dt)
4120 dtSunday = GetLastSundayBefore(dt)
4122 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4123 weekNumMonth2 = weekNumMonth2 + 1
4124 dtSunday = dtSunday - DateTimeDelta(7)
4126 data = { 'day': rjust(`day`, 2), \
4127 'month': monthNames[month - 1], \
4129 'weekNum': rjust(`weekNum`, 2), \
4130 'weekNumMonth': weekNumMonth, \
4131 'weekNumMonth2': weekNumMonth2, \
4132 'dayNum': rjust(`dayNum`, 3) }
4134 print " { { %(day)s, "\
4135 "wxDateTime::%(month)s, "\
4138 "%(weekNumMonth)s, "\
4139 "%(weekNumMonth2)s, "\
4140 "%(dayNum)s }," % data
4143 static const WeekNumberTestData weekNumberTestDates
[] =
4145 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4146 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4147 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4148 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4149 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4150 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4151 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4152 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4153 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4154 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4155 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4156 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4157 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4158 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4159 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4160 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4161 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4162 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4163 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4164 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4167 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4169 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4170 const Date
& d
= wn
.date
;
4172 wxDateTime dt
= d
.DT();
4174 wxDateTime::wxDateTime_t
4175 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4176 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4177 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4178 dnum
= dt
.GetDayOfYear();
4180 printf("%s: the day number is %d",
4181 d
.FormatDate().c_str(), dnum
);
4182 if ( dnum
== wn
.dnum
)
4188 printf(" (ERROR: should be %d)", wn
.dnum
);
4191 printf(", week in month is %d", wmon
);
4192 if ( wmon
== wn
.wmon
)
4198 printf(" (ERROR: should be %d)", wn
.wmon
);
4201 printf(" or %d", wmon2
);
4202 if ( wmon2
== wn
.wmon2
)
4208 printf(" (ERROR: should be %d)", wn
.wmon2
);
4211 printf(", week in year is %d", week
);
4212 if ( week
== wn
.week
)
4218 printf(" (ERROR: should be %d)\n", wn
.week
);
4223 // test DST calculations
4224 static void TestTimeDST()
4226 puts("\n*** wxDateTime DST test ***");
4228 printf("DST is%s in effect now.\n\n",
4229 wxDateTime::Now().IsDST() ? "" : " not");
4231 // taken from http://www.energy.ca.gov/daylightsaving.html
4232 static const Date datesDST
[2][2004 - 1900 + 1] =
4235 { 1, wxDateTime::Apr
, 1990 },
4236 { 7, wxDateTime::Apr
, 1991 },
4237 { 5, wxDateTime::Apr
, 1992 },
4238 { 4, wxDateTime::Apr
, 1993 },
4239 { 3, wxDateTime::Apr
, 1994 },
4240 { 2, wxDateTime::Apr
, 1995 },
4241 { 7, wxDateTime::Apr
, 1996 },
4242 { 6, wxDateTime::Apr
, 1997 },
4243 { 5, wxDateTime::Apr
, 1998 },
4244 { 4, wxDateTime::Apr
, 1999 },
4245 { 2, wxDateTime::Apr
, 2000 },
4246 { 1, wxDateTime::Apr
, 2001 },
4247 { 7, wxDateTime::Apr
, 2002 },
4248 { 6, wxDateTime::Apr
, 2003 },
4249 { 4, wxDateTime::Apr
, 2004 },
4252 { 28, wxDateTime::Oct
, 1990 },
4253 { 27, wxDateTime::Oct
, 1991 },
4254 { 25, wxDateTime::Oct
, 1992 },
4255 { 31, wxDateTime::Oct
, 1993 },
4256 { 30, wxDateTime::Oct
, 1994 },
4257 { 29, wxDateTime::Oct
, 1995 },
4258 { 27, wxDateTime::Oct
, 1996 },
4259 { 26, wxDateTime::Oct
, 1997 },
4260 { 25, wxDateTime::Oct
, 1998 },
4261 { 31, wxDateTime::Oct
, 1999 },
4262 { 29, wxDateTime::Oct
, 2000 },
4263 { 28, wxDateTime::Oct
, 2001 },
4264 { 27, wxDateTime::Oct
, 2002 },
4265 { 26, wxDateTime::Oct
, 2003 },
4266 { 31, wxDateTime::Oct
, 2004 },
4271 for ( year
= 1990; year
< 2005; year
++ )
4273 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4274 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4276 printf("DST period in the US for year %d: from %s to %s",
4277 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4279 size_t n
= year
- 1990;
4280 const Date
& dBegin
= datesDST
[0][n
];
4281 const Date
& dEnd
= datesDST
[1][n
];
4283 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4289 printf(" (ERROR: should be %s %d to %s %d)\n",
4290 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4291 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4297 for ( year
= 1990; year
< 2005; year
++ )
4299 printf("DST period in Europe for year %d: from %s to %s\n",
4301 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4302 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4306 // test wxDateTime -> text conversion
4307 static void TestTimeFormat()
4309 puts("\n*** wxDateTime formatting test ***");
4311 // some information may be lost during conversion, so store what kind
4312 // of info should we recover after a round trip
4315 CompareNone
, // don't try comparing
4316 CompareBoth
, // dates and times should be identical
4317 CompareDate
, // dates only
4318 CompareTime
// time only
4323 CompareKind compareKind
;
4325 } formatTestFormats
[] =
4327 { CompareBoth
, "---> %c" },
4328 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4329 { CompareBoth
, "Date is %x, time is %X" },
4330 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4331 { CompareNone
, "The day of year: %j, the week of year: %W" },
4332 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4335 static const Date formatTestDates
[] =
4337 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4338 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4340 // this test can't work for other centuries because it uses two digit
4341 // years in formats, so don't even try it
4342 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4343 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4344 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4348 // an extra test (as it doesn't depend on date, don't do it in the loop)
4349 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4351 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4355 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4356 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4358 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4359 printf("%s", s
.c_str());
4361 // what can we recover?
4362 int kind
= formatTestFormats
[n
].compareKind
;
4366 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4369 // converion failed - should it have?
4370 if ( kind
== CompareNone
)
4373 puts(" (ERROR: conversion back failed)");
4377 // should have parsed the entire string
4378 puts(" (ERROR: conversion back stopped too soon)");
4382 bool equal
= FALSE
; // suppress compilaer warning
4390 equal
= dt
.IsSameDate(dt2
);
4394 equal
= dt
.IsSameTime(dt2
);
4400 printf(" (ERROR: got back '%s' instead of '%s')\n",
4401 dt2
.Format().c_str(), dt
.Format().c_str());
4412 // test text -> wxDateTime conversion
4413 static void TestTimeParse()
4415 puts("\n*** wxDateTime parse test ***");
4417 struct ParseTestData
4424 static const ParseTestData parseTestDates
[] =
4426 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4427 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4430 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4432 const char *format
= parseTestDates
[n
].format
;
4434 printf("%s => ", format
);
4437 if ( dt
.ParseRfc822Date(format
) )
4439 printf("%s ", dt
.Format().c_str());
4441 if ( parseTestDates
[n
].good
)
4443 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4450 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4455 puts("(ERROR: bad format)");
4460 printf("bad format (%s)\n",
4461 parseTestDates
[n
].good
? "ERROR" : "ok");
4466 static void TestDateTimeInteractive()
4468 puts("\n*** interactive wxDateTime tests ***");
4474 printf("Enter a date: ");
4475 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4478 // kill the last '\n'
4479 buf
[strlen(buf
) - 1] = 0;
4482 const char *p
= dt
.ParseDate(buf
);
4485 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4491 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4494 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4495 dt
.Format("%b %d, %Y").c_str(),
4497 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4498 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4499 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4502 puts("\n*** done ***");
4505 static void TestTimeMS()
4507 puts("*** testing millisecond-resolution support in wxDateTime ***");
4509 wxDateTime dt1
= wxDateTime::Now(),
4510 dt2
= wxDateTime::UNow();
4512 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4513 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4514 printf("Dummy loop: ");
4515 for ( int i
= 0; i
< 6000; i
++ )
4517 //for ( int j = 0; j < 10; j++ )
4520 s
.Printf("%g", sqrt(i
));
4529 dt2
= wxDateTime::UNow();
4530 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4532 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4534 puts("\n*** done ***");
4537 static void TestTimeArithmetics()
4539 puts("\n*** testing arithmetic operations on wxDateTime ***");
4541 static const struct ArithmData
4543 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4544 : span(sp
), name(nam
) { }
4548 } testArithmData
[] =
4550 ArithmData(wxDateSpan::Day(), "day"),
4551 ArithmData(wxDateSpan::Week(), "week"),
4552 ArithmData(wxDateSpan::Month(), "month"),
4553 ArithmData(wxDateSpan::Year(), "year"),
4554 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4557 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4559 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4561 wxDateSpan span
= testArithmData
[n
].span
;
4565 const char *name
= testArithmData
[n
].name
;
4566 printf("%s + %s = %s, %s - %s = %s\n",
4567 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4568 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4570 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4571 if ( dt1
- span
== dt
)
4577 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4580 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4581 if ( dt2
+ span
== dt
)
4587 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4590 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4591 if ( dt2
+ 2*span
== dt1
)
4597 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4604 static void TestTimeHolidays()
4606 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4608 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4609 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4610 dtEnd
= dtStart
.GetLastMonthDay();
4612 wxDateTimeArray hol
;
4613 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4615 const wxChar
*format
= "%d-%b-%Y (%a)";
4617 printf("All holidays between %s and %s:\n",
4618 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4620 size_t count
= hol
.GetCount();
4621 for ( size_t n
= 0; n
< count
; n
++ )
4623 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4629 static void TestTimeZoneBug()
4631 puts("\n*** testing for DST/timezone bug ***\n");
4633 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4634 for ( int i
= 0; i
< 31; i
++ )
4636 printf("Date %s: week day %s.\n",
4637 date
.Format(_T("%d-%m-%Y")).c_str(),
4638 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4640 date
+= wxDateSpan::Day();
4646 static void TestTimeSpanFormat()
4648 puts("\n*** wxTimeSpan tests ***");
4650 static const char *formats
[] =
4652 _T("(default) %H:%M:%S"),
4653 _T("%E weeks and %D days"),
4654 _T("%l milliseconds"),
4655 _T("(with ms) %H:%M:%S:%l"),
4656 _T("100%% of minutes is %M"), // test "%%"
4657 _T("%D days and %H hours"),
4658 _T("or also %S seconds"),
4661 wxTimeSpan
ts1(1, 2, 3, 4),
4663 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4665 printf("ts1 = %s\tts2 = %s\n",
4666 ts1
.Format(formats
[n
]).c_str(),
4667 ts2
.Format(formats
[n
]).c_str());
4675 // test compatibility with the old wxDate/wxTime classes
4676 static void TestTimeCompatibility()
4678 puts("\n*** wxDateTime compatibility test ***");
4680 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4681 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4683 double jdnNow
= wxDateTime::Now().GetJDN();
4684 long jdnMidnight
= (long)(jdnNow
- 0.5);
4685 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4687 jdnMidnight
= wxDate().Set().GetJulianDate();
4688 printf("wxDateTime for today: %s\n",
4689 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4691 int flags
= wxEUROPEAN
;//wxFULL;
4694 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4695 for ( int n
= 0; n
< 7; n
++ )
4697 printf("Previous %s is %s\n",
4698 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4699 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4705 #endif // TEST_DATETIME
4707 // ----------------------------------------------------------------------------
4709 // ----------------------------------------------------------------------------
4713 #include "wx/thread.h"
4715 static size_t gs_counter
= (size_t)-1;
4716 static wxCriticalSection gs_critsect
;
4717 static wxSemaphore gs_cond
;
4719 class MyJoinableThread
: public wxThread
4722 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4723 { m_n
= n
; Create(); }
4725 // thread execution starts here
4726 virtual ExitCode
Entry();
4732 wxThread::ExitCode
MyJoinableThread::Entry()
4734 unsigned long res
= 1;
4735 for ( size_t n
= 1; n
< m_n
; n
++ )
4739 // it's a loooong calculation :-)
4743 return (ExitCode
)res
;
4746 class MyDetachedThread
: public wxThread
4749 MyDetachedThread(size_t n
, char ch
)
4753 m_cancelled
= FALSE
;
4758 // thread execution starts here
4759 virtual ExitCode
Entry();
4762 virtual void OnExit();
4765 size_t m_n
; // number of characters to write
4766 char m_ch
; // character to write
4768 bool m_cancelled
; // FALSE if we exit normally
4771 wxThread::ExitCode
MyDetachedThread::Entry()
4774 wxCriticalSectionLocker
lock(gs_critsect
);
4775 if ( gs_counter
== (size_t)-1 )
4781 for ( size_t n
= 0; n
< m_n
; n
++ )
4783 if ( TestDestroy() )
4793 wxThread::Sleep(100);
4799 void MyDetachedThread::OnExit()
4801 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4803 wxCriticalSectionLocker
lock(gs_critsect
);
4804 if ( !--gs_counter
&& !m_cancelled
)
4808 static void TestDetachedThreads()
4810 puts("\n*** Testing detached threads ***");
4812 static const size_t nThreads
= 3;
4813 MyDetachedThread
*threads
[nThreads
];
4815 for ( n
= 0; n
< nThreads
; n
++ )
4817 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4820 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4821 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4823 for ( n
= 0; n
< nThreads
; n
++ )
4828 // wait until all threads terminate
4834 static void TestJoinableThreads()
4836 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4838 // calc 10! in the background
4839 MyJoinableThread
thread(10);
4842 printf("\nThread terminated with exit code %lu.\n",
4843 (unsigned long)thread
.Wait());
4846 static void TestThreadSuspend()
4848 puts("\n*** Testing thread suspend/resume functions ***");
4850 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4854 // this is for this demo only, in a real life program we'd use another
4855 // condition variable which would be signaled from wxThread::Entry() to
4856 // tell us that the thread really started running - but here just wait a
4857 // bit and hope that it will be enough (the problem is, of course, that
4858 // the thread might still not run when we call Pause() which will result
4860 wxThread::Sleep(300);
4862 for ( size_t n
= 0; n
< 3; n
++ )
4866 puts("\nThread suspended");
4869 // don't sleep but resume immediately the first time
4870 wxThread::Sleep(300);
4872 puts("Going to resume the thread");
4877 puts("Waiting until it terminates now");
4879 // wait until the thread terminates
4885 static void TestThreadDelete()
4887 // As above, using Sleep() is only for testing here - we must use some
4888 // synchronisation object instead to ensure that the thread is still
4889 // running when we delete it - deleting a detached thread which already
4890 // terminated will lead to a crash!
4892 puts("\n*** Testing thread delete function ***");
4894 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4898 puts("\nDeleted a thread which didn't start to run yet.");
4900 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4904 wxThread::Sleep(300);
4908 puts("\nDeleted a running thread.");
4910 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4914 wxThread::Sleep(300);
4920 puts("\nDeleted a sleeping thread.");
4922 MyJoinableThread
thread3(20);
4927 puts("\nDeleted a joinable thread.");
4929 MyJoinableThread
thread4(2);
4932 wxThread::Sleep(300);
4936 puts("\nDeleted a joinable thread which already terminated.");
4941 class MyWaitingThread
: public wxThread
4944 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4947 m_condition
= condition
;
4952 virtual ExitCode
Entry()
4954 printf("Thread %lu has started running.\n", GetId());
4959 printf("Thread %lu starts to wait...\n", GetId());
4963 m_condition
->Wait();
4966 printf("Thread %lu finished to wait, exiting.\n", GetId());
4974 wxCondition
*m_condition
;
4977 static void TestThreadConditions()
4980 wxCondition
condition(mutex
);
4982 // otherwise its difficult to understand which log messages pertain to
4984 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4985 // condition.GetId(), gs_cond.GetId());
4987 // create and launch threads
4988 MyWaitingThread
*threads
[10];
4991 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4993 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4996 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5001 // wait until all threads run
5002 puts("Main thread is waiting for the other threads to start");
5005 size_t nRunning
= 0;
5006 while ( nRunning
< WXSIZEOF(threads
) )
5012 printf("Main thread: %u already running\n", nRunning
);
5016 puts("Main thread: all threads started up.");
5019 wxThread::Sleep(500);
5022 // now wake one of them up
5023 printf("Main thread: about to signal the condition.\n");
5028 wxThread::Sleep(200);
5030 // wake all the (remaining) threads up, so that they can exit
5031 printf("Main thread: about to broadcast the condition.\n");
5033 condition
.Broadcast();
5035 // give them time to terminate (dirty!)
5036 wxThread::Sleep(500);
5039 #include "wx/utils.h"
5041 class MyExecThread
: public wxThread
5044 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5050 virtual ExitCode
Entry()
5052 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5059 static void TestThreadExec()
5061 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5063 MyExecThread
thread(_T("true"));
5066 wxPrintf(_T("Main program exit code: %ld.\n"),
5067 wxExecute(_T("false"), wxEXEC_SYNC
));
5069 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5073 #include "wx/datetime.h"
5075 class MySemaphoreThread
: public wxThread
5078 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5079 : wxThread(wxTHREAD_JOINABLE
),
5086 virtual ExitCode
Entry()
5088 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
5089 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5093 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
5094 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5098 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
5099 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5111 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5113 static void TestSemaphore()
5115 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5117 static const int SEM_LIMIT
= 3;
5119 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5120 ArrayThreads threads
;
5122 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5124 threads
.Add(new MySemaphoreThread(i
, &sem
));
5125 threads
.Last()->Run();
5128 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5135 #endif // TEST_THREADS
5137 // ----------------------------------------------------------------------------
5139 // ----------------------------------------------------------------------------
5143 #include "wx/dynarray.h"
5145 typedef unsigned short ushort
;
5147 #define DefineCompare(name, T) \
5149 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5151 return first - second; \
5154 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5156 return *first - *second; \
5159 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5161 return *second - *first; \
5164 DefineCompare(UShort, ushort);
5165 DefineCompare(Int
, int);
5167 // test compilation of all macros
5168 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5169 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5170 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5171 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5173 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5174 #include "wx/arrimpl.cpp"
5175 WX_DEFINE_OBJARRAY(ArrayBars
);
5177 static void PrintArray(const char* name
, const wxArrayString
& array
)
5179 printf("Dump of the array '%s'\n", name
);
5181 size_t nCount
= array
.GetCount();
5182 for ( size_t n
= 0; n
< nCount
; n
++ )
5184 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5188 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5189 const wxString
& second
)
5191 return first
.length() - second
.length();
5194 #define TestArrayOf(name) \
5196 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5198 printf("Dump of the array '%s'\n", name); \
5200 size_t nCount = array.GetCount(); \
5201 for ( size_t n = 0; n < nCount; n++ ) \
5203 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5207 static void PrintArray(const char* name, const wxArray##name & array) \
5209 printf("Dump of the array '%s'\n", name); \
5211 size_t nCount = array.GetCount(); \
5212 for ( size_t n = 0; n < nCount; n++ ) \
5214 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5218 static void TestArrayOf ## name ## s() \
5220 printf("*** Testing wxArray%s ***\n", #name); \
5228 puts("Initially:"); \
5229 PrintArray("a", a); \
5231 puts("After sort:"); \
5232 a.Sort(name ## Compare); \
5233 PrintArray("a", a); \
5235 puts("After reverse sort:"); \
5236 a.Sort(name ## RevCompare); \
5237 PrintArray("a", a); \
5239 wxSortedArray##name b; \
5245 puts("Sorted array initially:"); \
5246 PrintArray("b", b); \
5249 TestArrayOf(UShort
);
5252 static void TestArrayOfObjects()
5254 puts("*** Testing wxObjArray ***\n");
5258 Bar
bar("second bar (two copies!)");
5260 printf("Initially: %u objects in the array, %u objects total.\n",
5261 bars
.GetCount(), Bar::GetNumber());
5263 bars
.Add(new Bar("first bar"));
5266 printf("Now: %u objects in the array, %u objects total.\n",
5267 bars
.GetCount(), Bar::GetNumber());
5269 bars
.RemoveAt(1, bars
.GetCount() - 1);
5271 printf("After removing all but first element: %u objects in the "
5272 "array, %u objects total.\n",
5273 bars
.GetCount(), Bar::GetNumber());
5277 printf("After Empty(): %u objects in the array, %u objects total.\n",
5278 bars
.GetCount(), Bar::GetNumber());
5281 printf("Finally: no more objects in the array, %u objects total.\n",
5285 #endif // TEST_ARRAYS
5287 // ----------------------------------------------------------------------------
5289 // ----------------------------------------------------------------------------
5293 #include "wx/timer.h"
5294 #include "wx/tokenzr.h"
5296 static void TestStringConstruction()
5298 puts("*** Testing wxString constructores ***");
5300 #define TEST_CTOR(args, res) \
5303 printf("wxString%s = %s ", #args, s.c_str()); \
5310 printf("(ERROR: should be %s)\n", res); \
5314 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5315 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5316 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5317 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5319 static const wxChar
*s
= _T("?really!");
5320 const wxChar
*start
= wxStrchr(s
, _T('r'));
5321 const wxChar
*end
= wxStrchr(s
, _T('!'));
5322 TEST_CTOR((start
, end
), _T("really"));
5327 static void TestString()
5337 for (int i
= 0; i
< 1000000; ++i
)
5341 c
= "! How'ya doin'?";
5344 c
= "Hello world! What's up?";
5349 printf ("TestString elapsed time: %ld\n", sw
.Time());
5352 static void TestPChar()
5360 for (int i
= 0; i
< 1000000; ++i
)
5362 strcpy (a
, "Hello");
5363 strcpy (b
, " world");
5364 strcpy (c
, "! How'ya doin'?");
5367 strcpy (c
, "Hello world! What's up?");
5368 if (strcmp (c
, a
) == 0)
5372 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5375 static void TestStringSub()
5377 wxString
s("Hello, world!");
5379 puts("*** Testing wxString substring extraction ***");
5381 printf("String = '%s'\n", s
.c_str());
5382 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5383 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5384 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5385 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5386 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5387 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5389 static const wxChar
*prefixes
[] =
5393 _T("Hello, world!"),
5394 _T("Hello, world!!!"),
5400 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5402 wxString prefix
= prefixes
[n
], rest
;
5403 bool rc
= s
.StartsWith(prefix
, &rest
);
5404 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5407 printf(" (the rest is '%s')\n", rest
.c_str());
5418 static void TestStringFormat()
5420 puts("*** Testing wxString formatting ***");
5423 s
.Printf("%03d", 18);
5425 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5426 printf("Number 18: %s\n", s
.c_str());
5431 // returns "not found" for npos, value for all others
5432 static wxString
PosToString(size_t res
)
5434 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5435 : wxString::Format(_T("%u"), res
);
5439 static void TestStringFind()
5441 puts("*** Testing wxString find() functions ***");
5443 static const wxChar
*strToFind
= _T("ell");
5444 static const struct StringFindTest
5448 result
; // of searching "ell" in str
5451 { _T("Well, hello world"), 0, 1 },
5452 { _T("Well, hello world"), 6, 7 },
5453 { _T("Well, hello world"), 9, wxString::npos
},
5456 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5458 const StringFindTest
& ft
= findTestData
[n
];
5459 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5461 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5462 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5464 size_t resTrue
= ft
.result
;
5465 if ( res
== resTrue
)
5471 printf(_T("(ERROR: should be %s)\n"),
5472 PosToString(resTrue
).c_str());
5479 static void TestStringTokenizer()
5481 puts("*** Testing wxStringTokenizer ***");
5483 static const wxChar
*modeNames
[] =
5487 _T("return all empty"),
5492 static const struct StringTokenizerTest
5494 const wxChar
*str
; // string to tokenize
5495 const wxChar
*delims
; // delimiters to use
5496 size_t count
; // count of token
5497 wxStringTokenizerMode mode
; // how should we tokenize it
5498 } tokenizerTestData
[] =
5500 { _T(""), _T(" "), 0 },
5501 { _T("Hello, world"), _T(" "), 2 },
5502 { _T("Hello, world "), _T(" "), 2 },
5503 { _T("Hello, world"), _T(","), 2 },
5504 { _T("Hello, world!"), _T(",!"), 2 },
5505 { _T("Hello,, world!"), _T(",!"), 3 },
5506 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5507 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5508 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5509 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5510 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5511 { _T("01/02/99"), _T("/-"), 3 },
5512 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5515 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5517 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5518 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5520 size_t count
= tkz
.CountTokens();
5521 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5522 MakePrintable(tt
.str
).c_str(),
5524 MakePrintable(tt
.delims
).c_str(),
5525 modeNames
[tkz
.GetMode()]);
5526 if ( count
== tt
.count
)
5532 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5537 // if we emulate strtok(), check that we do it correctly
5538 wxChar
*buf
, *s
= NULL
, *last
;
5540 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5542 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5543 wxStrcpy(buf
, tt
.str
);
5545 s
= wxStrtok(buf
, tt
.delims
, &last
);
5552 // now show the tokens themselves
5554 while ( tkz
.HasMoreTokens() )
5556 wxString token
= tkz
.GetNextToken();
5558 printf(_T("\ttoken %u: '%s'"),
5560 MakePrintable(token
).c_str());
5570 printf(" (ERROR: should be %s)\n", s
);
5573 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5577 // nothing to compare with
5582 if ( count2
!= count
)
5584 puts(_T("\tERROR: token count mismatch"));
5593 static void TestStringReplace()
5595 puts("*** Testing wxString::replace ***");
5597 static const struct StringReplaceTestData
5599 const wxChar
*original
; // original test string
5600 size_t start
, len
; // the part to replace
5601 const wxChar
*replacement
; // the replacement string
5602 const wxChar
*result
; // and the expected result
5603 } stringReplaceTestData
[] =
5605 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5606 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5607 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5608 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5609 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5612 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5614 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5616 wxString original
= data
.original
;
5617 original
.replace(data
.start
, data
.len
, data
.replacement
);
5619 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5620 data
.original
, data
.start
, data
.len
, data
.replacement
,
5623 if ( original
== data
.result
)
5629 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5636 static void TestStringMatch()
5638 wxPuts(_T("*** Testing wxString::Matches() ***"));
5640 static const struct StringMatchTestData
5643 const wxChar
*wildcard
;
5645 } stringMatchTestData
[] =
5647 { _T("foobar"), _T("foo*"), 1 },
5648 { _T("foobar"), _T("*oo*"), 1 },
5649 { _T("foobar"), _T("*bar"), 1 },
5650 { _T("foobar"), _T("??????"), 1 },
5651 { _T("foobar"), _T("f??b*"), 1 },
5652 { _T("foobar"), _T("f?b*"), 0 },
5653 { _T("foobar"), _T("*goo*"), 0 },
5654 { _T("foobar"), _T("*foo"), 0 },
5655 { _T("foobarfoo"), _T("*foo"), 1 },
5656 { _T(""), _T("*"), 1 },
5657 { _T(""), _T("?"), 0 },
5660 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5662 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5663 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5664 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5666 matches
? _T("matches") : _T("doesn't match"),
5668 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5674 #endif // TEST_STRINGS
5676 // ----------------------------------------------------------------------------
5678 // ----------------------------------------------------------------------------
5680 #ifdef TEST_SNGLINST
5681 #include "wx/snglinst.h"
5682 #endif // TEST_SNGLINST
5684 int main(int argc
, char **argv
)
5686 wxApp::CheckBuildOptions(wxBuildOptions());
5688 wxInitializer initializer
;
5691 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5696 #ifdef TEST_SNGLINST
5697 wxSingleInstanceChecker checker
;
5698 if ( checker
.Create(_T(".wxconsole.lock")) )
5700 if ( checker
.IsAnotherRunning() )
5702 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5707 // wait some time to give time to launch another instance
5708 wxPrintf(_T("Press \"Enter\" to continue..."));
5711 else // failed to create
5713 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5715 #endif // TEST_SNGLINST
5719 #endif // TEST_CHARSET
5722 TestCmdLineConvert();
5724 #if wxUSE_CMDLINE_PARSER
5725 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5727 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5728 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5729 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5730 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5732 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5733 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5734 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5735 wxCMD_LINE_VAL_NUMBER
},
5736 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5737 wxCMD_LINE_VAL_DATE
},
5739 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5740 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5745 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5747 parser
.AddOption("project_name", "", "full path to project file",
5748 wxCMD_LINE_VAL_STRING
,
5749 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5751 switch ( parser
.Parse() )
5754 wxLogMessage("Help was given, terminating.");
5758 ShowCmdLine(parser
);
5762 wxLogMessage("Syntax error detected, aborting.");
5765 #endif // wxUSE_CMDLINE_PARSER
5767 #endif // TEST_CMDLINE
5775 TestStringConstruction();
5778 TestStringTokenizer();
5779 TestStringReplace();
5785 #endif // TEST_STRINGS
5798 puts("*** Initially:");
5800 PrintArray("a1", a1
);
5802 wxArrayString
a2(a1
);
5803 PrintArray("a2", a2
);
5805 wxSortedArrayString
a3(a1
);
5806 PrintArray("a3", a3
);
5808 puts("*** After deleting three strings from a1");
5811 PrintArray("a1", a1
);
5812 PrintArray("a2", a2
);
5813 PrintArray("a3", a3
);
5815 puts("*** After reassigning a1 to a2 and a3");
5817 PrintArray("a2", a2
);
5818 PrintArray("a3", a3
);
5820 puts("*** After sorting a1");
5822 PrintArray("a1", a1
);
5824 puts("*** After sorting a1 in reverse order");
5826 PrintArray("a1", a1
);
5828 puts("*** After sorting a1 by the string length");
5829 a1
.Sort(StringLenCompare
);
5830 PrintArray("a1", a1
);
5832 TestArrayOfObjects();
5833 TestArrayOfUShorts();
5837 #endif // TEST_ARRAYS
5848 #ifdef TEST_DLLLOADER
5850 #endif // TEST_DLLLOADER
5854 #endif // TEST_ENVIRON
5858 #endif // TEST_EXECUTE
5860 #ifdef TEST_FILECONF
5862 #endif // TEST_FILECONF
5870 #endif // TEST_LOCALE
5874 for ( size_t n
= 0; n
< 8000; n
++ )
5876 s
<< (char)('A' + (n
% 26));
5880 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5882 // this one shouldn't be truncated
5885 // but this one will because log functions use fixed size buffer
5886 // (note that it doesn't need '\n' at the end neither - will be added
5888 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5900 #ifdef TEST_FILENAME
5904 fn
.Assign("c:\\foo", "bar.baz");
5905 fn
.Assign("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc");
5910 TestFileNameConstruction();
5913 TestFileNameConstruction();
5914 TestFileNameMakeRelative();
5915 TestFileNameSplit();
5918 TestFileNameComparison();
5919 TestFileNameOperations();
5921 #endif // TEST_FILENAME
5923 #ifdef TEST_FILETIME
5927 #endif // TEST_FILETIME
5930 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5931 if ( TestFtpConnect() )
5942 if ( TEST_INTERACTIVE
)
5943 TestFtpInteractive();
5945 //else: connecting to the FTP server failed
5951 #ifdef TEST_LONGLONG
5952 // seed pseudo random generator
5953 srand((unsigned)time(NULL
));
5962 TestMultiplication();
5965 TestLongLongConversion();
5966 TestBitOperations();
5967 TestLongLongComparison();
5968 TestLongLongPrint();
5970 #endif // TEST_LONGLONG
5978 #endif // TEST_HASHMAP
5981 wxLog::AddTraceMask(_T("mime"));
5986 TestMimeAssociate();
5991 #ifdef TEST_INFO_FUNCTIONS
5997 if ( TEST_INTERACTIVE
)
6000 #endif // TEST_INFO_FUNCTIONS
6002 #ifdef TEST_PATHLIST
6004 #endif // TEST_PATHLIST
6012 #endif // TEST_REGCONF
6015 // TODO: write a real test using src/regex/tests file
6020 TestRegExSubmatch();
6021 TestRegExReplacement();
6023 if ( TEST_INTERACTIVE
)
6024 TestRegExInteractive();
6026 #endif // TEST_REGEX
6028 #ifdef TEST_REGISTRY
6030 TestRegistryAssociation();
6031 #endif // TEST_REGISTRY
6036 #endif // TEST_SOCKETS
6041 #endif // TEST_STREAMS
6044 int nCPUs
= wxThread::GetCPUCount();
6045 printf("This system has %d CPUs\n", nCPUs
);
6047 wxThread::SetConcurrency(nCPUs
);
6051 TestDetachedThreads();
6052 TestJoinableThreads();
6053 TestThreadSuspend();
6055 TestThreadConditions();
6060 #endif // TEST_THREADS
6064 #endif // TEST_TIMER
6066 #ifdef TEST_DATETIME
6079 TestTimeArithmetics();
6082 TestTimeSpanFormat();
6088 if ( TEST_INTERACTIVE
)
6089 TestDateTimeInteractive();
6090 #endif // TEST_DATETIME
6093 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6095 #endif // TEST_USLEEP
6100 #endif // TEST_VCARD
6104 #endif // TEST_VOLUME
6108 TestEncodingConverter();
6109 #endif // TEST_WCHAR
6112 TestZipStreamRead();
6113 TestZipFileSystem();
6117 TestZlibStreamWrite();
6118 TestZlibStreamRead();