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
},
870 // wxFileName support for Mac file names is broken currently
873 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
874 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
875 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
876 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
877 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
878 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
882 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
883 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
886 static void TestFileNameConstruction()
888 puts("*** testing wxFileName construction ***");
890 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
892 const FileNameInfo
& fni
= filenames
[n
];
894 wxFileName
fn(fni
.fullname
, fni
.format
);
896 wxString fullname
= fn
.GetFullPath(fni
.format
);
897 if ( fullname
!= fni
.fullname
)
899 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
902 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
903 printf("'%s' is %s (%s)\n\t",
905 isAbsolute
? "absolute" : "relative",
906 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
908 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
910 puts("ERROR (couldn't be normalized)");
914 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
921 static void TestFileNameSplit()
923 puts("*** testing wxFileName splitting ***");
925 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
927 const FileNameInfo
& fni
= filenames
[n
];
928 wxString volume
, path
, name
, ext
;
929 wxFileName::SplitPath(fni
.fullname
,
930 &volume
, &path
, &name
, &ext
, fni
.format
);
932 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
934 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
936 if ( volume
!= fni
.volume
)
937 printf(" (ERROR: volume = '%s')", fni
.volume
);
938 if ( path
!= fni
.path
)
939 printf(" (ERROR: path = '%s')", fni
.path
);
940 if ( name
!= fni
.name
)
941 printf(" (ERROR: name = '%s')", fni
.name
);
942 if ( ext
!= fni
.ext
)
943 printf(" (ERROR: ext = '%s')", fni
.ext
);
949 static void TestFileNameTemp()
951 puts("*** testing wxFileName temp file creation ***");
953 static const char *tmpprefixes
[] =
961 "/tmp/foo/bar", // this one must be an error
965 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
967 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
970 // "error" is not in upper case because it may be ok
971 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
975 printf("Prefix '%s'\t-> temp file '%s'\n",
976 tmpprefixes
[n
], path
.c_str());
978 if ( !wxRemoveFile(path
) )
980 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
986 static void TestFileNameMakeRelative()
988 puts("*** testing wxFileName::MakeRelativeTo() ***");
990 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
992 const FileNameInfo
& fni
= filenames
[n
];
994 wxFileName
fn(fni
.fullname
, fni
.format
);
996 // choose the base dir of the same format
998 switch ( fni
.format
)
1010 // TODO: I don't know how this is supposed to work there
1013 case wxPATH_NATIVE
: // make gcc happy
1015 wxFAIL_MSG( "unexpected path format" );
1018 printf("'%s' relative to '%s': ",
1019 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
1021 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
1027 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
1032 static void TestFileNameComparison()
1037 static void TestFileNameOperations()
1042 static void TestFileNameCwd()
1047 #endif // TEST_FILENAME
1049 // ----------------------------------------------------------------------------
1050 // wxFileName time functions
1051 // ----------------------------------------------------------------------------
1053 #ifdef TEST_FILETIME
1055 #include <wx/filename.h>
1056 #include <wx/datetime.h>
1058 static void TestFileGetTimes()
1060 wxFileName
fn(_T("testdata.fc"));
1062 wxDateTime dtAccess
, dtMod
, dtCreate
;
1063 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1065 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1069 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1071 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1072 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1073 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1074 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1078 static void TestFileSetTimes()
1080 wxFileName
fn(_T("testdata.fc"));
1084 wxPrintf(_T("ERROR: Touch() failed.\n"));
1088 #endif // TEST_FILETIME
1090 // ----------------------------------------------------------------------------
1092 // ----------------------------------------------------------------------------
1096 #include "wx/hash.h"
1100 Foo(int n_
) { n
= n_
; count
++; }
1105 static size_t count
;
1108 size_t Foo::count
= 0;
1110 WX_DECLARE_LIST(Foo
, wxListFoos
);
1111 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1113 #include "wx/listimpl.cpp"
1115 WX_DEFINE_LIST(wxListFoos
);
1117 static void TestHash()
1119 puts("*** Testing wxHashTable ***\n");
1123 hash
.DeleteContents(TRUE
);
1125 printf("Hash created: %u foos in hash, %u foos totally\n",
1126 hash
.GetCount(), Foo::count
);
1128 static const int hashTestData
[] =
1130 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1134 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1136 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1139 printf("Hash filled: %u foos in hash, %u foos totally\n",
1140 hash
.GetCount(), Foo::count
);
1142 puts("Hash access test:");
1143 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1145 printf("\tGetting element with key %d, value %d: ",
1146 hashTestData
[n
], n
);
1147 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1150 printf("ERROR, not found.\n");
1154 printf("%d (%s)\n", foo
->n
,
1155 (size_t)foo
->n
== n
? "ok" : "ERROR");
1159 printf("\nTrying to get an element not in hash: ");
1161 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1163 puts("ERROR: found!");
1167 puts("ok (not found)");
1171 printf("Hash destroyed: %u foos left\n", Foo::count
);
1176 // ----------------------------------------------------------------------------
1178 // ----------------------------------------------------------------------------
1182 #include "wx/hashmap.h"
1184 // test compilation of basic map types
1185 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1186 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1187 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1188 myUnsignedHashMap
);
1189 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1191 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1193 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1195 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1199 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1200 // myStringHashMap );
1201 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1203 typedef myStringHashMap::iterator Itor
;
1205 static void TestHashMap()
1207 puts("*** Testing wxHashMap ***\n");
1208 myStringHashMap
sh(0); // as small as possible
1211 const size_t count
= 10000;
1213 // init with some data
1214 for( i
= 0; i
< count
; ++i
)
1216 buf
.Printf(wxT("%d"), i
);
1217 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1220 // test that insertion worked
1221 if( sh
.size() != count
)
1223 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1226 for( i
= 0; i
< count
; ++i
)
1228 buf
.Printf(wxT("%d"), i
);
1229 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1231 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1236 // check that iterators work
1238 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1242 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1246 if( it
->second
!= sh
[it
->first
] )
1248 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1253 if( sh
.size() != i
)
1255 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1258 // test copy ctor, assignment operator
1259 myStringHashMap
h1( sh
), h2( 0 );
1262 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1264 if( h1
[it
->first
] != it
->second
)
1266 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1269 if( h2
[it
->first
] != it
->second
)
1271 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1276 for( i
= 0; i
< count
; ++i
)
1278 buf
.Printf(wxT("%d"), i
);
1279 size_t sz
= sh
.size();
1281 // test find() and erase(it)
1284 it
= sh
.find( buf
);
1285 if( it
!= sh
.end() )
1289 if( sh
.find( buf
) != sh
.end() )
1291 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1295 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1300 size_t c
= sh
.erase( buf
);
1302 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1304 if( sh
.find( buf
) != sh
.end() )
1306 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1310 // count should decrease
1311 if( sh
.size() != sz
- 1 )
1313 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1317 printf("*** Finished testing wxHashMap ***\n");
1320 #endif // TEST_HASHMAP
1322 // ----------------------------------------------------------------------------
1324 // ----------------------------------------------------------------------------
1328 #include "wx/list.h"
1330 WX_DECLARE_LIST(Bar
, wxListBars
);
1331 #include "wx/listimpl.cpp"
1332 WX_DEFINE_LIST(wxListBars
);
1334 static void TestListCtor()
1336 puts("*** Testing wxList construction ***\n");
1340 list1
.Append(new Bar(_T("first")));
1341 list1
.Append(new Bar(_T("second")));
1343 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1344 list1
.GetCount(), Bar::GetNumber());
1349 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1350 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1352 list1
.DeleteContents(TRUE
);
1355 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1360 // ----------------------------------------------------------------------------
1362 // ----------------------------------------------------------------------------
1366 #include "wx/intl.h"
1367 #include "wx/utils.h" // for wxSetEnv
1369 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1371 // find the name of the language from its value
1372 static const char *GetLangName(int lang
)
1374 static const char *languageNames
[] =
1395 "ARABIC_SAUDI_ARABIA",
1420 "CHINESE_SIMPLIFIED",
1421 "CHINESE_TRADITIONAL",
1424 "CHINESE_SINGAPORE",
1435 "ENGLISH_AUSTRALIA",
1439 "ENGLISH_CARIBBEAN",
1443 "ENGLISH_NEW_ZEALAND",
1444 "ENGLISH_PHILIPPINES",
1445 "ENGLISH_SOUTH_AFRICA",
1457 "FRENCH_LUXEMBOURG",
1466 "GERMAN_LIECHTENSTEIN",
1467 "GERMAN_LUXEMBOURG",
1508 "MALAY_BRUNEI_DARUSSALAM",
1520 "NORWEGIAN_NYNORSK",
1527 "PORTUGUESE_BRAZILIAN",
1552 "SPANISH_ARGENTINA",
1556 "SPANISH_COSTA_RICA",
1557 "SPANISH_DOMINICAN_REPUBLIC",
1559 "SPANISH_EL_SALVADOR",
1560 "SPANISH_GUATEMALA",
1564 "SPANISH_NICARAGUA",
1568 "SPANISH_PUERTO_RICO",
1571 "SPANISH_VENEZUELA",
1608 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1609 return languageNames
[lang
];
1614 static void TestDefaultLang()
1616 puts("*** Testing wxLocale::GetSystemLanguage ***");
1618 static const wxChar
*langStrings
[] =
1620 NULL
, // system default
1627 _T("de_DE.iso88591"),
1629 _T("?"), // invalid lang spec
1630 _T("klingonese"), // I bet on some systems it does exist...
1633 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1634 wxLocale::GetSystemEncodingName().c_str(),
1635 wxLocale::GetSystemEncoding());
1637 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1639 const char *langStr
= langStrings
[n
];
1642 // FIXME: this doesn't do anything at all under Windows, we need
1643 // to create a new wxLocale!
1644 wxSetEnv(_T("LC_ALL"), langStr
);
1647 int lang
= gs_localeDefault
.GetSystemLanguage();
1648 printf("Locale for '%s' is %s.\n",
1649 langStr
? langStr
: "system default", GetLangName(lang
));
1653 #endif // TEST_LOCALE
1655 // ----------------------------------------------------------------------------
1657 // ----------------------------------------------------------------------------
1661 #include "wx/mimetype.h"
1663 static void TestMimeEnum()
1665 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1667 wxArrayString mimetypes
;
1669 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1671 printf("*** All %u known filetypes: ***\n", count
);
1676 for ( size_t n
= 0; n
< count
; n
++ )
1678 wxFileType
*filetype
=
1679 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1682 printf("nothing known about the filetype '%s'!\n",
1683 mimetypes
[n
].c_str());
1687 filetype
->GetDescription(&desc
);
1688 filetype
->GetExtensions(exts
);
1690 filetype
->GetIcon(NULL
);
1693 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1696 extsAll
<< _T(", ");
1700 printf("\t%s: %s (%s)\n",
1701 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1707 static void TestMimeOverride()
1709 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1711 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1712 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1714 if ( wxFile::Exists(mailcap
) )
1715 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1717 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1719 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1722 if ( wxFile::Exists(mimetypes
) )
1723 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1725 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1727 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1733 static void TestMimeFilename()
1735 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1737 static const wxChar
*filenames
[] =
1744 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1746 const wxString fname
= filenames
[n
];
1747 wxString ext
= fname
.AfterLast(_T('.'));
1748 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1751 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1756 if ( !ft
->GetDescription(&desc
) )
1757 desc
= _T("<no description>");
1760 if ( !ft
->GetOpenCommand(&cmd
,
1761 wxFileType::MessageParameters(fname
, _T(""))) )
1762 cmd
= _T("<no command available>");
1764 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1765 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1774 static void TestMimeAssociate()
1776 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1778 wxFileTypeInfo
ftInfo(
1779 _T("application/x-xyz"),
1780 _T("xyzview '%s'"), // open cmd
1781 _T(""), // print cmd
1782 _T("XYZ File"), // description
1783 _T(".xyz"), // extensions
1784 NULL
// end of extensions
1786 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1788 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1791 wxPuts(_T("ERROR: failed to create association!"));
1795 // TODO: read it back
1804 // ----------------------------------------------------------------------------
1805 // misc information functions
1806 // ----------------------------------------------------------------------------
1808 #ifdef TEST_INFO_FUNCTIONS
1810 #include "wx/utils.h"
1812 static void TestDiskInfo()
1814 puts("*** Testing wxGetDiskSpace() ***");
1819 printf("\nEnter a directory name: ");
1820 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1823 // kill the last '\n'
1824 pathname
[strlen(pathname
) - 1] = 0;
1826 wxLongLong total
, free
;
1827 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1829 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1833 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1834 (total
/ 1024).ToString().c_str(),
1835 (free
/ 1024).ToString().c_str(),
1841 static void TestOsInfo()
1843 puts("*** Testing OS info functions ***\n");
1846 wxGetOsVersion(&major
, &minor
);
1847 printf("Running under: %s, version %d.%d\n",
1848 wxGetOsDescription().c_str(), major
, minor
);
1850 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1852 printf("Host name is %s (%s).\n",
1853 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1858 static void TestUserInfo()
1860 puts("*** Testing user info functions ***\n");
1862 printf("User id is:\t%s\n", wxGetUserId().c_str());
1863 printf("User name is:\t%s\n", wxGetUserName().c_str());
1864 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1865 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1870 #endif // TEST_INFO_FUNCTIONS
1872 // ----------------------------------------------------------------------------
1874 // ----------------------------------------------------------------------------
1876 #ifdef TEST_LONGLONG
1878 #include "wx/longlong.h"
1879 #include "wx/timer.h"
1881 // make a 64 bit number from 4 16 bit ones
1882 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1884 // get a random 64 bit number
1885 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1887 static const long testLongs
[] =
1898 #if wxUSE_LONGLONG_WX
1899 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1900 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1901 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1902 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1903 #endif // wxUSE_LONGLONG_WX
1905 static void TestSpeed()
1907 static const long max
= 100000000;
1914 for ( n
= 0; n
< max
; n
++ )
1919 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1922 #if wxUSE_LONGLONG_NATIVE
1927 for ( n
= 0; n
< max
; n
++ )
1932 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1934 #endif // wxUSE_LONGLONG_NATIVE
1940 for ( n
= 0; n
< max
; n
++ )
1945 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1949 static void TestLongLongConversion()
1951 puts("*** Testing wxLongLong conversions ***\n");
1955 for ( size_t n
= 0; n
< 100000; n
++ )
1959 #if wxUSE_LONGLONG_NATIVE
1960 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1962 wxASSERT_MSG( a
== b
, "conversions failure" );
1964 puts("Can't do it without native long long type, test skipped.");
1967 #endif // wxUSE_LONGLONG_NATIVE
1969 if ( !(nTested
% 1000) )
1981 static void TestMultiplication()
1983 puts("*** Testing wxLongLong multiplication ***\n");
1987 for ( size_t n
= 0; n
< 100000; n
++ )
1992 #if wxUSE_LONGLONG_NATIVE
1993 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1994 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1996 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1997 #else // !wxUSE_LONGLONG_NATIVE
1998 puts("Can't do it without native long long type, test skipped.");
2001 #endif // wxUSE_LONGLONG_NATIVE
2003 if ( !(nTested
% 1000) )
2015 static void TestDivision()
2017 puts("*** Testing wxLongLong division ***\n");
2021 for ( size_t n
= 0; n
< 100000; n
++ )
2023 // get a random wxLongLong (shifting by 12 the MSB ensures that the
2024 // multiplication will not overflow)
2025 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
2027 // get a random (but non null) long (not wxLongLong for now) to divide
2039 #if wxUSE_LONGLONG_NATIVE
2040 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
2042 wxLongLongNative p
= m
/ l
, s
= m
% l
;
2043 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
2044 #else // !wxUSE_LONGLONG_NATIVE
2045 // verify the result
2046 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
2047 #endif // wxUSE_LONGLONG_NATIVE
2049 if ( !(nTested
% 1000) )
2061 static void TestAddition()
2063 puts("*** Testing wxLongLong addition ***\n");
2067 for ( size_t n
= 0; n
< 100000; n
++ )
2073 #if wxUSE_LONGLONG_NATIVE
2074 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2075 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2076 "addition failure" );
2077 #else // !wxUSE_LONGLONG_NATIVE
2078 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2079 #endif // wxUSE_LONGLONG_NATIVE
2081 if ( !(nTested
% 1000) )
2093 static void TestBitOperations()
2095 puts("*** Testing wxLongLong bit operation ***\n");
2099 for ( size_t n
= 0; n
< 100000; n
++ )
2103 #if wxUSE_LONGLONG_NATIVE
2104 for ( size_t n
= 0; n
< 33; n
++ )
2107 #else // !wxUSE_LONGLONG_NATIVE
2108 puts("Can't do it without native long long type, test skipped.");
2111 #endif // wxUSE_LONGLONG_NATIVE
2113 if ( !(nTested
% 1000) )
2125 static void TestLongLongComparison()
2127 #if wxUSE_LONGLONG_WX
2128 puts("*** Testing wxLongLong comparison ***\n");
2130 static const long ls
[2] =
2136 wxLongLongWx lls
[2];
2140 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2144 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2146 res
= lls
[m
] > testLongs
[n
];
2147 printf("0x%lx > 0x%lx is %s (%s)\n",
2148 ls
[m
], testLongs
[n
], res
? "true" : "false",
2149 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2151 res
= lls
[m
] < testLongs
[n
];
2152 printf("0x%lx < 0x%lx is %s (%s)\n",
2153 ls
[m
], testLongs
[n
], res
? "true" : "false",
2154 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2156 res
= lls
[m
] == testLongs
[n
];
2157 printf("0x%lx == 0x%lx is %s (%s)\n",
2158 ls
[m
], testLongs
[n
], res
? "true" : "false",
2159 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2162 #endif // wxUSE_LONGLONG_WX
2165 static void TestLongLongPrint()
2167 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2169 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2171 wxLongLong ll
= testLongs
[n
];
2172 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2175 wxLongLong
ll(0x12345678, 0x87654321);
2176 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2179 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2185 #endif // TEST_LONGLONG
2187 // ----------------------------------------------------------------------------
2189 // ----------------------------------------------------------------------------
2191 #ifdef TEST_PATHLIST
2193 static void TestPathList()
2195 puts("*** Testing wxPathList ***\n");
2197 wxPathList pathlist
;
2198 pathlist
.AddEnvList("PATH");
2199 wxString path
= pathlist
.FindValidPath("ls");
2202 printf("ERROR: command not found in the path.\n");
2206 printf("Command found in the path as '%s'.\n", path
.c_str());
2210 #endif // TEST_PATHLIST
2212 // ----------------------------------------------------------------------------
2213 // regular expressions
2214 // ----------------------------------------------------------------------------
2218 #include "wx/regex.h"
2220 static void TestRegExCompile()
2222 wxPuts(_T("*** Testing RE compilation ***\n"));
2224 static struct RegExCompTestData
2226 const wxChar
*pattern
;
2228 } regExCompTestData
[] =
2230 { _T("foo"), TRUE
},
2231 { _T("foo("), FALSE
},
2232 { _T("foo(bar"), FALSE
},
2233 { _T("foo(bar)"), TRUE
},
2234 { _T("foo["), FALSE
},
2235 { _T("foo[bar"), FALSE
},
2236 { _T("foo[bar]"), TRUE
},
2237 { _T("foo{"), TRUE
},
2238 { _T("foo{1"), FALSE
},
2239 { _T("foo{bar"), TRUE
},
2240 { _T("foo{1}"), TRUE
},
2241 { _T("foo{1,2}"), TRUE
},
2242 { _T("foo{bar}"), TRUE
},
2243 { _T("foo*"), TRUE
},
2244 { _T("foo**"), FALSE
},
2245 { _T("foo+"), TRUE
},
2246 { _T("foo++"), FALSE
},
2247 { _T("foo?"), TRUE
},
2248 { _T("foo??"), FALSE
},
2249 { _T("foo?+"), FALSE
},
2253 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2255 const RegExCompTestData
& data
= regExCompTestData
[n
];
2256 bool ok
= re
.Compile(data
.pattern
);
2258 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2260 ok
? _T("") : _T("not "),
2261 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2265 static void TestRegExMatch()
2267 wxPuts(_T("*** Testing RE matching ***\n"));
2269 static struct RegExMatchTestData
2271 const wxChar
*pattern
;
2274 } regExMatchTestData
[] =
2276 { _T("foo"), _T("bar"), FALSE
},
2277 { _T("foo"), _T("foobar"), TRUE
},
2278 { _T("^foo"), _T("foobar"), TRUE
},
2279 { _T("^foo"), _T("barfoo"), FALSE
},
2280 { _T("bar$"), _T("barbar"), TRUE
},
2281 { _T("bar$"), _T("barbar "), FALSE
},
2284 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2286 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2288 wxRegEx
re(data
.pattern
);
2289 bool ok
= re
.Matches(data
.text
);
2291 wxPrintf(_T("'%s' %s %s (%s)\n"),
2293 ok
? _T("matches") : _T("doesn't match"),
2295 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2299 static void TestRegExSubmatch()
2301 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2303 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2304 if ( !re
.IsValid() )
2306 wxPuts(_T("ERROR: compilation failed."));
2310 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2312 if ( !re
.Matches(text
) )
2314 wxPuts(_T("ERROR: match expected."));
2318 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2320 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2321 re
.GetMatch(text
, 3).c_str(),
2322 re
.GetMatch(text
, 2).c_str(),
2323 re
.GetMatch(text
, 4).c_str(),
2324 re
.GetMatch(text
, 1).c_str());
2328 static void TestRegExReplacement()
2330 wxPuts(_T("*** Testing RE replacement ***"));
2332 static struct RegExReplTestData
2336 const wxChar
*result
;
2338 } regExReplTestData
[] =
2340 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2341 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2342 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2343 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2344 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2345 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2346 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2349 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2350 wxRegEx
re(pattern
);
2352 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2354 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2356 const RegExReplTestData
& data
= regExReplTestData
[n
];
2358 wxString text
= data
.text
;
2359 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2361 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2362 data
.text
, data
.repl
,
2363 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2365 if ( text
== data
.result
&& nRepl
== data
.count
)
2371 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2372 data
.count
, data
.result
);
2377 static void TestRegExInteractive()
2379 wxPuts(_T("*** Testing RE interactively ***"));
2384 printf("\nEnter a pattern: ");
2385 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2388 // kill the last '\n'
2389 pattern
[strlen(pattern
) - 1] = 0;
2392 if ( !re
.Compile(pattern
) )
2400 printf("Enter text to match: ");
2401 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2404 // kill the last '\n'
2405 text
[strlen(text
) - 1] = 0;
2407 if ( !re
.Matches(text
) )
2409 printf("No match.\n");
2413 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2416 for ( size_t n
= 1; ; n
++ )
2418 if ( !re
.GetMatch(&start
, &len
, n
) )
2423 printf("Subexpr %u matched '%s'\n",
2424 n
, wxString(text
+ start
, len
).c_str());
2431 #endif // TEST_REGEX
2433 // ----------------------------------------------------------------------------
2435 // ----------------------------------------------------------------------------
2445 static void TestDbOpen()
2453 // ----------------------------------------------------------------------------
2454 // registry and related stuff
2455 // ----------------------------------------------------------------------------
2457 // this is for MSW only
2460 #undef TEST_REGISTRY
2465 #include "wx/confbase.h"
2466 #include "wx/msw/regconf.h"
2468 static void TestRegConfWrite()
2470 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2471 regconf
.Write(_T("Hello"), wxString(_T("world")));
2474 #endif // TEST_REGCONF
2476 #ifdef TEST_REGISTRY
2478 #include "wx/msw/registry.h"
2480 // I chose this one because I liked its name, but it probably only exists under
2482 static const wxChar
*TESTKEY
=
2483 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2485 static void TestRegistryRead()
2487 puts("*** testing registry reading ***");
2489 wxRegKey
key(TESTKEY
);
2490 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2493 puts("ERROR: test key can't be opened, aborting test.");
2498 size_t nSubKeys
, nValues
;
2499 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2501 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2504 printf("Enumerating values:\n");
2508 bool cont
= key
.GetFirstValue(value
, dummy
);
2511 printf("Value '%s': type ", value
.c_str());
2512 switch ( key
.GetValueType(value
) )
2514 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2515 case wxRegKey::Type_String
: printf("SZ"); break;
2516 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2517 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2518 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2519 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2520 default: printf("other (unknown)"); break;
2523 printf(", value = ");
2524 if ( key
.IsNumericValue(value
) )
2527 key
.QueryValue(value
, &val
);
2533 key
.QueryValue(value
, val
);
2534 printf("'%s'", val
.c_str());
2536 key
.QueryRawValue(value
, val
);
2537 printf(" (raw value '%s')", val
.c_str());
2542 cont
= key
.GetNextValue(value
, dummy
);
2546 static void TestRegistryAssociation()
2549 The second call to deleteself genertaes an error message, with a
2550 messagebox saying .flo is crucial to system operation, while the .ddf
2551 call also fails, but with no error message
2556 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2558 key
= "ddxf_auto_file" ;
2559 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2561 key
= "ddxf_auto_file" ;
2562 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2565 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2567 key
= "program \"%1\"" ;
2569 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2571 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2573 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2575 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2579 #endif // TEST_REGISTRY
2581 // ----------------------------------------------------------------------------
2583 // ----------------------------------------------------------------------------
2587 #include "wx/socket.h"
2588 #include "wx/protocol/protocol.h"
2589 #include "wx/protocol/http.h"
2591 static void TestSocketServer()
2593 puts("*** Testing wxSocketServer ***\n");
2595 static const int PORT
= 3000;
2600 wxSocketServer
*server
= new wxSocketServer(addr
);
2601 if ( !server
->Ok() )
2603 puts("ERROR: failed to bind");
2610 printf("Server: waiting for connection on port %d...\n", PORT
);
2612 wxSocketBase
*socket
= server
->Accept();
2615 puts("ERROR: wxSocketServer::Accept() failed.");
2619 puts("Server: got a client.");
2621 server
->SetTimeout(60); // 1 min
2623 while ( socket
->IsConnected() )
2629 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2631 // don't log error if the client just close the connection
2632 if ( socket
->IsConnected() )
2634 puts("ERROR: in wxSocket::Read.");
2654 printf("Server: got '%s'.\n", s
.c_str());
2655 if ( s
== _T("bye") )
2662 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2663 socket
->Write("\r\n", 2);
2664 printf("Server: wrote '%s'.\n", s
.c_str());
2667 puts("Server: lost a client.");
2672 // same as "delete server" but is consistent with GUI programs
2676 static void TestSocketClient()
2678 puts("*** Testing wxSocketClient ***\n");
2680 static const char *hostname
= "www.wxwindows.org";
2683 addr
.Hostname(hostname
);
2686 printf("--- Attempting to connect to %s:80...\n", hostname
);
2688 wxSocketClient client
;
2689 if ( !client
.Connect(addr
) )
2691 printf("ERROR: failed to connect to %s\n", hostname
);
2695 printf("--- Connected to %s:%u...\n",
2696 addr
.Hostname().c_str(), addr
.Service());
2700 // could use simply "GET" here I suppose
2702 wxString::Format("GET http://%s/\r\n", hostname
);
2703 client
.Write(cmdGet
, cmdGet
.length());
2704 printf("--- Sent command '%s' to the server\n",
2705 MakePrintable(cmdGet
).c_str());
2706 client
.Read(buf
, WXSIZEOF(buf
));
2707 printf("--- Server replied:\n%s", buf
);
2711 #endif // TEST_SOCKETS
2713 // ----------------------------------------------------------------------------
2715 // ----------------------------------------------------------------------------
2719 #include "wx/protocol/ftp.h"
2723 #define FTP_ANONYMOUS
2725 #ifdef FTP_ANONYMOUS
2726 static const char *directory
= "/pub";
2727 static const char *filename
= "welcome.msg";
2729 static const char *directory
= "/etc";
2730 static const char *filename
= "issue";
2733 static bool TestFtpConnect()
2735 puts("*** Testing FTP connect ***");
2737 #ifdef FTP_ANONYMOUS
2738 static const char *hostname
= "ftp.wxwindows.org";
2740 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2741 #else // !FTP_ANONYMOUS
2742 static const char *hostname
= "localhost";
2745 fgets(user
, WXSIZEOF(user
), stdin
);
2746 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2750 printf("Password for %s: ", password
);
2751 fgets(password
, WXSIZEOF(password
), stdin
);
2752 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2753 ftp
.SetPassword(password
);
2755 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2756 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2758 if ( !ftp
.Connect(hostname
) )
2760 printf("ERROR: failed to connect to %s\n", hostname
);
2766 printf("--- Connected to %s, current directory is '%s'\n",
2767 hostname
, ftp
.Pwd().c_str());
2773 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2774 static void TestFtpWuFtpd()
2777 static const char *hostname
= "ftp.eudora.com";
2778 if ( !ftp
.Connect(hostname
) )
2780 printf("ERROR: failed to connect to %s\n", hostname
);
2784 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2785 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2788 printf("ERROR: couldn't get input stream for %s\n", filename
);
2792 size_t size
= in
->StreamSize();
2793 printf("Reading file %s (%u bytes)...", filename
, size
);
2795 char *data
= new char[size
];
2796 if ( !in
->Read(data
, size
) )
2798 puts("ERROR: read error");
2802 printf("Successfully retrieved the file.\n");
2811 static void TestFtpList()
2813 puts("*** Testing wxFTP file listing ***\n");
2816 if ( !ftp
.ChDir(directory
) )
2818 printf("ERROR: failed to cd to %s\n", directory
);
2821 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2823 // test NLIST and LIST
2824 wxArrayString files
;
2825 if ( !ftp
.GetFilesList(files
) )
2827 puts("ERROR: failed to get NLIST of files");
2831 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2832 size_t count
= files
.GetCount();
2833 for ( size_t n
= 0; n
< count
; n
++ )
2835 printf("\t%s\n", files
[n
].c_str());
2837 puts("End of the file list");
2840 if ( !ftp
.GetDirList(files
) )
2842 puts("ERROR: failed to get LIST of files");
2846 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2847 size_t count
= files
.GetCount();
2848 for ( size_t n
= 0; n
< count
; n
++ )
2850 printf("\t%s\n", files
[n
].c_str());
2852 puts("End of the file list");
2855 if ( !ftp
.ChDir(_T("..")) )
2857 puts("ERROR: failed to cd to ..");
2860 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2863 static void TestFtpDownload()
2865 puts("*** Testing wxFTP download ***\n");
2868 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2871 printf("ERROR: couldn't get input stream for %s\n", filename
);
2875 size_t size
= in
->StreamSize();
2876 printf("Reading file %s (%u bytes)...", filename
, size
);
2879 char *data
= new char[size
];
2880 if ( !in
->Read(data
, size
) )
2882 puts("ERROR: read error");
2886 printf("\nContents of %s:\n%s\n", filename
, data
);
2894 static void TestFtpFileSize()
2896 puts("*** Testing FTP SIZE command ***");
2898 if ( !ftp
.ChDir(directory
) )
2900 printf("ERROR: failed to cd to %s\n", directory
);
2903 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2905 if ( ftp
.FileExists(filename
) )
2907 int size
= ftp
.GetFileSize(filename
);
2909 printf("ERROR: couldn't get size of '%s'\n", filename
);
2911 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2915 printf("ERROR: '%s' doesn't exist\n", filename
);
2919 static void TestFtpMisc()
2921 puts("*** Testing miscellaneous wxFTP functions ***");
2923 if ( ftp
.SendCommand("STAT") != '2' )
2925 puts("ERROR: STAT failed");
2929 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2932 if ( ftp
.SendCommand("HELP SITE") != '2' )
2934 puts("ERROR: HELP SITE failed");
2938 printf("The list of site-specific commands:\n\n%s\n",
2939 ftp
.GetLastResult().c_str());
2943 static void TestFtpInteractive()
2945 puts("\n*** Interactive wxFTP test ***");
2951 printf("Enter FTP command: ");
2952 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2955 // kill the last '\n'
2956 buf
[strlen(buf
) - 1] = 0;
2958 // special handling of LIST and NLST as they require data connection
2959 wxString
start(buf
, 4);
2961 if ( start
== "LIST" || start
== "NLST" )
2964 if ( strlen(buf
) > 4 )
2967 wxArrayString files
;
2968 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2970 printf("ERROR: failed to get %s of files\n", start
.c_str());
2974 printf("--- %s of '%s' under '%s':\n",
2975 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2976 size_t count
= files
.GetCount();
2977 for ( size_t n
= 0; n
< count
; n
++ )
2979 printf("\t%s\n", files
[n
].c_str());
2981 puts("--- End of the file list");
2986 char ch
= ftp
.SendCommand(buf
);
2987 printf("Command %s", ch
? "succeeded" : "failed");
2990 printf(" (return code %c)", ch
);
2993 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2997 puts("\n*** done ***");
3000 static void TestFtpUpload()
3002 puts("*** Testing wxFTP uploading ***\n");
3005 static const char *file1
= "test1";
3006 static const char *file2
= "test2";
3007 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
3010 printf("--- Uploading to %s ---\n", file1
);
3011 out
->Write("First hello", 11);
3015 // send a command to check the remote file
3016 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
3018 printf("ERROR: STAT %s failed\n", file1
);
3022 printf("STAT %s returned:\n\n%s\n",
3023 file1
, ftp
.GetLastResult().c_str());
3026 out
= ftp
.GetOutputStream(file2
);
3029 printf("--- Uploading to %s ---\n", file1
);
3030 out
->Write("Second hello", 12);
3037 // ----------------------------------------------------------------------------
3039 // ----------------------------------------------------------------------------
3043 #include "wx/wfstream.h"
3044 #include "wx/mstream.h"
3046 static void TestFileStream()
3048 puts("*** Testing wxFileInputStream ***");
3050 static const wxChar
*filename
= _T("testdata.fs");
3052 wxFileOutputStream
fsOut(filename
);
3053 fsOut
.Write("foo", 3);
3056 wxFileInputStream
fsIn(filename
);
3057 printf("File stream size: %u\n", fsIn
.GetSize());
3058 while ( !fsIn
.Eof() )
3060 putchar(fsIn
.GetC());
3063 if ( !wxRemoveFile(filename
) )
3065 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3068 puts("\n*** wxFileInputStream test done ***");
3071 static void TestMemoryStream()
3073 puts("*** Testing wxMemoryInputStream ***");
3076 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3078 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3079 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3080 while ( !memInpStream
.Eof() )
3082 putchar(memInpStream
.GetC());
3085 puts("\n*** wxMemoryInputStream test done ***");
3088 #endif // TEST_STREAMS
3090 // ----------------------------------------------------------------------------
3092 // ----------------------------------------------------------------------------
3096 #include "wx/timer.h"
3097 #include "wx/utils.h"
3099 static void TestStopWatch()
3101 puts("*** Testing wxStopWatch ***\n");
3105 printf("Initially paused, after 2 seconds time is...");
3108 printf("\t%ldms\n", sw
.Time());
3110 printf("Resuming stopwatch and sleeping 3 seconds...");
3114 printf("\telapsed time: %ldms\n", sw
.Time());
3117 printf("Pausing agan and sleeping 2 more seconds...");
3120 printf("\telapsed time: %ldms\n", sw
.Time());
3123 printf("Finally resuming and sleeping 2 more seconds...");
3126 printf("\telapsed time: %ldms\n", sw
.Time());
3129 puts("\nChecking for 'backwards clock' bug...");
3130 for ( size_t n
= 0; n
< 70; n
++ )
3134 for ( size_t m
= 0; m
< 100000; m
++ )
3136 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3138 puts("\ntime is negative - ERROR!");
3149 #endif // TEST_TIMER
3151 // ----------------------------------------------------------------------------
3153 // ----------------------------------------------------------------------------
3157 #include "wx/vcard.h"
3159 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3162 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3166 wxString(_T('\t'), level
).c_str(),
3167 vcObj
->GetName().c_str());
3170 switch ( vcObj
->GetType() )
3172 case wxVCardObject::String
:
3173 case wxVCardObject::UString
:
3176 vcObj
->GetValue(&val
);
3177 value
<< _T('"') << val
<< _T('"');
3181 case wxVCardObject::Int
:
3184 vcObj
->GetValue(&i
);
3185 value
.Printf(_T("%u"), i
);
3189 case wxVCardObject::Long
:
3192 vcObj
->GetValue(&l
);
3193 value
.Printf(_T("%lu"), l
);
3197 case wxVCardObject::None
:
3200 case wxVCardObject::Object
:
3201 value
= _T("<node>");
3205 value
= _T("<unknown value type>");
3209 printf(" = %s", value
.c_str());
3212 DumpVObject(level
+ 1, *vcObj
);
3215 vcObj
= vcard
.GetNextProp(&cookie
);
3219 static void DumpVCardAddresses(const wxVCard
& vcard
)
3221 puts("\nShowing all addresses from vCard:\n");
3225 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3229 int flags
= addr
->GetFlags();
3230 if ( flags
& wxVCardAddress::Domestic
)
3232 flagsStr
<< _T("domestic ");
3234 if ( flags
& wxVCardAddress::Intl
)
3236 flagsStr
<< _T("international ");
3238 if ( flags
& wxVCardAddress::Postal
)
3240 flagsStr
<< _T("postal ");
3242 if ( flags
& wxVCardAddress::Parcel
)
3244 flagsStr
<< _T("parcel ");
3246 if ( flags
& wxVCardAddress::Home
)
3248 flagsStr
<< _T("home ");
3250 if ( flags
& wxVCardAddress::Work
)
3252 flagsStr
<< _T("work ");
3255 printf("Address %u:\n"
3257 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3260 addr
->GetPostOffice().c_str(),
3261 addr
->GetExtAddress().c_str(),
3262 addr
->GetStreet().c_str(),
3263 addr
->GetLocality().c_str(),
3264 addr
->GetRegion().c_str(),
3265 addr
->GetPostalCode().c_str(),
3266 addr
->GetCountry().c_str()
3270 addr
= vcard
.GetNextAddress(&cookie
);
3274 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3276 puts("\nShowing all phone numbers from vCard:\n");
3280 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3284 int flags
= phone
->GetFlags();
3285 if ( flags
& wxVCardPhoneNumber::Voice
)
3287 flagsStr
<< _T("voice ");
3289 if ( flags
& wxVCardPhoneNumber::Fax
)
3291 flagsStr
<< _T("fax ");
3293 if ( flags
& wxVCardPhoneNumber::Cellular
)
3295 flagsStr
<< _T("cellular ");
3297 if ( flags
& wxVCardPhoneNumber::Modem
)
3299 flagsStr
<< _T("modem ");
3301 if ( flags
& wxVCardPhoneNumber::Home
)
3303 flagsStr
<< _T("home ");
3305 if ( flags
& wxVCardPhoneNumber::Work
)
3307 flagsStr
<< _T("work ");
3310 printf("Phone number %u:\n"
3315 phone
->GetNumber().c_str()
3319 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3323 static void TestVCardRead()
3325 puts("*** Testing wxVCard reading ***\n");
3327 wxVCard
vcard(_T("vcard.vcf"));
3328 if ( !vcard
.IsOk() )
3330 puts("ERROR: couldn't load vCard.");
3334 // read individual vCard properties
3335 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3339 vcObj
->GetValue(&value
);
3344 value
= _T("<none>");
3347 printf("Full name retrieved directly: %s\n", value
.c_str());
3350 if ( !vcard
.GetFullName(&value
) )
3352 value
= _T("<none>");
3355 printf("Full name from wxVCard API: %s\n", value
.c_str());
3357 // now show how to deal with multiply occuring properties
3358 DumpVCardAddresses(vcard
);
3359 DumpVCardPhoneNumbers(vcard
);
3361 // and finally show all
3362 puts("\nNow dumping the entire vCard:\n"
3363 "-----------------------------\n");
3365 DumpVObject(0, vcard
);
3369 static void TestVCardWrite()
3371 puts("*** Testing wxVCard writing ***\n");
3374 if ( !vcard
.IsOk() )
3376 puts("ERROR: couldn't create vCard.");
3381 vcard
.SetName("Zeitlin", "Vadim");
3382 vcard
.SetFullName("Vadim Zeitlin");
3383 vcard
.SetOrganization("wxWindows", "R&D");
3385 // just dump the vCard back
3386 puts("Entire vCard follows:\n");
3387 puts(vcard
.Write());
3391 #endif // TEST_VCARD
3393 // ----------------------------------------------------------------------------
3395 // ----------------------------------------------------------------------------
3397 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3403 #include "wx/volume.h"
3405 static const wxChar
*volumeKinds
[] =
3411 _T("network volume"),
3415 static void TestFSVolume()
3417 wxPuts(_T("*** Testing wxFSVolume class ***"));
3419 wxArrayString volumes
= wxFSVolume::GetVolumes();
3420 size_t count
= volumes
.GetCount();
3424 wxPuts(_T("ERROR: no mounted volumes?"));
3428 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3430 for ( size_t n
= 0; n
< count
; n
++ )
3432 wxFSVolume
vol(volumes
[n
]);
3435 wxPuts(_T("ERROR: couldn't create volume"));
3439 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3441 vol
.GetDisplayName().c_str(),
3442 vol
.GetName().c_str(),
3443 volumeKinds
[vol
.GetKind()],
3444 vol
.IsWritable() ? _T("rw") : _T("ro"),
3445 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3450 #endif // TEST_VOLUME
3452 // ----------------------------------------------------------------------------
3453 // wide char (Unicode) support
3454 // ----------------------------------------------------------------------------
3458 #include "wx/strconv.h"
3459 #include "wx/fontenc.h"
3460 #include "wx/encconv.h"
3461 #include "wx/buffer.h"
3463 static const char textInUtf8
[] =
3465 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3466 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3467 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3468 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3469 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3470 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3471 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3474 static void TestUtf8()
3476 puts("*** Testing UTF8 support ***\n");
3480 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3482 puts("ERROR: UTF-8 decoding failed.");
3486 wxCSConv
conv(_T("koi8-r"));
3487 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3489 puts("ERROR: conversion to KOI8-R failed.");
3493 printf("The resulting string (in KOI8-R): %s\n", buf
);
3497 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3499 puts("ERROR: conversion to UTF-8 failed.");
3503 printf("The string in UTF-8: %s\n", buf
);
3509 static void TestEncodingConverter()
3511 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3513 // using wxEncodingConverter should give the same result as above
3516 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3518 puts("ERROR: UTF-8 decoding failed.");
3522 wxEncodingConverter ec
;
3523 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3524 ec
.Convert(wbuf
, buf
);
3525 printf("The same string obtained using wxEC: %s\n", buf
);
3531 #endif // TEST_WCHAR
3533 // ----------------------------------------------------------------------------
3535 // ----------------------------------------------------------------------------
3539 #include "wx/filesys.h"
3540 #include "wx/fs_zip.h"
3541 #include "wx/zipstrm.h"
3543 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3545 static void TestZipStreamRead()
3547 puts("*** Testing ZIP reading ***\n");
3549 static const wxChar
*filename
= _T("foo");
3550 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3551 printf("Archive size: %u\n", istr
.GetSize());
3553 printf("Dumping the file '%s':\n", filename
);
3554 while ( !istr
.Eof() )
3556 putchar(istr
.GetC());
3560 puts("\n----- done ------");
3563 static void DumpZipDirectory(wxFileSystem
& fs
,
3564 const wxString
& dir
,
3565 const wxString
& indent
)
3567 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3568 TESTFILE_ZIP
, dir
.c_str());
3569 wxString wildcard
= prefix
+ _T("/*");
3571 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3572 while ( !dirname
.empty() )
3574 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3576 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3581 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3583 DumpZipDirectory(fs
, dirname
,
3584 indent
+ wxString(_T(' '), 4));
3586 dirname
= fs
.FindNext();
3589 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3590 while ( !filename
.empty() )
3592 if ( !filename
.StartsWith(prefix
, &filename
) )
3594 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3599 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3601 filename
= fs
.FindNext();
3605 static void TestZipFileSystem()
3607 puts("*** Testing ZIP file system ***\n");
3609 wxFileSystem::AddHandler(new wxZipFSHandler
);
3611 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3613 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3618 // ----------------------------------------------------------------------------
3620 // ----------------------------------------------------------------------------
3624 #include "wx/zstream.h"
3625 #include "wx/wfstream.h"
3627 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3628 static const char *TEST_DATA
= "hello and hello and hello and hello and hello";
3630 static void TestZlibStreamWrite()
3632 puts("*** Testing Zlib stream reading ***\n");
3634 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3635 wxZlibOutputStream
ostr(fileOutStream
);
3636 printf("Compressing the test string... ");
3637 ostr
.Write(TEST_DATA
, strlen(TEST_DATA
) + 1);
3640 puts("(ERROR: failed)");
3647 puts("\n----- done ------");
3650 static void TestZlibStreamRead()
3652 puts("*** Testing Zlib stream reading ***\n");
3654 wxFileInputStream
fileInStream(FILENAME_GZ
);
3655 wxZlibInputStream
istr(fileInStream
);
3656 printf("Archive size: %u\n", istr
.GetSize());
3658 puts("Dumping the file:");
3659 while ( !istr
.Eof() )
3661 putchar(istr
.GetC());
3665 puts("\n----- done ------");
3670 // ----------------------------------------------------------------------------
3672 // ----------------------------------------------------------------------------
3674 #ifdef TEST_DATETIME
3678 #include "wx/date.h"
3679 #include "wx/datetime.h"
3684 wxDateTime::wxDateTime_t day
;
3685 wxDateTime::Month month
;
3687 wxDateTime::wxDateTime_t hour
, min
, sec
;
3689 wxDateTime::WeekDay wday
;
3690 time_t gmticks
, ticks
;
3692 void Init(const wxDateTime::Tm
& tm
)
3701 gmticks
= ticks
= -1;
3704 wxDateTime
DT() const
3705 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3707 bool SameDay(const wxDateTime::Tm
& tm
) const
3709 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3712 wxString
Format() const
3715 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3717 wxDateTime::GetMonthName(month
).c_str(),
3719 abs(wxDateTime::ConvertYearToBC(year
)),
3720 year
> 0 ? "AD" : "BC");
3724 wxString
FormatDate() const
3727 s
.Printf("%02d-%s-%4d%s",
3729 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3730 abs(wxDateTime::ConvertYearToBC(year
)),
3731 year
> 0 ? "AD" : "BC");
3736 static const Date testDates
[] =
3738 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3739 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3740 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3741 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3742 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3743 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3744 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3745 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3746 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3747 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3748 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3749 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3750 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3751 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3752 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3755 // this test miscellaneous static wxDateTime functions
3756 static void TestTimeStatic()
3758 puts("\n*** wxDateTime static methods test ***");
3760 // some info about the current date
3761 int year
= wxDateTime::GetCurrentYear();
3762 printf("Current year %d is %sa leap one and has %d days.\n",
3764 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3765 wxDateTime::GetNumberOfDays(year
));
3767 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3768 printf("Current month is '%s' ('%s') and it has %d days\n",
3769 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3770 wxDateTime::GetMonthName(month
).c_str(),
3771 wxDateTime::GetNumberOfDays(month
));
3774 static const size_t nYears
= 5;
3775 static const size_t years
[2][nYears
] =
3777 // first line: the years to test
3778 { 1990, 1976, 2000, 2030, 1984, },
3780 // second line: TRUE if leap, FALSE otherwise
3781 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3784 for ( size_t n
= 0; n
< nYears
; n
++ )
3786 int year
= years
[0][n
];
3787 bool should
= years
[1][n
] != 0,
3788 is
= wxDateTime::IsLeapYear(year
);
3790 printf("Year %d is %sa leap year (%s)\n",
3793 should
== is
? "ok" : "ERROR");
3795 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3799 // test constructing wxDateTime objects
3800 static void TestTimeSet()
3802 puts("\n*** wxDateTime construction test ***");
3804 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3806 const Date
& d1
= testDates
[n
];
3807 wxDateTime dt
= d1
.DT();
3810 d2
.Init(dt
.GetTm());
3812 wxString s1
= d1
.Format(),
3815 printf("Date: %s == %s (%s)\n",
3816 s1
.c_str(), s2
.c_str(),
3817 s1
== s2
? "ok" : "ERROR");
3821 // test time zones stuff
3822 static void TestTimeZones()
3824 puts("\n*** wxDateTime timezone test ***");
3826 wxDateTime now
= wxDateTime::Now();
3828 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3829 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3830 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3831 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3832 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3833 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3835 wxDateTime::Tm tm
= now
.GetTm();
3836 if ( wxDateTime(tm
) != now
)
3838 printf("ERROR: got %s instead of %s\n",
3839 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3843 // test some minimal support for the dates outside the standard range
3844 static void TestTimeRange()
3846 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3848 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3850 printf("Unix epoch:\t%s\n",
3851 wxDateTime(2440587.5).Format(fmt
).c_str());
3852 printf("Feb 29, 0: \t%s\n",
3853 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3854 printf("JDN 0: \t%s\n",
3855 wxDateTime(0.0).Format(fmt
).c_str());
3856 printf("Jan 1, 1AD:\t%s\n",
3857 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3858 printf("May 29, 2099:\t%s\n",
3859 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3862 static void TestTimeTicks()
3864 puts("\n*** wxDateTime ticks test ***");
3866 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3868 const Date
& d
= testDates
[n
];
3869 if ( d
.ticks
== -1 )
3872 wxDateTime dt
= d
.DT();
3873 long ticks
= (dt
.GetValue() / 1000).ToLong();
3874 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3875 if ( ticks
== d
.ticks
)
3881 printf(" (ERROR: should be %ld, delta = %ld)\n",
3882 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
3885 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3886 ticks
= (dt
.GetValue() / 1000).ToLong();
3887 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3888 if ( ticks
== d
.gmticks
)
3894 printf(" (ERROR: should be %ld, delta = %ld)\n",
3895 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
3902 // test conversions to JDN &c
3903 static void TestTimeJDN()
3905 puts("\n*** wxDateTime to JDN test ***");
3907 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3909 const Date
& d
= testDates
[n
];
3910 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3911 double jdn
= dt
.GetJulianDayNumber();
3913 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3920 printf(" (ERROR: should be %f, delta = %f)\n",
3921 d
.jdn
, jdn
- d
.jdn
);
3926 // test week days computation
3927 static void TestTimeWDays()
3929 puts("\n*** wxDateTime weekday test ***");
3931 // test GetWeekDay()
3933 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3935 const Date
& d
= testDates
[n
];
3936 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3938 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3941 wxDateTime::GetWeekDayName(wday
).c_str());
3942 if ( wday
== d
.wday
)
3948 printf(" (ERROR: should be %s)\n",
3949 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3955 // test SetToWeekDay()
3956 struct WeekDateTestData
3958 Date date
; // the real date (precomputed)
3959 int nWeek
; // its week index in the month
3960 wxDateTime::WeekDay wday
; // the weekday
3961 wxDateTime::Month month
; // the month
3962 int year
; // and the year
3964 wxString
Format() const
3967 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3969 case 1: which
= "first"; break;
3970 case 2: which
= "second"; break;
3971 case 3: which
= "third"; break;
3972 case 4: which
= "fourth"; break;
3973 case 5: which
= "fifth"; break;
3975 case -1: which
= "last"; break;
3980 which
+= " from end";
3983 s
.Printf("The %s %s of %s in %d",
3985 wxDateTime::GetWeekDayName(wday
).c_str(),
3986 wxDateTime::GetMonthName(month
).c_str(),
3993 // the array data was generated by the following python program
3995 from DateTime import *
3996 from whrandom import *
3997 from string import *
3999 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4000 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4002 week = DateTimeDelta(7)
4005 year = randint(1900, 2100)
4006 month = randint(1, 12)
4007 day = randint(1, 28)
4008 dt = DateTime(year, month, day)
4009 wday = dt.day_of_week
4011 countFromEnd = choice([-1, 1])
4014 while dt.month is month:
4015 dt = dt - countFromEnd * week
4016 weekNum = weekNum + countFromEnd
4018 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
4020 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
4021 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
4024 static const WeekDateTestData weekDatesTestData
[] =
4026 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
4027 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
4028 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
4029 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
4030 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
4031 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
4032 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
4033 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
4034 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
4035 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
4036 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
4037 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
4038 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
4039 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
4040 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
4041 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
4042 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
4043 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
4044 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
4045 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4048 static const char *fmt
= "%d-%b-%Y";
4051 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4053 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4055 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4057 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4059 const Date
& d
= wd
.date
;
4060 if ( d
.SameDay(dt
.GetTm()) )
4066 dt
.Set(d
.day
, d
.month
, d
.year
);
4068 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4073 // test the computation of (ISO) week numbers
4074 static void TestTimeWNumber()
4076 puts("\n*** wxDateTime week number test ***");
4078 struct WeekNumberTestData
4080 Date date
; // the date
4081 wxDateTime::wxDateTime_t week
; // the week number in the year
4082 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4083 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4084 wxDateTime::wxDateTime_t dnum
; // day number in the year
4087 // data generated with the following python script:
4089 from DateTime import *
4090 from whrandom import *
4091 from string import *
4093 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4094 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4096 def GetMonthWeek(dt):
4097 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4098 if weekNumMonth < 0:
4099 weekNumMonth = weekNumMonth + 53
4102 def GetLastSundayBefore(dt):
4103 if dt.iso_week[2] == 7:
4106 return dt - DateTimeDelta(dt.iso_week[2])
4109 year = randint(1900, 2100)
4110 month = randint(1, 12)
4111 day = randint(1, 28)
4112 dt = DateTime(year, month, day)
4113 dayNum = dt.day_of_year
4114 weekNum = dt.iso_week[1]
4115 weekNumMonth = GetMonthWeek(dt)
4118 dtSunday = GetLastSundayBefore(dt)
4120 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4121 weekNumMonth2 = weekNumMonth2 + 1
4122 dtSunday = dtSunday - DateTimeDelta(7)
4124 data = { 'day': rjust(`day`, 2), \
4125 'month': monthNames[month - 1], \
4127 'weekNum': rjust(`weekNum`, 2), \
4128 'weekNumMonth': weekNumMonth, \
4129 'weekNumMonth2': weekNumMonth2, \
4130 'dayNum': rjust(`dayNum`, 3) }
4132 print " { { %(day)s, "\
4133 "wxDateTime::%(month)s, "\
4136 "%(weekNumMonth)s, "\
4137 "%(weekNumMonth2)s, "\
4138 "%(dayNum)s }," % data
4141 static const WeekNumberTestData weekNumberTestDates
[] =
4143 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4144 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4145 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4146 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4147 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4148 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4149 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4150 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4151 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4152 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4153 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4154 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4155 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4156 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4157 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4158 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4159 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4160 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4161 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4162 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4165 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4167 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4168 const Date
& d
= wn
.date
;
4170 wxDateTime dt
= d
.DT();
4172 wxDateTime::wxDateTime_t
4173 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4174 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4175 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4176 dnum
= dt
.GetDayOfYear();
4178 printf("%s: the day number is %d",
4179 d
.FormatDate().c_str(), dnum
);
4180 if ( dnum
== wn
.dnum
)
4186 printf(" (ERROR: should be %d)", wn
.dnum
);
4189 printf(", week in month is %d", wmon
);
4190 if ( wmon
== wn
.wmon
)
4196 printf(" (ERROR: should be %d)", wn
.wmon
);
4199 printf(" or %d", wmon2
);
4200 if ( wmon2
== wn
.wmon2
)
4206 printf(" (ERROR: should be %d)", wn
.wmon2
);
4209 printf(", week in year is %d", week
);
4210 if ( week
== wn
.week
)
4216 printf(" (ERROR: should be %d)\n", wn
.week
);
4221 // test DST calculations
4222 static void TestTimeDST()
4224 puts("\n*** wxDateTime DST test ***");
4226 printf("DST is%s in effect now.\n\n",
4227 wxDateTime::Now().IsDST() ? "" : " not");
4229 // taken from http://www.energy.ca.gov/daylightsaving.html
4230 static const Date datesDST
[2][2004 - 1900 + 1] =
4233 { 1, wxDateTime::Apr
, 1990 },
4234 { 7, wxDateTime::Apr
, 1991 },
4235 { 5, wxDateTime::Apr
, 1992 },
4236 { 4, wxDateTime::Apr
, 1993 },
4237 { 3, wxDateTime::Apr
, 1994 },
4238 { 2, wxDateTime::Apr
, 1995 },
4239 { 7, wxDateTime::Apr
, 1996 },
4240 { 6, wxDateTime::Apr
, 1997 },
4241 { 5, wxDateTime::Apr
, 1998 },
4242 { 4, wxDateTime::Apr
, 1999 },
4243 { 2, wxDateTime::Apr
, 2000 },
4244 { 1, wxDateTime::Apr
, 2001 },
4245 { 7, wxDateTime::Apr
, 2002 },
4246 { 6, wxDateTime::Apr
, 2003 },
4247 { 4, wxDateTime::Apr
, 2004 },
4250 { 28, wxDateTime::Oct
, 1990 },
4251 { 27, wxDateTime::Oct
, 1991 },
4252 { 25, wxDateTime::Oct
, 1992 },
4253 { 31, wxDateTime::Oct
, 1993 },
4254 { 30, wxDateTime::Oct
, 1994 },
4255 { 29, wxDateTime::Oct
, 1995 },
4256 { 27, wxDateTime::Oct
, 1996 },
4257 { 26, wxDateTime::Oct
, 1997 },
4258 { 25, wxDateTime::Oct
, 1998 },
4259 { 31, wxDateTime::Oct
, 1999 },
4260 { 29, wxDateTime::Oct
, 2000 },
4261 { 28, wxDateTime::Oct
, 2001 },
4262 { 27, wxDateTime::Oct
, 2002 },
4263 { 26, wxDateTime::Oct
, 2003 },
4264 { 31, wxDateTime::Oct
, 2004 },
4269 for ( year
= 1990; year
< 2005; year
++ )
4271 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4272 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4274 printf("DST period in the US for year %d: from %s to %s",
4275 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4277 size_t n
= year
- 1990;
4278 const Date
& dBegin
= datesDST
[0][n
];
4279 const Date
& dEnd
= datesDST
[1][n
];
4281 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4287 printf(" (ERROR: should be %s %d to %s %d)\n",
4288 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4289 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4295 for ( year
= 1990; year
< 2005; year
++ )
4297 printf("DST period in Europe for year %d: from %s to %s\n",
4299 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4300 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4304 // test wxDateTime -> text conversion
4305 static void TestTimeFormat()
4307 puts("\n*** wxDateTime formatting test ***");
4309 // some information may be lost during conversion, so store what kind
4310 // of info should we recover after a round trip
4313 CompareNone
, // don't try comparing
4314 CompareBoth
, // dates and times should be identical
4315 CompareDate
, // dates only
4316 CompareTime
// time only
4321 CompareKind compareKind
;
4323 } formatTestFormats
[] =
4325 { CompareBoth
, "---> %c" },
4326 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4327 { CompareBoth
, "Date is %x, time is %X" },
4328 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4329 { CompareNone
, "The day of year: %j, the week of year: %W" },
4330 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4333 static const Date formatTestDates
[] =
4335 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4336 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4338 // this test can't work for other centuries because it uses two digit
4339 // years in formats, so don't even try it
4340 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4341 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4342 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4346 // an extra test (as it doesn't depend on date, don't do it in the loop)
4347 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4349 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4353 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4354 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4356 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4357 printf("%s", s
.c_str());
4359 // what can we recover?
4360 int kind
= formatTestFormats
[n
].compareKind
;
4364 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4367 // converion failed - should it have?
4368 if ( kind
== CompareNone
)
4371 puts(" (ERROR: conversion back failed)");
4375 // should have parsed the entire string
4376 puts(" (ERROR: conversion back stopped too soon)");
4380 bool equal
= FALSE
; // suppress compilaer warning
4388 equal
= dt
.IsSameDate(dt2
);
4392 equal
= dt
.IsSameTime(dt2
);
4398 printf(" (ERROR: got back '%s' instead of '%s')\n",
4399 dt2
.Format().c_str(), dt
.Format().c_str());
4410 // test text -> wxDateTime conversion
4411 static void TestTimeParse()
4413 puts("\n*** wxDateTime parse test ***");
4415 struct ParseTestData
4422 static const ParseTestData parseTestDates
[] =
4424 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4425 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4428 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4430 const char *format
= parseTestDates
[n
].format
;
4432 printf("%s => ", format
);
4435 if ( dt
.ParseRfc822Date(format
) )
4437 printf("%s ", dt
.Format().c_str());
4439 if ( parseTestDates
[n
].good
)
4441 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4448 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4453 puts("(ERROR: bad format)");
4458 printf("bad format (%s)\n",
4459 parseTestDates
[n
].good
? "ERROR" : "ok");
4464 static void TestDateTimeInteractive()
4466 puts("\n*** interactive wxDateTime tests ***");
4472 printf("Enter a date: ");
4473 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4476 // kill the last '\n'
4477 buf
[strlen(buf
) - 1] = 0;
4480 const char *p
= dt
.ParseDate(buf
);
4483 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4489 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4492 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4493 dt
.Format("%b %d, %Y").c_str(),
4495 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4496 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4497 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4500 puts("\n*** done ***");
4503 static void TestTimeMS()
4505 puts("*** testing millisecond-resolution support in wxDateTime ***");
4507 wxDateTime dt1
= wxDateTime::Now(),
4508 dt2
= wxDateTime::UNow();
4510 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4511 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4512 printf("Dummy loop: ");
4513 for ( int i
= 0; i
< 6000; i
++ )
4515 //for ( int j = 0; j < 10; j++ )
4518 s
.Printf("%g", sqrt(i
));
4527 dt2
= wxDateTime::UNow();
4528 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4530 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4532 puts("\n*** done ***");
4535 static void TestTimeArithmetics()
4537 puts("\n*** testing arithmetic operations on wxDateTime ***");
4539 static const struct ArithmData
4541 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4542 : span(sp
), name(nam
) { }
4546 } testArithmData
[] =
4548 ArithmData(wxDateSpan::Day(), "day"),
4549 ArithmData(wxDateSpan::Week(), "week"),
4550 ArithmData(wxDateSpan::Month(), "month"),
4551 ArithmData(wxDateSpan::Year(), "year"),
4552 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4555 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4557 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4559 wxDateSpan span
= testArithmData
[n
].span
;
4563 const char *name
= testArithmData
[n
].name
;
4564 printf("%s + %s = %s, %s - %s = %s\n",
4565 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4566 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4568 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4569 if ( dt1
- span
== dt
)
4575 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4578 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4579 if ( dt2
+ span
== dt
)
4585 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4588 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4589 if ( dt2
+ 2*span
== dt1
)
4595 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4602 static void TestTimeHolidays()
4604 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4606 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4607 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4608 dtEnd
= dtStart
.GetLastMonthDay();
4610 wxDateTimeArray hol
;
4611 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4613 const wxChar
*format
= "%d-%b-%Y (%a)";
4615 printf("All holidays between %s and %s:\n",
4616 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4618 size_t count
= hol
.GetCount();
4619 for ( size_t n
= 0; n
< count
; n
++ )
4621 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4627 static void TestTimeZoneBug()
4629 puts("\n*** testing for DST/timezone bug ***\n");
4631 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4632 for ( int i
= 0; i
< 31; i
++ )
4634 printf("Date %s: week day %s.\n",
4635 date
.Format(_T("%d-%m-%Y")).c_str(),
4636 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4638 date
+= wxDateSpan::Day();
4644 static void TestTimeSpanFormat()
4646 puts("\n*** wxTimeSpan tests ***");
4648 static const char *formats
[] =
4650 _T("(default) %H:%M:%S"),
4651 _T("%E weeks and %D days"),
4652 _T("%l milliseconds"),
4653 _T("(with ms) %H:%M:%S:%l"),
4654 _T("100%% of minutes is %M"), // test "%%"
4655 _T("%D days and %H hours"),
4656 _T("or also %S seconds"),
4659 wxTimeSpan
ts1(1, 2, 3, 4),
4661 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4663 printf("ts1 = %s\tts2 = %s\n",
4664 ts1
.Format(formats
[n
]).c_str(),
4665 ts2
.Format(formats
[n
]).c_str());
4673 // test compatibility with the old wxDate/wxTime classes
4674 static void TestTimeCompatibility()
4676 puts("\n*** wxDateTime compatibility test ***");
4678 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4679 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4681 double jdnNow
= wxDateTime::Now().GetJDN();
4682 long jdnMidnight
= (long)(jdnNow
- 0.5);
4683 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4685 jdnMidnight
= wxDate().Set().GetJulianDate();
4686 printf("wxDateTime for today: %s\n",
4687 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4689 int flags
= wxEUROPEAN
;//wxFULL;
4692 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4693 for ( int n
= 0; n
< 7; n
++ )
4695 printf("Previous %s is %s\n",
4696 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4697 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4703 #endif // TEST_DATETIME
4705 // ----------------------------------------------------------------------------
4707 // ----------------------------------------------------------------------------
4711 #include "wx/thread.h"
4713 static size_t gs_counter
= (size_t)-1;
4714 static wxCriticalSection gs_critsect
;
4715 static wxSemaphore gs_cond
;
4717 class MyJoinableThread
: public wxThread
4720 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4721 { m_n
= n
; Create(); }
4723 // thread execution starts here
4724 virtual ExitCode
Entry();
4730 wxThread::ExitCode
MyJoinableThread::Entry()
4732 unsigned long res
= 1;
4733 for ( size_t n
= 1; n
< m_n
; n
++ )
4737 // it's a loooong calculation :-)
4741 return (ExitCode
)res
;
4744 class MyDetachedThread
: public wxThread
4747 MyDetachedThread(size_t n
, char ch
)
4751 m_cancelled
= FALSE
;
4756 // thread execution starts here
4757 virtual ExitCode
Entry();
4760 virtual void OnExit();
4763 size_t m_n
; // number of characters to write
4764 char m_ch
; // character to write
4766 bool m_cancelled
; // FALSE if we exit normally
4769 wxThread::ExitCode
MyDetachedThread::Entry()
4772 wxCriticalSectionLocker
lock(gs_critsect
);
4773 if ( gs_counter
== (size_t)-1 )
4779 for ( size_t n
= 0; n
< m_n
; n
++ )
4781 if ( TestDestroy() )
4791 wxThread::Sleep(100);
4797 void MyDetachedThread::OnExit()
4799 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4801 wxCriticalSectionLocker
lock(gs_critsect
);
4802 if ( !--gs_counter
&& !m_cancelled
)
4806 static void TestDetachedThreads()
4808 puts("\n*** Testing detached threads ***");
4810 static const size_t nThreads
= 3;
4811 MyDetachedThread
*threads
[nThreads
];
4813 for ( n
= 0; n
< nThreads
; n
++ )
4815 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4818 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4819 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4821 for ( n
= 0; n
< nThreads
; n
++ )
4826 // wait until all threads terminate
4832 static void TestJoinableThreads()
4834 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4836 // calc 10! in the background
4837 MyJoinableThread
thread(10);
4840 printf("\nThread terminated with exit code %lu.\n",
4841 (unsigned long)thread
.Wait());
4844 static void TestThreadSuspend()
4846 puts("\n*** Testing thread suspend/resume functions ***");
4848 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4852 // this is for this demo only, in a real life program we'd use another
4853 // condition variable which would be signaled from wxThread::Entry() to
4854 // tell us that the thread really started running - but here just wait a
4855 // bit and hope that it will be enough (the problem is, of course, that
4856 // the thread might still not run when we call Pause() which will result
4858 wxThread::Sleep(300);
4860 for ( size_t n
= 0; n
< 3; n
++ )
4864 puts("\nThread suspended");
4867 // don't sleep but resume immediately the first time
4868 wxThread::Sleep(300);
4870 puts("Going to resume the thread");
4875 puts("Waiting until it terminates now");
4877 // wait until the thread terminates
4883 static void TestThreadDelete()
4885 // As above, using Sleep() is only for testing here - we must use some
4886 // synchronisation object instead to ensure that the thread is still
4887 // running when we delete it - deleting a detached thread which already
4888 // terminated will lead to a crash!
4890 puts("\n*** Testing thread delete function ***");
4892 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4896 puts("\nDeleted a thread which didn't start to run yet.");
4898 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4902 wxThread::Sleep(300);
4906 puts("\nDeleted a running thread.");
4908 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4912 wxThread::Sleep(300);
4918 puts("\nDeleted a sleeping thread.");
4920 MyJoinableThread
thread3(20);
4925 puts("\nDeleted a joinable thread.");
4927 MyJoinableThread
thread4(2);
4930 wxThread::Sleep(300);
4934 puts("\nDeleted a joinable thread which already terminated.");
4939 class MyWaitingThread
: public wxThread
4942 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4945 m_condition
= condition
;
4950 virtual ExitCode
Entry()
4952 printf("Thread %lu has started running.\n", GetId());
4957 printf("Thread %lu starts to wait...\n", GetId());
4961 m_condition
->Wait();
4964 printf("Thread %lu finished to wait, exiting.\n", GetId());
4972 wxCondition
*m_condition
;
4975 static void TestThreadConditions()
4978 wxCondition
condition(mutex
);
4980 // otherwise its difficult to understand which log messages pertain to
4982 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4983 // condition.GetId(), gs_cond.GetId());
4985 // create and launch threads
4986 MyWaitingThread
*threads
[10];
4989 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4991 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4994 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4999 // wait until all threads run
5000 puts("Main thread is waiting for the other threads to start");
5003 size_t nRunning
= 0;
5004 while ( nRunning
< WXSIZEOF(threads
) )
5010 printf("Main thread: %u already running\n", nRunning
);
5014 puts("Main thread: all threads started up.");
5017 wxThread::Sleep(500);
5020 // now wake one of them up
5021 printf("Main thread: about to signal the condition.\n");
5026 wxThread::Sleep(200);
5028 // wake all the (remaining) threads up, so that they can exit
5029 printf("Main thread: about to broadcast the condition.\n");
5031 condition
.Broadcast();
5033 // give them time to terminate (dirty!)
5034 wxThread::Sleep(500);
5037 #include "wx/utils.h"
5039 class MyExecThread
: public wxThread
5042 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5048 virtual ExitCode
Entry()
5050 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5057 static void TestThreadExec()
5059 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5061 MyExecThread
thread(_T("true"));
5064 wxPrintf(_T("Main program exit code: %ld.\n"),
5065 wxExecute(_T("false"), wxEXEC_SYNC
));
5067 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5071 #include "wx/datetime.h"
5073 class MySemaphoreThread
: public wxThread
5076 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5077 : wxThread(wxTHREAD_JOINABLE
),
5084 virtual ExitCode
Entry()
5086 wxPrintf(_T("%s: Thread %d starting to wait for semaphore...\n"),
5087 wxDateTime::Now().FormatTime().c_str(), m_i
);
5091 wxPrintf(_T("%s: Thread %d acquired the semaphore.\n"),
5092 wxDateTime::Now().FormatTime().c_str(), m_i
);
5096 wxPrintf(_T("%s: Thread %d releasing the semaphore.\n"),
5097 wxDateTime::Now().FormatTime().c_str(), m_i
);
5109 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5111 static void TestSemaphore()
5113 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5115 static const int SEM_LIMIT
= 3;
5117 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5118 ArrayThreads threads
;
5120 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5122 threads
.Add(new MySemaphoreThread(i
, &sem
));
5123 threads
.Last()->Run();
5126 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5133 #endif // TEST_THREADS
5135 // ----------------------------------------------------------------------------
5137 // ----------------------------------------------------------------------------
5141 #include "wx/dynarray.h"
5143 typedef unsigned short ushort
;
5145 #define DefineCompare(name, T) \
5147 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5149 return first - second; \
5152 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5154 return *first - *second; \
5157 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5159 return *second - *first; \
5162 DefineCompare(UShort, ushort);
5163 DefineCompare(Int
, int);
5165 // test compilation of all macros
5166 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5167 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5168 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5169 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5171 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5172 #include "wx/arrimpl.cpp"
5173 WX_DEFINE_OBJARRAY(ArrayBars
);
5175 static void PrintArray(const char* name
, const wxArrayString
& array
)
5177 printf("Dump of the array '%s'\n", name
);
5179 size_t nCount
= array
.GetCount();
5180 for ( size_t n
= 0; n
< nCount
; n
++ )
5182 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5186 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5187 const wxString
& second
)
5189 return first
.length() - second
.length();
5192 #define TestArrayOf(name) \
5194 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5196 printf("Dump of the array '%s'\n", name); \
5198 size_t nCount = array.GetCount(); \
5199 for ( size_t n = 0; n < nCount; n++ ) \
5201 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5205 static void PrintArray(const char* name, const wxArray##name & array) \
5207 printf("Dump of the array '%s'\n", name); \
5209 size_t nCount = array.GetCount(); \
5210 for ( size_t n = 0; n < nCount; n++ ) \
5212 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5216 static void TestArrayOf ## name ## s() \
5218 printf("*** Testing wxArray%s ***\n", #name); \
5226 puts("Initially:"); \
5227 PrintArray("a", a); \
5229 puts("After sort:"); \
5230 a.Sort(name ## Compare); \
5231 PrintArray("a", a); \
5233 puts("After reverse sort:"); \
5234 a.Sort(name ## RevCompare); \
5235 PrintArray("a", a); \
5237 wxSortedArray##name b; \
5243 puts("Sorted array initially:"); \
5244 PrintArray("b", b); \
5247 TestArrayOf(UShort
);
5250 static void TestArrayOfObjects()
5252 puts("*** Testing wxObjArray ***\n");
5256 Bar
bar("second bar (two copies!)");
5258 printf("Initially: %u objects in the array, %u objects total.\n",
5259 bars
.GetCount(), Bar::GetNumber());
5261 bars
.Add(new Bar("first bar"));
5264 printf("Now: %u objects in the array, %u objects total.\n",
5265 bars
.GetCount(), Bar::GetNumber());
5267 bars
.RemoveAt(1, bars
.GetCount() - 1);
5269 printf("After removing all but first element: %u objects in the "
5270 "array, %u objects total.\n",
5271 bars
.GetCount(), Bar::GetNumber());
5275 printf("After Empty(): %u objects in the array, %u objects total.\n",
5276 bars
.GetCount(), Bar::GetNumber());
5279 printf("Finally: no more objects in the array, %u objects total.\n",
5283 #endif // TEST_ARRAYS
5285 // ----------------------------------------------------------------------------
5287 // ----------------------------------------------------------------------------
5291 #include "wx/timer.h"
5292 #include "wx/tokenzr.h"
5294 static void TestStringConstruction()
5296 puts("*** Testing wxString constructores ***");
5298 #define TEST_CTOR(args, res) \
5301 printf("wxString%s = %s ", #args, s.c_str()); \
5308 printf("(ERROR: should be %s)\n", res); \
5312 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5313 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5314 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5315 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5317 static const wxChar
*s
= _T("?really!");
5318 const wxChar
*start
= wxStrchr(s
, _T('r'));
5319 const wxChar
*end
= wxStrchr(s
, _T('!'));
5320 TEST_CTOR((start
, end
), _T("really"));
5325 static void TestString()
5335 for (int i
= 0; i
< 1000000; ++i
)
5339 c
= "! How'ya doin'?";
5342 c
= "Hello world! What's up?";
5347 printf ("TestString elapsed time: %ld\n", sw
.Time());
5350 static void TestPChar()
5358 for (int i
= 0; i
< 1000000; ++i
)
5360 strcpy (a
, "Hello");
5361 strcpy (b
, " world");
5362 strcpy (c
, "! How'ya doin'?");
5365 strcpy (c
, "Hello world! What's up?");
5366 if (strcmp (c
, a
) == 0)
5370 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5373 static void TestStringSub()
5375 wxString
s("Hello, world!");
5377 puts("*** Testing wxString substring extraction ***");
5379 printf("String = '%s'\n", s
.c_str());
5380 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5381 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5382 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5383 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5384 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5385 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5387 static const wxChar
*prefixes
[] =
5391 _T("Hello, world!"),
5392 _T("Hello, world!!!"),
5398 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5400 wxString prefix
= prefixes
[n
], rest
;
5401 bool rc
= s
.StartsWith(prefix
, &rest
);
5402 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5405 printf(" (the rest is '%s')\n", rest
.c_str());
5416 static void TestStringFormat()
5418 puts("*** Testing wxString formatting ***");
5421 s
.Printf("%03d", 18);
5423 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5424 printf("Number 18: %s\n", s
.c_str());
5429 // returns "not found" for npos, value for all others
5430 static wxString
PosToString(size_t res
)
5432 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5433 : wxString::Format(_T("%u"), res
);
5437 static void TestStringFind()
5439 puts("*** Testing wxString find() functions ***");
5441 static const wxChar
*strToFind
= _T("ell");
5442 static const struct StringFindTest
5446 result
; // of searching "ell" in str
5449 { _T("Well, hello world"), 0, 1 },
5450 { _T("Well, hello world"), 6, 7 },
5451 { _T("Well, hello world"), 9, wxString::npos
},
5454 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5456 const StringFindTest
& ft
= findTestData
[n
];
5457 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5459 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5460 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5462 size_t resTrue
= ft
.result
;
5463 if ( res
== resTrue
)
5469 printf(_T("(ERROR: should be %s)\n"),
5470 PosToString(resTrue
).c_str());
5477 static void TestStringTokenizer()
5479 puts("*** Testing wxStringTokenizer ***");
5481 static const wxChar
*modeNames
[] =
5485 _T("return all empty"),
5490 static const struct StringTokenizerTest
5492 const wxChar
*str
; // string to tokenize
5493 const wxChar
*delims
; // delimiters to use
5494 size_t count
; // count of token
5495 wxStringTokenizerMode mode
; // how should we tokenize it
5496 } tokenizerTestData
[] =
5498 { _T(""), _T(" "), 0 },
5499 { _T("Hello, world"), _T(" "), 2 },
5500 { _T("Hello, world "), _T(" "), 2 },
5501 { _T("Hello, world"), _T(","), 2 },
5502 { _T("Hello, world!"), _T(",!"), 2 },
5503 { _T("Hello,, world!"), _T(",!"), 3 },
5504 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5505 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5506 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5507 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5508 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5509 { _T("01/02/99"), _T("/-"), 3 },
5510 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5513 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5515 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5516 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5518 size_t count
= tkz
.CountTokens();
5519 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5520 MakePrintable(tt
.str
).c_str(),
5522 MakePrintable(tt
.delims
).c_str(),
5523 modeNames
[tkz
.GetMode()]);
5524 if ( count
== tt
.count
)
5530 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5535 // if we emulate strtok(), check that we do it correctly
5536 wxChar
*buf
, *s
= NULL
, *last
;
5538 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5540 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5541 wxStrcpy(buf
, tt
.str
);
5543 s
= wxStrtok(buf
, tt
.delims
, &last
);
5550 // now show the tokens themselves
5552 while ( tkz
.HasMoreTokens() )
5554 wxString token
= tkz
.GetNextToken();
5556 printf(_T("\ttoken %u: '%s'"),
5558 MakePrintable(token
).c_str());
5568 printf(" (ERROR: should be %s)\n", s
);
5571 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5575 // nothing to compare with
5580 if ( count2
!= count
)
5582 puts(_T("\tERROR: token count mismatch"));
5591 static void TestStringReplace()
5593 puts("*** Testing wxString::replace ***");
5595 static const struct StringReplaceTestData
5597 const wxChar
*original
; // original test string
5598 size_t start
, len
; // the part to replace
5599 const wxChar
*replacement
; // the replacement string
5600 const wxChar
*result
; // and the expected result
5601 } stringReplaceTestData
[] =
5603 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5604 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5605 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5606 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5607 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5610 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5612 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5614 wxString original
= data
.original
;
5615 original
.replace(data
.start
, data
.len
, data
.replacement
);
5617 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5618 data
.original
, data
.start
, data
.len
, data
.replacement
,
5621 if ( original
== data
.result
)
5627 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5634 static void TestStringMatch()
5636 wxPuts(_T("*** Testing wxString::Matches() ***"));
5638 static const struct StringMatchTestData
5641 const wxChar
*wildcard
;
5643 } stringMatchTestData
[] =
5645 { _T("foobar"), _T("foo*"), 1 },
5646 { _T("foobar"), _T("*oo*"), 1 },
5647 { _T("foobar"), _T("*bar"), 1 },
5648 { _T("foobar"), _T("??????"), 1 },
5649 { _T("foobar"), _T("f??b*"), 1 },
5650 { _T("foobar"), _T("f?b*"), 0 },
5651 { _T("foobar"), _T("*goo*"), 0 },
5652 { _T("foobar"), _T("*foo"), 0 },
5653 { _T("foobarfoo"), _T("*foo"), 1 },
5654 { _T(""), _T("*"), 1 },
5655 { _T(""), _T("?"), 0 },
5658 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5660 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5661 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5662 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5664 matches
? _T("matches") : _T("doesn't match"),
5666 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5672 #endif // TEST_STRINGS
5674 // ----------------------------------------------------------------------------
5676 // ----------------------------------------------------------------------------
5678 #ifdef TEST_SNGLINST
5679 #include "wx/snglinst.h"
5680 #endif // TEST_SNGLINST
5682 int main(int argc
, char **argv
)
5684 wxApp::CheckBuildOptions(wxBuildOptions());
5686 wxInitializer initializer
;
5689 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5694 #ifdef TEST_SNGLINST
5695 wxSingleInstanceChecker checker
;
5696 if ( checker
.Create(_T(".wxconsole.lock")) )
5698 if ( checker
.IsAnotherRunning() )
5700 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5705 // wait some time to give time to launch another instance
5706 wxPrintf(_T("Press \"Enter\" to continue..."));
5709 else // failed to create
5711 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5713 #endif // TEST_SNGLINST
5717 #endif // TEST_CHARSET
5720 TestCmdLineConvert();
5722 #if wxUSE_CMDLINE_PARSER
5723 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5725 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5726 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5727 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5728 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5730 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5731 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5732 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5733 wxCMD_LINE_VAL_NUMBER
},
5734 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5735 wxCMD_LINE_VAL_DATE
},
5737 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5738 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5743 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5745 parser
.AddOption("project_name", "", "full path to project file",
5746 wxCMD_LINE_VAL_STRING
,
5747 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5749 switch ( parser
.Parse() )
5752 wxLogMessage("Help was given, terminating.");
5756 ShowCmdLine(parser
);
5760 wxLogMessage("Syntax error detected, aborting.");
5763 #endif // wxUSE_CMDLINE_PARSER
5765 #endif // TEST_CMDLINE
5773 TestStringConstruction();
5776 TestStringTokenizer();
5777 TestStringReplace();
5783 #endif // TEST_STRINGS
5796 puts("*** Initially:");
5798 PrintArray("a1", a1
);
5800 wxArrayString
a2(a1
);
5801 PrintArray("a2", a2
);
5803 wxSortedArrayString
a3(a1
);
5804 PrintArray("a3", a3
);
5806 puts("*** After deleting three strings from a1");
5809 PrintArray("a1", a1
);
5810 PrintArray("a2", a2
);
5811 PrintArray("a3", a3
);
5813 puts("*** After reassigning a1 to a2 and a3");
5815 PrintArray("a2", a2
);
5816 PrintArray("a3", a3
);
5818 puts("*** After sorting a1");
5820 PrintArray("a1", a1
);
5822 puts("*** After sorting a1 in reverse order");
5824 PrintArray("a1", a1
);
5826 puts("*** After sorting a1 by the string length");
5827 a1
.Sort(StringLenCompare
);
5828 PrintArray("a1", a1
);
5830 TestArrayOfObjects();
5831 TestArrayOfUShorts();
5835 #endif // TEST_ARRAYS
5846 #ifdef TEST_DLLLOADER
5848 #endif // TEST_DLLLOADER
5852 #endif // TEST_ENVIRON
5856 #endif // TEST_EXECUTE
5858 #ifdef TEST_FILECONF
5860 #endif // TEST_FILECONF
5868 #endif // TEST_LOCALE
5872 for ( size_t n
= 0; n
< 8000; n
++ )
5874 s
<< (char)('A' + (n
% 26));
5878 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5880 // this one shouldn't be truncated
5883 // but this one will because log functions use fixed size buffer
5884 // (note that it doesn't need '\n' at the end neither - will be added
5886 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5898 #ifdef TEST_FILENAME
5902 fn
.Assign("c:\\foo", "bar.baz");
5903 fn
.Assign("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc");
5910 TestFileNameConstruction();
5911 TestFileNameMakeRelative();
5912 TestFileNameSplit();
5915 TestFileNameComparison();
5916 TestFileNameOperations();
5918 #endif // TEST_FILENAME
5920 #ifdef TEST_FILETIME
5924 #endif // TEST_FILETIME
5927 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5928 if ( TestFtpConnect() )
5939 if ( TEST_INTERACTIVE
)
5940 TestFtpInteractive();
5942 //else: connecting to the FTP server failed
5948 #ifdef TEST_LONGLONG
5949 // seed pseudo random generator
5950 srand((unsigned)time(NULL
));
5959 TestMultiplication();
5962 TestLongLongConversion();
5963 TestBitOperations();
5964 TestLongLongComparison();
5965 TestLongLongPrint();
5967 #endif // TEST_LONGLONG
5975 #endif // TEST_HASHMAP
5978 wxLog::AddTraceMask(_T("mime"));
5986 TestMimeAssociate();
5989 #ifdef TEST_INFO_FUNCTIONS
5995 if ( TEST_INTERACTIVE
)
5998 #endif // TEST_INFO_FUNCTIONS
6000 #ifdef TEST_PATHLIST
6002 #endif // TEST_PATHLIST
6010 #endif // TEST_REGCONF
6013 // TODO: write a real test using src/regex/tests file
6018 TestRegExSubmatch();
6019 TestRegExReplacement();
6021 if ( TEST_INTERACTIVE
)
6022 TestRegExInteractive();
6024 #endif // TEST_REGEX
6026 #ifdef TEST_REGISTRY
6028 TestRegistryAssociation();
6029 #endif // TEST_REGISTRY
6034 #endif // TEST_SOCKETS
6039 #endif // TEST_STREAMS
6042 int nCPUs
= wxThread::GetCPUCount();
6043 printf("This system has %d CPUs\n", nCPUs
);
6045 wxThread::SetConcurrency(nCPUs
);
6049 TestDetachedThreads();
6050 TestJoinableThreads();
6051 TestThreadSuspend();
6053 TestThreadConditions();
6058 #endif // TEST_THREADS
6062 #endif // TEST_TIMER
6064 #ifdef TEST_DATETIME
6077 TestTimeArithmetics();
6080 TestTimeSpanFormat();
6086 if ( TEST_INTERACTIVE
)
6087 TestDateTimeInteractive();
6088 #endif // TEST_DATETIME
6091 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6093 #endif // TEST_USLEEP
6098 #endif // TEST_VCARD
6102 #endif // TEST_VOLUME
6106 TestEncodingConverter();
6107 #endif // TEST_WCHAR
6110 TestZipStreamRead();
6111 TestZipFileSystem();
6115 TestZlibStreamWrite();
6116 TestZlibStreamRead();