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
87 // #define TEST_VCARD -- don't enable this (VZ)
94 static const bool TEST_ALL
= TRUE
;
98 static const bool TEST_ALL
= FALSE
;
101 // some tests are interactive, define this to run them
102 #ifdef TEST_INTERACTIVE
103 #undef TEST_INTERACTIVE
105 static const bool TEST_INTERACTIVE
= TRUE
;
107 static const bool TEST_INTERACTIVE
= FALSE
;
110 // ----------------------------------------------------------------------------
111 // test class for container objects
112 // ----------------------------------------------------------------------------
114 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
116 class Bar
// Foo is already taken in the hash test
119 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
120 Bar(const Bar
& bar
) : m_name(bar
.m_name
) { ms_bars
++; }
121 ~Bar() { ms_bars
--; }
123 static size_t GetNumber() { return ms_bars
; }
125 const wxChar
*GetName() const { return m_name
; }
130 static size_t ms_bars
;
133 size_t Bar
::ms_bars
= 0;
135 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
137 // ============================================================================
139 // ============================================================================
141 // ----------------------------------------------------------------------------
143 // ----------------------------------------------------------------------------
145 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
147 // replace TABs with \t and CRs with \n
148 static wxString
MakePrintable(const wxChar
*s
)
151 (void)str
.Replace(_T("\t"), _T("\\t"));
152 (void)str
.Replace(_T("\n"), _T("\\n"));
153 (void)str
.Replace(_T("\r"), _T("\\r"));
158 #endif // MakePrintable() is used
160 // ----------------------------------------------------------------------------
161 // wxFontMapper::CharsetToEncoding
162 // ----------------------------------------------------------------------------
166 #include "wx/fontmap.h"
168 static void TestCharset()
170 static const wxChar
*charsets
[] =
172 // some vali charsets
181 // and now some bogus ones
188 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
190 wxFontEncoding enc
= wxFontMapper
::Get()->CharsetToEncoding(charsets
[n
]);
191 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
193 wxFontMapper
::Get()->GetEncodingName(enc
).c_str(),
194 wxFontMapper
::Get()->GetEncodingDescription(enc
).c_str());
198 #endif // TEST_CHARSET
200 // ----------------------------------------------------------------------------
202 // ----------------------------------------------------------------------------
206 #include "wx/cmdline.h"
207 #include "wx/datetime.h"
210 #if wxUSE_CMDLINE_PARSER
212 static void ShowCmdLine(const wxCmdLineParser
& parser
)
214 wxString s
= _T("Input files: ");
216 size_t count
= parser
.GetParamCount();
217 for ( size_t param
= 0; param
< count
; param
++ )
219 s
<< parser
.GetParam(param
) << ' ';
223 << _T("Verbose:\t") << (parser
.Found(_T("v")) ?
_T("yes") : _T("no")) << '\n'
224 << _T("Quiet:\t") << (parser
.Found(_T("q")) ?
_T("yes") : _T("no")) << '\n';
229 if ( parser
.Found(_T("o"), &strVal
) )
230 s
<< _T("Output file:\t") << strVal
<< '\n';
231 if ( parser
.Found(_T("i"), &strVal
) )
232 s
<< _T("Input dir:\t") << strVal
<< '\n';
233 if ( parser
.Found(_T("s"), &lVal
) )
234 s
<< _T("Size:\t") << lVal
<< '\n';
235 if ( parser
.Found(_T("d"), &dt
) )
236 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
237 if ( parser
.Found(_T("project_name"), &strVal
) )
238 s
<< _T("Project:\t") << strVal
<< '\n';
243 #endif // wxUSE_CMDLINE_PARSER
245 static void TestCmdLineConvert()
247 static const wxChar
*cmdlines
[] =
250 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
251 _T("literal \\\" and \"\""),
254 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
256 const wxChar
*cmdline
= cmdlines
[n
];
257 wxPrintf(_T("Parsing: %s\n"), cmdline
);
258 wxArrayString args
= wxCmdLineParser
::ConvertStringToArgs(cmdline
);
260 size_t count
= args
.GetCount();
261 wxPrintf(_T("\targc = %u\n"), count
);
262 for ( size_t arg
= 0; arg
< count
; arg
++ )
264 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
269 #endif // TEST_CMDLINE
271 // ----------------------------------------------------------------------------
273 // ----------------------------------------------------------------------------
280 static const wxChar
*ROOTDIR
= _T("/");
281 static const wxChar
*TESTDIR
= _T("/usr");
282 #elif defined(__WXMSW__)
283 static const wxChar
*ROOTDIR
= _T("c:\\");
284 static const wxChar
*TESTDIR
= _T("d:\\");
286 #error "don't know where the root directory is"
289 static void TestDirEnumHelper(wxDir
& dir
,
290 int flags
= wxDIR_DEFAULT
,
291 const wxString
& filespec
= wxEmptyString
)
295 if ( !dir
.IsOpened() )
298 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
301 wxPrintf(_T("\t%s\n"), filename
.c_str());
303 cont
= dir
.GetNext(&filename
);
309 static void TestDirEnum()
311 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
313 wxString cwd
= wxGetCwd();
314 if ( !wxDir
::Exists(cwd
) )
316 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
321 if ( !dir
.IsOpened() )
323 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
327 wxPuts(_T("Enumerating everything in current directory:"));
328 TestDirEnumHelper(dir
);
330 wxPuts(_T("Enumerating really everything in current directory:"));
331 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
333 wxPuts(_T("Enumerating object files in current directory:"));
334 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o*");
336 wxPuts(_T("Enumerating directories in current directory:"));
337 TestDirEnumHelper(dir
, wxDIR_DIRS
);
339 wxPuts(_T("Enumerating files in current directory:"));
340 TestDirEnumHelper(dir
, wxDIR_FILES
);
342 wxPuts(_T("Enumerating files including hidden in current directory:"));
343 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
347 wxPuts(_T("Enumerating everything in root directory:"));
348 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
350 wxPuts(_T("Enumerating directories in root directory:"));
351 TestDirEnumHelper(dir
, wxDIR_DIRS
);
353 wxPuts(_T("Enumerating files in root directory:"));
354 TestDirEnumHelper(dir
, wxDIR_FILES
);
356 wxPuts(_T("Enumerating files including hidden in root directory:"));
357 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
359 wxPuts(_T("Enumerating files in non existing directory:"));
360 wxDir
dirNo("nosuchdir");
361 TestDirEnumHelper(dirNo
);
364 class DirPrintTraverser
: public wxDirTraverser
367 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
369 return wxDIR_CONTINUE
;
372 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
374 wxString path
, name
, ext
;
375 wxSplitPath(dirname
, &path
, &name
, &ext
);
378 name
<< _T('.') << ext
;
381 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
383 if ( wxIsPathSeparator(*p
) )
387 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
389 return wxDIR_CONTINUE
;
393 static void TestDirTraverse()
395 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
399 size_t n
= wxDir
::GetAllFiles(TESTDIR
, &files
);
400 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
403 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
404 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
407 // enum again with custom traverser
409 DirPrintTraverser traverser
;
410 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
413 static void TestDirExists()
415 wxPuts(_T("*** Testing wxDir::Exists() ***"));
417 static const wxChar
*dirnames
[] =
420 #if defined(__WXMSW__)
423 _T("\\\\share\\file"),
427 _T("c:\\autoexec.bat"),
428 #elif defined(__UNIX__)
437 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
439 wxPrintf(_T("%-40s: %s\n"),
441 wxDir
::Exists(dirnames
[n
]) ?
_T("exists")
442 : _T("doesn't exist"));
448 // ----------------------------------------------------------------------------
450 // ----------------------------------------------------------------------------
452 #ifdef TEST_DLLLOADER
454 #include "wx/dynlib.h"
456 static void TestDllLoad()
458 #if defined(__WXMSW__)
459 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
460 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
461 #elif defined(__UNIX__)
462 // weird: using just libc.so does *not* work!
463 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
464 static const wxChar
*FUNC_NAME
= _T("strlen");
466 #error "don't know how to test wxDllLoader on this platform"
469 wxPuts(_T("*** testing wxDllLoader ***\n"));
471 wxDynamicLibrary
lib(LIB_NAME
);
472 if ( !lib
.IsLoaded() )
474 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
478 typedef int (*wxStrlenType
)(const char *);
479 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
482 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
483 FUNC_NAME
, LIB_NAME
);
487 if ( pfnStrlen("foo") != 3 )
489 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
493 wxPuts(_T("... ok"));
499 #endif // TEST_DLLLOADER
501 // ----------------------------------------------------------------------------
503 // ----------------------------------------------------------------------------
507 #include "wx/utils.h"
509 static wxString
MyGetEnv(const wxString
& var
)
512 if ( !wxGetEnv(var
, &val
) )
515 val
= wxString(_T('\'')) + val
+ _T('\'');
520 static void TestEnvironment()
522 const wxChar
*var
= _T("wxTestVar");
524 wxPuts(_T("*** testing environment access functions ***"));
526 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
527 wxSetEnv(var
, _T("value for wxTestVar"));
528 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
529 wxSetEnv(var
, _T("another value"));
530 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
532 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
533 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
536 #endif // TEST_ENVIRON
538 // ----------------------------------------------------------------------------
540 // ----------------------------------------------------------------------------
544 #include "wx/utils.h"
546 static void TestExecute()
548 wxPuts(_T("*** testing wxExecute ***"));
551 #define COMMAND "cat -n ../../Makefile" // "echo hi"
552 #define SHELL_COMMAND "echo hi from shell"
553 #define REDIRECT_COMMAND COMMAND // "date"
554 #elif defined(__WXMSW__)
555 #define COMMAND "command.com /c echo hi"
556 #define SHELL_COMMAND "echo hi"
557 #define REDIRECT_COMMAND COMMAND
559 #error "no command to exec"
562 wxPrintf(_T("Testing wxShell: "));
564 if ( wxShell(SHELL_COMMAND
) )
567 wxPuts(_T("ERROR."));
569 wxPrintf(_T("Testing wxExecute: "));
571 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
574 wxPuts(_T("ERROR."));
576 #if 0 // no, it doesn't work (yet?)
577 wxPrintf(_T("Testing async wxExecute: "));
579 if ( wxExecute(COMMAND
) != 0 )
580 wxPuts(_T("Ok (command launched)."));
582 wxPuts(_T("ERROR."));
585 wxPrintf(_T("Testing wxExecute with redirection:\n"));
586 wxArrayString output
;
587 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
589 wxPuts(_T("ERROR."));
593 size_t count
= output
.GetCount();
594 for ( size_t n
= 0; n
< count
; n
++ )
596 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
603 #endif // TEST_EXECUTE
605 // ----------------------------------------------------------------------------
607 // ----------------------------------------------------------------------------
612 #include "wx/ffile.h"
613 #include "wx/textfile.h"
615 static void TestFileRead()
617 wxPuts(_T("*** wxFile read test ***"));
619 wxFile
file(_T("testdata.fc"));
620 if ( file
.IsOpened() )
622 wxPrintf(_T("File length: %lu\n"), file
.Length());
624 wxPuts(_T("File dump:\n----------"));
626 static const off_t len
= 1024;
630 off_t nRead
= file
.Read(buf
, len
);
631 if ( nRead
== wxInvalidOffset
)
633 wxPrintf(_T("Failed to read the file."));
637 fwrite(buf
, nRead
, 1, stdout
);
643 wxPuts(_T("----------"));
647 wxPrintf(_T("ERROR: can't open test file.\n"));
653 static void TestTextFileRead()
655 wxPuts(_T("*** wxTextFile read test ***"));
657 wxTextFile
file(_T("testdata.fc"));
660 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
661 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
665 wxPuts(_T("\nDumping the entire file:"));
666 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
668 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
670 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
672 wxPuts(_T("\nAnd now backwards:"));
673 for ( s
= file
.GetLastLine();
674 file
.GetCurrentLine() != 0;
675 s
= file
.GetPrevLine() )
677 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
679 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
683 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
689 static void TestFileCopy()
691 wxPuts(_T("*** Testing wxCopyFile ***"));
693 static const wxChar
*filename1
= _T("testdata.fc");
694 static const wxChar
*filename2
= _T("test2");
695 if ( !wxCopyFile(filename1
, filename2
) )
697 wxPuts(_T("ERROR: failed to copy file"));
701 wxFFile
f1(filename1
, "rb"),
704 if ( !f1
.IsOpened() || !f2
.IsOpened() )
706 wxPuts(_T("ERROR: failed to open file(s)"));
711 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
713 wxPuts(_T("ERROR: failed to read file(s)"));
717 if ( (s1
.length() != s2
.length()) ||
718 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
720 wxPuts(_T("ERROR: copy error!"));
724 wxPuts(_T("File was copied ok."));
730 if ( !wxRemoveFile(filename2
) )
732 wxPuts(_T("ERROR: failed to remove the file"));
740 // ----------------------------------------------------------------------------
742 // ----------------------------------------------------------------------------
746 #include "wx/confbase.h"
747 #include "wx/fileconf.h"
749 static const struct FileConfTestData
751 const wxChar
*name
; // value name
752 const wxChar
*value
; // the value from the file
755 { _T("value1"), _T("one") },
756 { _T("value2"), _T("two") },
757 { _T("novalue"), _T("default") },
760 static void TestFileConfRead()
762 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
764 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
765 _T("testdata.fc"), wxEmptyString
,
766 wxCONFIG_USE_RELATIVE_PATH
);
768 // test simple reading
769 wxPuts(_T("\nReading config file:"));
770 wxString
defValue(_T("default")), value
;
771 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
773 const FileConfTestData
& data
= fcTestData
[n
];
774 value
= fileconf
.Read(data
.name
, defValue
);
775 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
776 if ( value
== data
.value
)
782 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
786 // test enumerating the entries
787 wxPuts(_T("\nEnumerating all root entries:"));
790 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
793 wxPrintf(_T("\t%s = %s\n"),
795 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
797 cont
= fileconf
.GetNextEntry(name
, dummy
);
801 #endif // TEST_FILECONF
803 // ----------------------------------------------------------------------------
805 // ----------------------------------------------------------------------------
809 #include "wx/filename.h"
811 static void DumpFileName(const wxFileName
& fn
)
813 wxString full
= fn
.GetFullPath();
815 wxString vol
, path
, name
, ext
;
816 wxFileName
::SplitPath(full
, &vol
, &path
, &name
, &ext
);
818 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
819 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
821 wxFileName
::SplitPath(full
, &path
, &name
, &ext
);
822 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
823 path
.c_str(), name
.c_str(), ext
.c_str());
825 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
826 wxPrintf(_T("with volume: \t'%s'\n"),
827 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
828 wxPrintf(_T("with separator:\t'%s'\n"),
829 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
830 wxPrintf(_T("with both: \t'%s'\n"),
831 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
833 wxPuts(_T("The directories in the path are:"));
834 wxArrayString dirs
= fn
.GetDirs();
835 size_t count
= dirs
.GetCount();
836 for ( size_t n
= 0; n
< count
; n
++ )
838 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
842 static struct FileNameInfo
844 const wxChar
*fullname
;
845 const wxChar
*volume
;
854 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
855 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
856 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
857 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
858 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
859 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
860 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
861 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
862 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
864 // Windows file names
865 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
866 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
867 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
868 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
869 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
870 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
871 { _T("\\\\server\\dir\\foo.bar"), _T("server"), _T("\\dir"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
873 // wxFileName support for Mac file names is broken currently
876 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
877 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
878 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
879 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
880 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
881 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
885 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
886 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
889 static void TestFileNameConstruction()
891 wxPuts(_T("*** testing wxFileName construction ***"));
893 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
895 const FileNameInfo
& fni
= filenames
[n
];
897 wxFileName
fn(fni
.fullname
, fni
.format
);
899 wxString fullname
= fn
.GetFullPath(fni
.format
);
900 if ( fullname
!= fni
.fullname
)
902 wxPrintf(_T("ERROR: fullname should be '%s'\n"), fni
.fullname
);
905 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
906 wxPrintf(_T("'%s' is %s (%s)\n\t"),
908 isAbsolute ?
"absolute" : "relative",
909 isAbsolute
== fni
.isAbsolute ?
"ok" : "ERROR");
911 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
913 wxPuts(_T("ERROR (couldn't be normalized)"));
917 wxPrintf(_T("normalized: '%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
924 static void TestFileNameSplit()
926 wxPuts(_T("*** testing wxFileName splitting ***"));
928 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
930 const FileNameInfo
& fni
= filenames
[n
];
931 wxString volume
, path
, name
, ext
;
932 wxFileName
::SplitPath(fni
.fullname
,
933 &volume
, &path
, &name
, &ext
, fni
.format
);
935 wxPrintf(_T("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'"),
937 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
939 if ( volume
!= fni
.volume
)
940 wxPrintf(_T(" (ERROR: volume = '%s')"), fni
.volume
);
941 if ( path
!= fni
.path
)
942 wxPrintf(_T(" (ERROR: path = '%s')"), fni
.path
);
943 if ( name
!= fni
.name
)
944 wxPrintf(_T(" (ERROR: name = '%s')"), fni
.name
);
945 if ( ext
!= fni
.ext
)
946 wxPrintf(_T(" (ERROR: ext = '%s')"), fni
.ext
);
952 static void TestFileNameTemp()
954 wxPuts(_T("*** testing wxFileName temp file creation ***"));
956 static const wxChar
*tmpprefixes
[] =
964 _T("/tmp/foo/bar"), // this one must be an error
968 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
970 wxString path
= wxFileName
::CreateTempFileName(tmpprefixes
[n
]);
973 // "error" is not in upper case because it may be ok
974 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
978 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
979 tmpprefixes
[n
], path
.c_str());
981 if ( !wxRemoveFile(path
) )
983 wxLogWarning(_T("Failed to remove temp file '%s'"),
990 static void TestFileNameMakeRelative()
992 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
994 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
996 const FileNameInfo
& fni
= filenames
[n
];
998 wxFileName
fn(fni
.fullname
, fni
.format
);
1000 // choose the base dir of the same format
1002 switch ( fni
.format
)
1014 // TODO: I don't know how this is supposed to work there
1017 case wxPATH_NATIVE
: // make gcc happy
1019 wxFAIL_MSG( "unexpected path format" );
1022 wxPrintf(_T("'%s' relative to '%s': "),
1023 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
1025 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
1027 wxPuts(_T("unchanged"));
1031 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
1036 static void TestFileNameComparison()
1041 static void TestFileNameOperations()
1046 static void TestFileNameCwd()
1051 #endif // TEST_FILENAME
1053 // ----------------------------------------------------------------------------
1054 // wxFileName time functions
1055 // ----------------------------------------------------------------------------
1057 #ifdef TEST_FILETIME
1059 #include <wx/filename.h>
1060 #include <wx/datetime.h>
1062 static void TestFileGetTimes()
1064 wxFileName
fn(_T("testdata.fc"));
1066 wxDateTime dtAccess
, dtMod
, dtCreate
;
1067 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1069 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1073 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1075 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1076 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1077 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1078 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1082 static void TestFileSetTimes()
1084 wxFileName
fn(_T("testdata.fc"));
1088 wxPrintf(_T("ERROR: Touch() failed.\n"));
1092 #endif // TEST_FILETIME
1094 // ----------------------------------------------------------------------------
1096 // ----------------------------------------------------------------------------
1100 #include "wx/hash.h"
1104 Foo(int n_
) { n
= n_
; count
++; }
1109 static size_t count
;
1112 size_t Foo
::count
= 0;
1114 WX_DECLARE_LIST(Foo
, wxListFoos
);
1115 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1117 #include "wx/listimpl.cpp"
1119 WX_DEFINE_LIST(wxListFoos
);
1121 static void TestHash()
1123 wxPuts(_T("*** Testing wxHashTable ***\n"));
1127 hash
.DeleteContents(TRUE
);
1129 wxPrintf(_T("Hash created: %u foos in hash, %u foos totally\n"),
1130 hash
.GetCount(), Foo
::count
);
1132 static const int hashTestData
[] =
1134 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1138 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1140 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1143 wxPrintf(_T("Hash filled: %u foos in hash, %u foos totally\n"),
1144 hash
.GetCount(), Foo
::count
);
1146 wxPuts(_T("Hash access test:"));
1147 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1149 wxPrintf(_T("\tGetting element with key %d, value %d: "),
1150 hashTestData
[n
], n
);
1151 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1154 wxPrintf(_T("ERROR, not found.\n"));
1158 wxPrintf(_T("%d (%s)\n"), foo
->n
,
1159 (size_t)foo
->n
== n ?
"ok" : "ERROR");
1163 wxPrintf(_T("\nTrying to get an element not in hash: "));
1165 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1167 wxPuts(_T("ERROR: found!"));
1171 wxPuts(_T("ok (not found)"));
1175 wxPrintf(_T("Hash destroyed: %u foos left\n"), Foo
::count
);
1180 // ----------------------------------------------------------------------------
1182 // ----------------------------------------------------------------------------
1186 #include "wx/hashmap.h"
1188 // test compilation of basic map types
1189 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1190 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1191 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1192 myUnsignedHashMap
);
1193 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1195 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1197 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1199 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1203 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1204 // myStringHashMap );
1205 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1207 typedef myStringHashMap
::iterator Itor
;
1209 static void TestHashMap()
1211 wxPuts(_T("*** Testing wxHashMap ***\n"));
1212 myStringHashMap
sh(0); // as small as possible
1215 const size_t count
= 10000;
1217 // init with some data
1218 for( i
= 0; i
< count
; ++i
)
1220 buf
.Printf(wxT("%d"), i
);
1221 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1224 // test that insertion worked
1225 if( sh
.size() != count
)
1227 wxPrintf(_T("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n"), sh
.size(), count
);
1230 for( i
= 0; i
< count
; ++i
)
1232 buf
.Printf(wxT("%d"), i
);
1233 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1235 wxPrintf(_T("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n"));
1240 // check that iterators work
1242 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1246 wxPrintf(_T("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n"));
1250 if( it
->second
!= sh
[it
->first
] )
1252 wxPrintf(_T("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n"));
1257 if( sh
.size() != i
)
1259 wxPrintf(_T("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n"), i
, count
);
1262 // test copy ctor, assignment operator
1263 myStringHashMap
h1( sh
), h2( 0 );
1266 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1268 if( h1
[it
->first
] != it
->second
)
1270 wxPrintf(_T("*** ERROR: COPY CTOR BROKEN %s ***\n"), it
->first
.c_str());
1273 if( h2
[it
->first
] != it
->second
)
1275 wxPrintf(_T("*** ERROR: OPERATOR= BROKEN %s ***\n"), it
->first
.c_str());
1280 for( i
= 0; i
< count
; ++i
)
1282 buf
.Printf(wxT("%d"), i
);
1283 size_t sz
= sh
.size();
1285 // test find() and erase(it)
1288 it
= sh
.find( buf
);
1289 if( it
!= sh
.end() )
1293 if( sh
.find( buf
) != sh
.end() )
1295 wxPrintf(_T("*** ERROR: FOUND DELETED ELEMENT %u ***\n"), i
);
1299 wxPrintf(_T("*** ERROR: CANT FIND ELEMENT %u ***\n"), i
);
1304 size_t c
= sh
.erase( buf
);
1306 wxPrintf(_T("*** ERROR: SHOULD RETURN 1 ***\n"));
1308 if( sh
.find( buf
) != sh
.end() )
1310 wxPrintf(_T("*** ERROR: FOUND DELETED ELEMENT %u ***\n"), i
);
1314 // count should decrease
1315 if( sh
.size() != sz
- 1 )
1317 wxPrintf(_T("*** ERROR: COUNT DID NOT DECREASE ***\n"));
1321 wxPrintf(_T("*** Finished testing wxHashMap ***\n"));
1324 #endif // TEST_HASHMAP
1326 // ----------------------------------------------------------------------------
1328 // ----------------------------------------------------------------------------
1332 #include "wx/list.h"
1334 WX_DECLARE_LIST(Bar
, wxListBars
);
1335 #include "wx/listimpl.cpp"
1336 WX_DEFINE_LIST(wxListBars
);
1338 static void TestListCtor()
1340 wxPuts(_T("*** Testing wxList construction ***\n"));
1344 list1
.Append(new Bar(_T("first")));
1345 list1
.Append(new Bar(_T("second")));
1347 wxPrintf(_T("After 1st list creation: %u objects in the list, %u objects total.\n"),
1348 list1
.GetCount(), Bar
::GetNumber());
1353 wxPrintf(_T("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n"),
1354 list1
.GetCount(), list2
.GetCount(), Bar
::GetNumber());
1356 list1
.DeleteContents(TRUE
);
1359 wxPrintf(_T("After list destruction: %u objects left.\n"), Bar
::GetNumber());
1364 // ----------------------------------------------------------------------------
1366 // ----------------------------------------------------------------------------
1370 #include "wx/intl.h"
1371 #include "wx/utils.h" // for wxSetEnv
1373 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1375 // find the name of the language from its value
1376 static const wxChar
*GetLangName(int lang
)
1378 static const wxChar
*languageNames
[] =
1388 _T("ARABIC_ALGERIA"),
1389 _T("ARABIC_BAHRAIN"),
1392 _T("ARABIC_JORDAN"),
1393 _T("ARABIC_KUWAIT"),
1394 _T("ARABIC_LEBANON"),
1396 _T("ARABIC_MOROCCO"),
1399 _T("ARABIC_SAUDI_ARABIA"),
1402 _T("ARABIC_TUNISIA"),
1409 _T("AZERI_CYRILLIC"),
1424 _T("CHINESE_SIMPLIFIED"),
1425 _T("CHINESE_TRADITIONAL"),
1426 _T("CHINESE_HONGKONG"),
1427 _T("CHINESE_MACAU"),
1428 _T("CHINESE_SINGAPORE"),
1429 _T("CHINESE_TAIWAN"),
1435 _T("DUTCH_BELGIAN"),
1439 _T("ENGLISH_AUSTRALIA"),
1440 _T("ENGLISH_BELIZE"),
1441 _T("ENGLISH_BOTSWANA"),
1442 _T("ENGLISH_CANADA"),
1443 _T("ENGLISH_CARIBBEAN"),
1444 _T("ENGLISH_DENMARK"),
1446 _T("ENGLISH_JAMAICA"),
1447 _T("ENGLISH_NEW_ZEALAND"),
1448 _T("ENGLISH_PHILIPPINES"),
1449 _T("ENGLISH_SOUTH_AFRICA"),
1450 _T("ENGLISH_TRINIDAD"),
1451 _T("ENGLISH_ZIMBABWE"),
1459 _T("FRENCH_BELGIAN"),
1460 _T("FRENCH_CANADIAN"),
1461 _T("FRENCH_LUXEMBOURG"),
1462 _T("FRENCH_MONACO"),
1468 _T("GERMAN_AUSTRIAN"),
1469 _T("GERMAN_BELGIUM"),
1470 _T("GERMAN_LIECHTENSTEIN"),
1471 _T("GERMAN_LUXEMBOURG"),
1489 _T("ITALIAN_SWISS"),
1494 _T("KASHMIRI_INDIA"),
1512 _T("MALAY_BRUNEI_DARUSSALAM"),
1513 _T("MALAY_MALAYSIA"),
1523 _T("NORWEGIAN_BOKMAL"),
1524 _T("NORWEGIAN_NYNORSK"),
1531 _T("PORTUGUESE_BRAZILIAN"),
1534 _T("RHAETO_ROMANCE"),
1537 _T("RUSSIAN_UKRAINE"),
1543 _T("SERBIAN_CYRILLIC"),
1544 _T("SERBIAN_LATIN"),
1545 _T("SERBO_CROATIAN"),
1556 _T("SPANISH_ARGENTINA"),
1557 _T("SPANISH_BOLIVIA"),
1558 _T("SPANISH_CHILE"),
1559 _T("SPANISH_COLOMBIA"),
1560 _T("SPANISH_COSTA_RICA"),
1561 _T("SPANISH_DOMINICAN_REPUBLIC"),
1562 _T("SPANISH_ECUADOR"),
1563 _T("SPANISH_EL_SALVADOR"),
1564 _T("SPANISH_GUATEMALA"),
1565 _T("SPANISH_HONDURAS"),
1566 _T("SPANISH_MEXICAN"),
1567 _T("SPANISH_MODERN"),
1568 _T("SPANISH_NICARAGUA"),
1569 _T("SPANISH_PANAMA"),
1570 _T("SPANISH_PARAGUAY"),
1572 _T("SPANISH_PUERTO_RICO"),
1573 _T("SPANISH_URUGUAY"),
1575 _T("SPANISH_VENEZUELA"),
1579 _T("SWEDISH_FINLAND"),
1597 _T("URDU_PAKISTAN"),
1599 _T("UZBEK_CYRILLIC"),
1612 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1613 return languageNames
[lang
];
1615 return _T("INVALID");
1618 static void TestDefaultLang()
1620 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1622 static const wxChar
*langStrings
[] =
1624 NULL
, // system default
1631 _T("de_DE.iso88591"),
1633 _T("?"), // invalid lang spec
1634 _T("klingonese"), // I bet on some systems it does exist...
1637 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1638 wxLocale
::GetSystemEncodingName().c_str(),
1639 wxLocale
::GetSystemEncoding());
1641 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1643 const wxChar
*langStr
= langStrings
[n
];
1646 // FIXME: this doesn't do anything at all under Windows, we need
1647 // to create a new wxLocale!
1648 wxSetEnv(_T("LC_ALL"), langStr
);
1651 int lang
= gs_localeDefault
.GetSystemLanguage();
1652 wxPrintf(_T("Locale for '%s' is %s.\n"),
1653 langStr ? langStr
: _T("system default"), GetLangName(lang
));
1657 #endif // TEST_LOCALE
1659 // ----------------------------------------------------------------------------
1661 // ----------------------------------------------------------------------------
1665 #include "wx/mimetype.h"
1667 static void TestMimeEnum()
1669 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1671 wxArrayString mimetypes
;
1673 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1675 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1680 for ( size_t n
= 0; n
< count
; n
++ )
1682 wxFileType
*filetype
=
1683 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1686 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1687 mimetypes
[n
].c_str());
1691 filetype
->GetDescription(&desc
);
1692 filetype
->GetExtensions(exts
);
1694 filetype
->GetIcon(NULL
);
1697 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1700 extsAll
<< _T(", ");
1704 wxPrintf(_T("\t%s: %s (%s)\n"),
1705 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1711 static void TestMimeOverride()
1713 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1715 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1716 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1718 if ( wxFile
::Exists(mailcap
) )
1719 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1721 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ?
_T("ok") : _T("ERROR"));
1723 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1726 if ( wxFile
::Exists(mimetypes
) )
1727 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1729 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ?
_T("ok") : _T("ERROR"));
1731 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1737 static void TestMimeFilename()
1739 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1741 static const wxChar
*filenames
[] =
1749 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1751 const wxString fname
= filenames
[n
];
1752 wxString ext
= fname
.AfterLast(_T('.'));
1753 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1756 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1761 if ( !ft
->GetDescription(&desc
) )
1762 desc
= _T("<no description>");
1765 if ( !ft
->GetOpenCommand(&cmd
,
1766 wxFileType
::MessageParameters(fname
, _T(""))) )
1767 cmd
= _T("<no command available>");
1769 cmd
= wxString('"') + cmd
+ '"';
1771 wxPrintf(_T("To open %s (%s) do %s.\n"),
1772 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1781 static void TestMimeAssociate()
1783 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1785 wxFileTypeInfo
ftInfo(
1786 _T("application/x-xyz"),
1787 _T("xyzview '%s'"), // open cmd
1788 _T(""), // print cmd
1789 _T("XYZ File"), // description
1790 _T(".xyz"), // extensions
1791 NULL
// end of extensions
1793 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1795 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1798 wxPuts(_T("ERROR: failed to create association!"));
1802 // TODO: read it back
1811 // ----------------------------------------------------------------------------
1812 // misc information functions
1813 // ----------------------------------------------------------------------------
1815 #ifdef TEST_INFO_FUNCTIONS
1817 #include "wx/utils.h"
1819 static void TestDiskInfo()
1821 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1825 wxChar pathname
[128];
1826 wxPrintf(_T("\nEnter a directory name: "));
1827 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1830 // kill the last '\n'
1831 pathname
[wxStrlen(pathname
) - 1] = 0;
1833 wxLongLong total
, free
;
1834 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1836 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1840 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1841 (total
/ 1024).ToString().c_str(),
1842 (free
/ 1024).ToString().c_str(),
1848 static void TestOsInfo()
1850 wxPuts(_T("*** Testing OS info functions ***\n"));
1853 wxGetOsVersion(&major
, &minor
);
1854 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1855 wxGetOsDescription().c_str(), major
, minor
);
1857 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1859 wxPrintf(_T("Host name is %s (%s).\n"),
1860 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1865 static void TestUserInfo()
1867 wxPuts(_T("*** Testing user info functions ***\n"));
1869 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1870 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1871 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1872 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1877 #endif // TEST_INFO_FUNCTIONS
1879 // ----------------------------------------------------------------------------
1881 // ----------------------------------------------------------------------------
1883 #ifdef TEST_LONGLONG
1885 #include "wx/longlong.h"
1886 #include "wx/timer.h"
1888 // make a 64 bit number from 4 16 bit ones
1889 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1891 // get a random 64 bit number
1892 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1894 static const long testLongs
[] =
1905 #if wxUSE_LONGLONG_WX
1906 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1907 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1908 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1909 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1910 #endif // wxUSE_LONGLONG_WX
1912 static void TestSpeed()
1914 static const long max
= 100000000;
1921 for ( n
= 0; n
< max
; n
++ )
1926 wxPrintf(_T("Summing longs took %ld milliseconds.\n"), sw
.Time());
1929 #if wxUSE_LONGLONG_NATIVE
1934 for ( n
= 0; n
< max
; n
++ )
1939 wxPrintf(_T("Summing wxLongLong_t took %ld milliseconds.\n"), sw
.Time());
1941 #endif // wxUSE_LONGLONG_NATIVE
1947 for ( n
= 0; n
< max
; n
++ )
1952 wxPrintf(_T("Summing wxLongLongs took %ld milliseconds.\n"), sw
.Time());
1956 static void TestLongLongConversion()
1958 wxPuts(_T("*** Testing wxLongLong conversions ***\n"));
1962 for ( size_t n
= 0; n
< 100000; n
++ )
1966 #if wxUSE_LONGLONG_NATIVE
1967 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1969 wxASSERT_MSG( a
== b
, "conversions failure" );
1971 wxPuts(_T("Can't do it without native long long type, test skipped."));
1974 #endif // wxUSE_LONGLONG_NATIVE
1976 if ( !(nTested
% 1000) )
1985 wxPuts(_T(" done!"));
1988 static void TestMultiplication()
1990 wxPuts(_T("*** Testing wxLongLong multiplication ***\n"));
1994 for ( size_t n
= 0; n
< 100000; n
++ )
1999 #if wxUSE_LONGLONG_NATIVE
2000 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
2001 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
2003 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
2004 #else // !wxUSE_LONGLONG_NATIVE
2005 wxPuts(_T("Can't do it without native long long type, test skipped."));
2008 #endif // wxUSE_LONGLONG_NATIVE
2010 if ( !(nTested
% 1000) )
2019 wxPuts(_T(" done!"));
2022 static void TestDivision()
2024 wxPuts(_T("*** Testing wxLongLong division ***\n"));
2028 for ( size_t n
= 0; n
< 100000; n
++ )
2030 // get a random wxLongLong (shifting by 12 the MSB ensures that the
2031 // multiplication will not overflow)
2032 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
2034 // get a random (but non null) long (not wxLongLong for now) to divide
2046 #if wxUSE_LONGLONG_NATIVE
2047 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
2049 wxLongLongNative p
= m
/ l
, s
= m
% l
;
2050 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
2051 #else // !wxUSE_LONGLONG_NATIVE
2052 // verify the result
2053 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
2054 #endif // wxUSE_LONGLONG_NATIVE
2056 if ( !(nTested
% 1000) )
2065 wxPuts(_T(" done!"));
2068 static void TestAddition()
2070 wxPuts(_T("*** Testing wxLongLong addition ***\n"));
2074 for ( size_t n
= 0; n
< 100000; n
++ )
2080 #if wxUSE_LONGLONG_NATIVE
2081 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2082 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2083 "addition failure" );
2084 #else // !wxUSE_LONGLONG_NATIVE
2085 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2086 #endif // wxUSE_LONGLONG_NATIVE
2088 if ( !(nTested
% 1000) )
2097 wxPuts(_T(" done!"));
2100 static void TestBitOperations()
2102 wxPuts(_T("*** Testing wxLongLong bit operation ***\n"));
2106 for ( size_t n
= 0; n
< 100000; n
++ )
2110 #if wxUSE_LONGLONG_NATIVE
2111 for ( size_t n
= 0; n
< 33; n
++ )
2114 #else // !wxUSE_LONGLONG_NATIVE
2115 wxPuts(_T("Can't do it without native long long type, test skipped."));
2118 #endif // wxUSE_LONGLONG_NATIVE
2120 if ( !(nTested
% 1000) )
2129 wxPuts(_T(" done!"));
2132 static void TestLongLongComparison()
2134 #if wxUSE_LONGLONG_WX
2135 wxPuts(_T("*** Testing wxLongLong comparison ***\n"));
2137 static const long ls
[2] =
2143 wxLongLongWx lls
[2];
2147 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2151 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2153 res
= lls
[m
] > testLongs
[n
];
2154 wxPrintf(_T("0x%lx > 0x%lx is %s (%s)\n"),
2155 ls
[m
], testLongs
[n
], res ?
"true" : "false",
2156 res
== (ls
[m
] > testLongs
[n
]) ?
"ok" : "ERROR");
2158 res
= lls
[m
] < testLongs
[n
];
2159 wxPrintf(_T("0x%lx < 0x%lx is %s (%s)\n"),
2160 ls
[m
], testLongs
[n
], res ?
"true" : "false",
2161 res
== (ls
[m
] < testLongs
[n
]) ?
"ok" : "ERROR");
2163 res
= lls
[m
] == testLongs
[n
];
2164 wxPrintf(_T("0x%lx == 0x%lx is %s (%s)\n"),
2165 ls
[m
], testLongs
[n
], res ?
"true" : "false",
2166 res
== (ls
[m
] == testLongs
[n
]) ?
"ok" : "ERROR");
2169 #endif // wxUSE_LONGLONG_WX
2172 static void TestLongLongPrint()
2174 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2176 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2178 wxLongLong ll
= testLongs
[n
];
2179 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2182 wxLongLong
ll(0x12345678, 0x87654321);
2183 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2186 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2192 #endif // TEST_LONGLONG
2194 // ----------------------------------------------------------------------------
2196 // ----------------------------------------------------------------------------
2198 #ifdef TEST_PATHLIST
2201 #define CMD_IN_PATH _T("ls")
2203 #define CMD_IN_PATH _T("command.com")
2206 static void TestPathList()
2208 wxPuts(_T("*** Testing wxPathList ***\n"));
2210 wxPathList pathlist
;
2211 pathlist
.AddEnvList(_T("PATH"));
2212 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
2215 wxPrintf(_T("ERROR: command not found in the path.\n"));
2219 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
2223 #endif // TEST_PATHLIST
2225 // ----------------------------------------------------------------------------
2226 // regular expressions
2227 // ----------------------------------------------------------------------------
2231 #include "wx/regex.h"
2233 static void TestRegExCompile()
2235 wxPuts(_T("*** Testing RE compilation ***\n"));
2237 static struct RegExCompTestData
2239 const wxChar
*pattern
;
2241 } regExCompTestData
[] =
2243 { _T("foo"), TRUE
},
2244 { _T("foo("), FALSE
},
2245 { _T("foo(bar"), FALSE
},
2246 { _T("foo(bar)"), TRUE
},
2247 { _T("foo["), FALSE
},
2248 { _T("foo[bar"), FALSE
},
2249 { _T("foo[bar]"), TRUE
},
2250 { _T("foo{"), TRUE
},
2251 { _T("foo{1"), FALSE
},
2252 { _T("foo{bar"), TRUE
},
2253 { _T("foo{1}"), TRUE
},
2254 { _T("foo{1,2}"), TRUE
},
2255 { _T("foo{bar}"), TRUE
},
2256 { _T("foo*"), TRUE
},
2257 { _T("foo**"), FALSE
},
2258 { _T("foo+"), TRUE
},
2259 { _T("foo++"), FALSE
},
2260 { _T("foo?"), TRUE
},
2261 { _T("foo??"), FALSE
},
2262 { _T("foo?+"), FALSE
},
2266 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2268 const RegExCompTestData
& data
= regExCompTestData
[n
];
2269 bool ok
= re
.Compile(data
.pattern
);
2271 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2273 ok ?
_T("") : _T("not "),
2274 ok
== data
.correct ?
_T("ok") : _T("ERROR"));
2278 static void TestRegExMatch()
2280 wxPuts(_T("*** Testing RE matching ***\n"));
2282 static struct RegExMatchTestData
2284 const wxChar
*pattern
;
2287 } regExMatchTestData
[] =
2289 { _T("foo"), _T("bar"), FALSE
},
2290 { _T("foo"), _T("foobar"), TRUE
},
2291 { _T("^foo"), _T("foobar"), TRUE
},
2292 { _T("^foo"), _T("barfoo"), FALSE
},
2293 { _T("bar$"), _T("barbar"), TRUE
},
2294 { _T("bar$"), _T("barbar "), FALSE
},
2297 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2299 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2301 wxRegEx
re(data
.pattern
);
2302 bool ok
= re
.Matches(data
.text
);
2304 wxPrintf(_T("'%s' %s %s (%s)\n"),
2306 ok ?
_T("matches") : _T("doesn't match"),
2308 ok
== data
.correct ?
_T("ok") : _T("ERROR"));
2312 static void TestRegExSubmatch()
2314 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2316 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2317 if ( !re
.IsValid() )
2319 wxPuts(_T("ERROR: compilation failed."));
2323 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2325 if ( !re
.Matches(text
) )
2327 wxPuts(_T("ERROR: match expected."));
2331 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2333 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2334 re
.GetMatch(text
, 3).c_str(),
2335 re
.GetMatch(text
, 2).c_str(),
2336 re
.GetMatch(text
, 4).c_str(),
2337 re
.GetMatch(text
, 1).c_str());
2341 static void TestRegExReplacement()
2343 wxPuts(_T("*** Testing RE replacement ***"));
2345 static struct RegExReplTestData
2349 const wxChar
*result
;
2351 } regExReplTestData
[] =
2353 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2354 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2355 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2356 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2357 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2358 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2359 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2362 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2363 wxRegEx
re(pattern
);
2365 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2367 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2369 const RegExReplTestData
& data
= regExReplTestData
[n
];
2371 wxString text
= data
.text
;
2372 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2374 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2375 data
.text
, data
.repl
,
2376 nRepl
, nRepl
== 1 ?
_T("") : _T("es"),
2378 if ( text
== data
.result
&& nRepl
== data
.count
)
2384 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2385 data
.count
, data
.result
);
2390 static void TestRegExInteractive()
2392 wxPuts(_T("*** Testing RE interactively ***"));
2396 wxChar pattern
[128];
2397 wxPrintf(_T("\nEnter a pattern: "));
2398 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2401 // kill the last '\n'
2402 pattern
[wxStrlen(pattern
) - 1] = 0;
2405 if ( !re
.Compile(pattern
) )
2413 wxPrintf(_T("Enter text to match: "));
2414 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
2417 // kill the last '\n'
2418 text
[wxStrlen(text
) - 1] = 0;
2420 if ( !re
.Matches(text
) )
2422 wxPrintf(_T("No match.\n"));
2426 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
2429 for ( size_t n
= 1; ; n
++ )
2431 if ( !re
.GetMatch(&start
, &len
, n
) )
2436 wxPrintf(_T("Subexpr %u matched '%s'\n"),
2437 n
, wxString(text
+ start
, len
).c_str());
2444 #endif // TEST_REGEX
2446 // ----------------------------------------------------------------------------
2448 // ----------------------------------------------------------------------------
2458 static void TestDbOpen()
2466 // ----------------------------------------------------------------------------
2468 // ----------------------------------------------------------------------------
2471 NB: this stuff was taken from the glibc test suite and modified to build
2472 in wxWindows: if I read the copyright below properly, this shouldn't
2478 #ifdef wxTEST_PRINTF
2479 // use our functions from wxchar.cpp
2483 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
2484 // in the tests below
2485 int wxPrintf( const wxChar
*format
, ... );
2486 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
2491 static void rfg1 (void);
2492 static void rfg2 (void);
2496 fmtchk (const wxChar
*fmt
)
2498 (void) wxPrintf(_T("%s:\t`"), fmt
);
2499 (void) wxPrintf(fmt
, 0x12);
2500 (void) wxPrintf(_T("'\n"));
2504 fmtst1chk (const wxChar
*fmt
)
2506 (void) wxPrintf(_T("%s:\t`"), fmt
);
2507 (void) wxPrintf(fmt
, 4, 0x12);
2508 (void) wxPrintf(_T("'\n"));
2512 fmtst2chk (const wxChar
*fmt
)
2514 (void) wxPrintf(_T("%s:\t`"), fmt
);
2515 (void) wxPrintf(fmt
, 4, 4, 0x12);
2516 (void) wxPrintf(_T("'\n"));
2519 /* This page is covered by the following copyright: */
2521 /* (C) Copyright C E Chew
2523 * Feel free to copy, use and distribute this software provided:
2525 * 1. you do not pretend that you wrote it
2526 * 2. you leave this copyright notice intact.
2530 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
2537 /* Formatted Output Test
2539 * This exercises the output formatting code.
2547 wxChar
*prefix
= buf
;
2550 wxPuts(_T("\nFormatted output test"));
2551 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
2552 wxStrcpy(prefix
, _T("%"));
2553 for (i
= 0; i
< 2; i
++) {
2554 for (j
= 0; j
< 2; j
++) {
2555 for (k
= 0; k
< 2; k
++) {
2556 for (l
= 0; l
< 2; l
++) {
2557 wxStrcpy(prefix
, _T("%"));
2558 if (i
== 0) wxStrcat(prefix
, _T("-"));
2559 if (j
== 0) wxStrcat(prefix
, _T("+"));
2560 if (k
== 0) wxStrcat(prefix
, _T("#"));
2561 if (l
== 0) wxStrcat(prefix
, _T("0"));
2562 wxPrintf(_T("%5s |"), prefix
);
2563 wxStrcpy(tp
, prefix
);
2564 wxStrcat(tp
, _T("6d |"));
2566 wxStrcpy(tp
, prefix
);
2567 wxStrcat(tp
, _T("6o |"));
2569 wxStrcpy(tp
, prefix
);
2570 wxStrcat(tp
, _T("6x |"));
2572 wxStrcpy(tp
, prefix
);
2573 wxStrcat(tp
, _T("6X |"));
2575 wxStrcpy(tp
, prefix
);
2576 wxStrcat(tp
, _T("6u |"));
2583 wxPrintf(_T("%10s\n"), (wxChar
*) NULL
);
2584 wxPrintf(_T("%-10s\n"), (wxChar
*) NULL
);
2587 static void TestPrintf()
2589 static wxChar shortstr
[] = _T("Hi, Z.");
2590 static wxChar longstr
[] = "Good morning, Doctor Chandra. This is Hal. \
2591 I am ready for my first lesson today.";
2596 fmtchk(_T("%4.4x"));
2597 fmtchk(_T("%04.4x"));
2598 fmtchk(_T("%4.3x"));
2599 fmtchk(_T("%04.3x"));
2601 fmtst1chk(_T("%.*x"));
2602 fmtst1chk(_T("%0*x"));
2603 fmtst2chk(_T("%*.*x"));
2604 fmtst2chk(_T("%0*.*x"));
2606 wxPrintf(_T("bad format:\t\"%b\"\n"));
2607 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
2609 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
2610 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
2611 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
2612 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
2613 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
2614 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
2615 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
2616 wxPrintf(_T("left-adjusted ZLDN:\t\"%-010ld\"\n"), -123456);
2617 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
2618 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
2620 wxPrintf(_T("zero-padded string:\t\"%010s\"\n"), shortstr
);
2621 wxPrintf(_T("left-adjusted Z string:\t\"%-010s\"\n"), shortstr
);
2622 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
2623 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
2624 wxPrintf(_T("null string:\t\"%s\"\n"), (wxChar
*)NULL
);
2625 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
2627 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
2628 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
2629 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
2630 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
2631 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
2632 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
2633 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
2634 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
2635 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
2636 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
2637 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
2638 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
2640 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
2641 wxPrintf (_T(" %6.5f\n"), .1);
2642 wxPrintf (_T("x%5.4fx\n"), .5);
2644 wxPrintf (_T("%#03x\n"), 1);
2646 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
2652 while (niter
-- != 0)
2653 wxPrintf (_T("%.17e\n"), d
/ 2);
2657 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
2659 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
2660 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
2661 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
2662 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
2663 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
2664 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
2665 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
2666 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
2667 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
2668 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
2673 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
2675 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
2676 rc
, WXSIZEOF(buf
), buf
);
2679 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
2680 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
2686 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
2687 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
2688 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
2689 wxPrintf (_T("%g should be 123.456\n"), 123.456);
2690 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
2691 wxPrintf (_T("%g should be 10\n"), 10.0);
2692 wxPrintf (_T("%g should be 0.02\n"), 0.02);
2696 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
2702 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
2704 result
|= wxStrcmp (buf
,
2705 _T("onetwo three "));
2707 wxPuts (result
!= 0 ?
_T("Test failed!") : _T("Test ok."));
2713 wxSprintf (buf
, _T("%07Lo"), 040000000000ll);
2714 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
2716 if (wxStrcmp (buf
, _T("40000000000")) != 0)
2719 wxPuts (_T("\tFAILED"));
2724 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
2725 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
2727 wxPuts (_T("--- Should be no further output. ---"));
2736 memset (bytes
, '\xff', sizeof bytes
);
2737 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
2738 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
2739 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
2741 wxPuts (_T("%hhn overwrite more bytes"));
2746 wxPuts (_T("%hhn wrote incorrect value"));
2758 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
2759 if (wxStrcmp (buf
, _T(" ")) != 0)
2760 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
2761 wxSprintf (buf
, _T("%5.f"), 33.3);
2762 if (wxStrcmp (buf
, _T(" 33")) != 0)
2763 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
2764 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
2765 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
2766 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
2767 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
2768 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
2769 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
2770 wxSprintf (buf
, _T("%.g"), 33.3);
2771 if (wxStrcmp (buf
, _T("3e+01")) != 0)
2772 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
2773 wxSprintf (buf
, _T("%.G"), 33.3);
2774 if (wxStrcmp (buf
, _T("3E+01")) != 0)
2775 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
2785 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
2786 if (wxStrcmp (buf
, _T("3")) != 0)
2787 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2789 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
2790 if (wxStrcmp (buf
, _T("3")) != 0)
2791 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2793 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
2794 if (wxStrcmp (buf
, _T(" 3")) != 0)
2795 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
2797 wxSprintf (buf
, _T("%04.*o"), prec
, 33);
2798 if (wxStrcmp (buf
, _T(" 041")) != 0)
2799 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
2801 wxSprintf (buf
, _T("%09.*u"), prec
, 33);
2802 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
2803 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
2805 wxSprintf (buf
, _T("%04.*x"), prec
, 33);
2806 if (wxStrcmp (buf
, _T(" 021")) != 0)
2807 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2809 wxSprintf (buf
, _T("%04.*X"), prec
, 33);
2810 if (wxStrcmp (buf
, _T(" 021")) != 0)
2811 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2814 #endif // TEST_PRINTF
2816 // ----------------------------------------------------------------------------
2817 // registry and related stuff
2818 // ----------------------------------------------------------------------------
2820 // this is for MSW only
2823 #undef TEST_REGISTRY
2828 #include "wx/confbase.h"
2829 #include "wx/msw/regconf.h"
2831 static void TestRegConfWrite()
2833 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2834 regconf
.Write(_T("Hello"), wxString(_T("world")));
2837 #endif // TEST_REGCONF
2839 #ifdef TEST_REGISTRY
2841 #include "wx/msw/registry.h"
2843 // I chose this one because I liked its name, but it probably only exists under
2845 static const wxChar
*TESTKEY
=
2846 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2848 static void TestRegistryRead()
2850 wxPuts(_T("*** testing registry reading ***"));
2852 wxRegKey
key(TESTKEY
);
2853 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2856 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2861 size_t nSubKeys
, nValues
;
2862 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2864 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2867 wxPrintf(_T("Enumerating values:\n"));
2871 bool cont
= key
.GetFirstValue(value
, dummy
);
2874 wxPrintf(_T("Value '%s': type "), value
.c_str());
2875 switch ( key
.GetValueType(value
) )
2877 case wxRegKey
::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2878 case wxRegKey
::Type_String
: wxPrintf(_T("SZ")); break;
2879 case wxRegKey
::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2880 case wxRegKey
::Type_Binary
: wxPrintf(_T("BINARY")); break;
2881 case wxRegKey
::Type_Dword
: wxPrintf(_T("DWORD")); break;
2882 case wxRegKey
::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2883 default: wxPrintf(_T("other (unknown)")); break;
2886 wxPrintf(_T(", value = "));
2887 if ( key
.IsNumericValue(value
) )
2890 key
.QueryValue(value
, &val
);
2891 wxPrintf(_T("%ld"), val
);
2896 key
.QueryValue(value
, val
);
2897 wxPrintf(_T("'%s'"), val
.c_str());
2899 key
.QueryRawValue(value
, val
);
2900 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2905 cont
= key
.GetNextValue(value
, dummy
);
2909 static void TestRegistryAssociation()
2912 The second call to deleteself genertaes an error message, with a
2913 messagebox saying .flo is crucial to system operation, while the .ddf
2914 call also fails, but with no error message
2919 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2921 key
= "ddxf_auto_file" ;
2922 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2924 key
= "ddxf_auto_file" ;
2925 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2928 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2930 key
= "program \"%1\"" ;
2932 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2934 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2936 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2938 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2942 #endif // TEST_REGISTRY
2944 // ----------------------------------------------------------------------------
2946 // ----------------------------------------------------------------------------
2950 #include "wx/socket.h"
2951 #include "wx/protocol/protocol.h"
2952 #include "wx/protocol/http.h"
2954 static void TestSocketServer()
2956 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2958 static const int PORT
= 3000;
2963 wxSocketServer
*server
= new wxSocketServer(addr
);
2964 if ( !server
->Ok() )
2966 wxPuts(_T("ERROR: failed to bind"));
2973 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2975 wxSocketBase
*socket
= server
->Accept();
2978 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2982 wxPuts(_T("Server: got a client."));
2984 server
->SetTimeout(60); // 1 min
2986 while ( socket
->IsConnected() )
2989 wxChar ch
= _T('\0');
2992 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2994 // don't log error if the client just close the connection
2995 if ( socket
->IsConnected() )
2997 wxPuts(_T("ERROR: in wxSocket::Read."));
3017 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
3018 if ( s
== _T("bye") )
3025 socket
->Write(s
.MakeUpper().c_str(), s
.length());
3026 socket
->Write("\r\n", 2);
3027 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
3030 wxPuts(_T("Server: lost a client."));
3035 // same as "delete server" but is consistent with GUI programs
3039 static void TestSocketClient()
3041 wxPuts(_T("*** Testing wxSocketClient ***\n"));
3043 static const wxChar
*hostname
= _T("www.wxwindows.org");
3046 addr
.Hostname(hostname
);
3049 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
3051 wxSocketClient client
;
3052 if ( !client
.Connect(addr
) )
3054 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
3058 wxPrintf(_T("--- Connected to %s:%u...\n"),
3059 addr
.Hostname().c_str(), addr
.Service());
3063 // could use simply "GET" here I suppose
3065 wxString
::Format(_T("GET http://%s/\r\n"), hostname
);
3066 client
.Write(cmdGet
, cmdGet
.length());
3067 wxPrintf(_T("--- Sent command '%s' to the server\n"),
3068 MakePrintable(cmdGet
).c_str());
3069 client
.Read(buf
, WXSIZEOF(buf
));
3070 wxPrintf(_T("--- Server replied:\n%s"), buf
);
3074 #endif // TEST_SOCKETS
3076 // ----------------------------------------------------------------------------
3078 // ----------------------------------------------------------------------------
3082 #include "wx/protocol/ftp.h"
3086 #define FTP_ANONYMOUS
3088 #ifdef FTP_ANONYMOUS
3089 static const wxChar
*directory
= _T("/pub");
3090 static const wxChar
*filename
= _T("welcome.msg");
3092 static const wxChar
*directory
= _T("/etc");
3093 static const wxChar
*filename
= _T("issue");
3096 static bool TestFtpConnect()
3098 wxPuts(_T("*** Testing FTP connect ***"));
3100 #ifdef FTP_ANONYMOUS
3101 static const wxChar
*hostname
= _T("ftp.wxwindows.org");
3103 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
3104 #else // !FTP_ANONYMOUS
3105 static const wxChar
*hostname
= "localhost";
3108 wxFgets(user
, WXSIZEOF(user
), stdin
);
3109 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
3112 wxChar password
[256];
3113 wxPrintf(_T("Password for %s: "), password
);
3114 wxFgets(password
, WXSIZEOF(password
), stdin
);
3115 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
3116 ftp
.SetPassword(password
);
3118 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
3119 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
3121 if ( !ftp
.Connect(hostname
) )
3123 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
3129 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
3130 hostname
, ftp
.Pwd().c_str());
3136 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
3137 static void TestFtpWuFtpd()
3140 static const wxChar
*hostname
= _T("ftp.eudora.com");
3141 if ( !ftp
.Connect(hostname
) )
3143 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
3147 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
3148 wxInputStream
*in
= ftp
.GetInputStream(filename
);
3151 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
3155 size_t size
= in
->StreamSize();
3156 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
3158 wxChar
*data
= new wxChar
[size
];
3159 if ( !in
->Read(data
, size
) )
3161 wxPuts(_T("ERROR: read error"));
3165 wxPrintf(_T("Successfully retrieved the file.\n"));
3174 static void TestFtpList()
3176 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
3179 if ( !ftp
.ChDir(directory
) )
3181 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
3184 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
3186 // test NLIST and LIST
3187 wxArrayString files
;
3188 if ( !ftp
.GetFilesList(files
) )
3190 wxPuts(_T("ERROR: failed to get NLIST of files"));
3194 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
3195 size_t count
= files
.GetCount();
3196 for ( size_t n
= 0; n
< count
; n
++ )
3198 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3200 wxPuts(_T("End of the file list"));
3203 if ( !ftp
.GetDirList(files
) )
3205 wxPuts(_T("ERROR: failed to get LIST of files"));
3209 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
3210 size_t count
= files
.GetCount();
3211 for ( size_t n
= 0; n
< count
; n
++ )
3213 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3215 wxPuts(_T("End of the file list"));
3218 if ( !ftp
.ChDir(_T("..")) )
3220 wxPuts(_T("ERROR: failed to cd to .."));
3223 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
3226 static void TestFtpDownload()
3228 wxPuts(_T("*** Testing wxFTP download ***\n"));
3231 wxInputStream
*in
= ftp
.GetInputStream(filename
);
3234 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
3238 size_t size
= in
->StreamSize();
3239 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
3242 wxChar
*data
= new wxChar
[size
];
3243 if ( !in
->Read(data
, size
) )
3245 wxPuts(_T("ERROR: read error"));
3249 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
3257 static void TestFtpFileSize()
3259 wxPuts(_T("*** Testing FTP SIZE command ***"));
3261 if ( !ftp
.ChDir(directory
) )
3263 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
3266 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
3268 if ( ftp
.FileExists(filename
) )
3270 int size
= ftp
.GetFileSize(filename
);
3272 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
3274 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
3278 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
3282 static void TestFtpMisc()
3284 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
3286 if ( ftp
.SendCommand("STAT") != '2' )
3288 wxPuts(_T("ERROR: STAT failed"));
3292 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
3295 if ( ftp
.SendCommand("HELP SITE") != '2' )
3297 wxPuts(_T("ERROR: HELP SITE failed"));
3301 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
3302 ftp
.GetLastResult().c_str());
3306 static void TestFtpInteractive()
3308 wxPuts(_T("\n*** Interactive wxFTP test ***"));
3314 wxPrintf(_T("Enter FTP command: "));
3315 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3318 // kill the last '\n'
3319 buf
[wxStrlen(buf
) - 1] = 0;
3321 // special handling of LIST and NLST as they require data connection
3322 wxString
start(buf
, 4);
3324 if ( start
== "LIST" || start
== "NLST" )
3327 if ( wxStrlen(buf
) > 4 )
3330 wxArrayString files
;
3331 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
3333 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
3337 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
3338 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
3339 size_t count
= files
.GetCount();
3340 for ( size_t n
= 0; n
< count
; n
++ )
3342 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3344 wxPuts(_T("--- End of the file list"));
3349 wxChar ch
= ftp
.SendCommand(buf
);
3350 wxPrintf(_T("Command %s"), ch ?
_T("succeeded") : _T("failed"));
3353 wxPrintf(_T(" (return code %c)"), ch
);
3356 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
3360 wxPuts(_T("\n*** done ***"));
3363 static void TestFtpUpload()
3365 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
3368 static const wxChar
*file1
= _T("test1");
3369 static const wxChar
*file2
= _T("test2");
3370 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
3373 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
3374 out
->Write("First hello", 11);
3378 // send a command to check the remote file
3379 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
3381 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
3385 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
3386 file1
, ftp
.GetLastResult().c_str());
3389 out
= ftp
.GetOutputStream(file2
);
3392 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
3393 out
->Write("Second hello", 12);
3400 // ----------------------------------------------------------------------------
3402 // ----------------------------------------------------------------------------
3406 #include "wx/wfstream.h"
3407 #include "wx/mstream.h"
3409 static void TestFileStream()
3411 wxPuts(_T("*** Testing wxFileInputStream ***"));
3413 static const wxChar
*filename
= _T("testdata.fs");
3415 wxFileOutputStream
fsOut(filename
);
3416 fsOut
.Write("foo", 3);
3419 wxFileInputStream
fsIn(filename
);
3420 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
3421 while ( !fsIn
.Eof() )
3423 putchar(fsIn
.GetC());
3426 if ( !wxRemoveFile(filename
) )
3428 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
);
3431 wxPuts(_T("\n*** wxFileInputStream test done ***"));
3434 static void TestMemoryStream()
3436 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
3438 wxMemoryOutputStream memOutStream
;
3439 wxPrintf(_T("Initially out stream offset: %lu\n"),
3440 (unsigned long)memOutStream
.TellO());
3442 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
3444 memOutStream
.PutC(*p
);
3447 wxPrintf(_T("Final out stream offset: %lu\n"),
3448 (unsigned long)memOutStream
.TellO());
3450 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
3453 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
3455 wxMemoryInputStream
memInpStream(buf
, len
);
3456 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3457 while ( !memInpStream
.Eof() )
3459 putchar(memInpStream
.GetC());
3462 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
3465 #endif // TEST_STREAMS
3467 // ----------------------------------------------------------------------------
3469 // ----------------------------------------------------------------------------
3473 #include "wx/timer.h"
3474 #include "wx/utils.h"
3476 static void TestStopWatch()
3478 wxPuts(_T("*** Testing wxStopWatch ***\n"));
3482 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
3485 wxPrintf(_T("\t%ldms\n"), sw
.Time());
3487 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
3491 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3494 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
3497 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3500 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
3503 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3506 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
3507 for ( size_t n
= 0; n
< 70; n
++ )
3511 for ( size_t m
= 0; m
< 100000; m
++ )
3513 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3515 wxPuts(_T("\ntime is negative - ERROR!"));
3523 wxPuts(_T(", ok."));
3526 #endif // TEST_TIMER
3528 // ----------------------------------------------------------------------------
3530 // ----------------------------------------------------------------------------
3534 #include "wx/vcard.h"
3536 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3539 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3542 wxPrintf(_T("%s%s"),
3543 wxString(_T('\t'), level
).c_str(),
3544 vcObj
->GetName().c_str());
3547 switch ( vcObj
->GetType() )
3549 case wxVCardObject
::String
:
3550 case wxVCardObject
::UString
:
3553 vcObj
->GetValue(&val
);
3554 value
<< _T('"') << val
<< _T('"');
3558 case wxVCardObject
::Int
:
3561 vcObj
->GetValue(&i
);
3562 value
.Printf(_T("%u"), i
);
3566 case wxVCardObject
::Long
:
3569 vcObj
->GetValue(&l
);
3570 value
.Printf(_T("%lu"), l
);
3574 case wxVCardObject
::None
:
3577 case wxVCardObject
::Object
:
3578 value
= _T("<node>");
3582 value
= _T("<unknown value type>");
3586 wxPrintf(_T(" = %s"), value
.c_str());
3589 DumpVObject(level
+ 1, *vcObj
);
3592 vcObj
= vcard
.GetNextProp(&cookie
);
3596 static void DumpVCardAddresses(const wxVCard
& vcard
)
3598 wxPuts(_T("\nShowing all addresses from vCard:\n"));
3602 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3606 int flags
= addr
->GetFlags();
3607 if ( flags
& wxVCardAddress
::Domestic
)
3609 flagsStr
<< _T("domestic ");
3611 if ( flags
& wxVCardAddress
::Intl
)
3613 flagsStr
<< _T("international ");
3615 if ( flags
& wxVCardAddress
::Postal
)
3617 flagsStr
<< _T("postal ");
3619 if ( flags
& wxVCardAddress
::Parcel
)
3621 flagsStr
<< _T("parcel ");
3623 if ( flags
& wxVCardAddress
::Home
)
3625 flagsStr
<< _T("home ");
3627 if ( flags
& wxVCardAddress
::Work
)
3629 flagsStr
<< _T("work ");
3632 wxPrintf(_T("Address %u:\n")
3634 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3637 addr
->GetPostOffice().c_str(),
3638 addr
->GetExtAddress().c_str(),
3639 addr
->GetStreet().c_str(),
3640 addr
->GetLocality().c_str(),
3641 addr
->GetRegion().c_str(),
3642 addr
->GetPostalCode().c_str(),
3643 addr
->GetCountry().c_str()
3647 addr
= vcard
.GetNextAddress(&cookie
);
3651 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3653 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
3657 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3661 int flags
= phone
->GetFlags();
3662 if ( flags
& wxVCardPhoneNumber
::Voice
)
3664 flagsStr
<< _T("voice ");
3666 if ( flags
& wxVCardPhoneNumber
::Fax
)
3668 flagsStr
<< _T("fax ");
3670 if ( flags
& wxVCardPhoneNumber
::Cellular
)
3672 flagsStr
<< _T("cellular ");
3674 if ( flags
& wxVCardPhoneNumber
::Modem
)
3676 flagsStr
<< _T("modem ");
3678 if ( flags
& wxVCardPhoneNumber
::Home
)
3680 flagsStr
<< _T("home ");
3682 if ( flags
& wxVCardPhoneNumber
::Work
)
3684 flagsStr
<< _T("work ");
3687 wxPrintf(_T("Phone number %u:\n")
3692 phone
->GetNumber().c_str()
3696 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3700 static void TestVCardRead()
3702 wxPuts(_T("*** Testing wxVCard reading ***\n"));
3704 wxVCard
vcard(_T("vcard.vcf"));
3705 if ( !vcard
.IsOk() )
3707 wxPuts(_T("ERROR: couldn't load vCard."));
3711 // read individual vCard properties
3712 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3716 vcObj
->GetValue(&value
);
3721 value
= _T("<none>");
3724 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
3727 if ( !vcard
.GetFullName(&value
) )
3729 value
= _T("<none>");
3732 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
3734 // now show how to deal with multiply occuring properties
3735 DumpVCardAddresses(vcard
);
3736 DumpVCardPhoneNumbers(vcard
);
3738 // and finally show all
3739 wxPuts(_T("\nNow dumping the entire vCard:\n")
3740 "-----------------------------\n");
3742 DumpVObject(0, vcard
);
3746 static void TestVCardWrite()
3748 wxPuts(_T("*** Testing wxVCard writing ***\n"));
3751 if ( !vcard
.IsOk() )
3753 wxPuts(_T("ERROR: couldn't create vCard."));
3758 vcard
.SetName("Zeitlin", "Vadim");
3759 vcard
.SetFullName("Vadim Zeitlin");
3760 vcard
.SetOrganization("wxWindows", "R&D");
3762 // just dump the vCard back
3763 wxPuts(_T("Entire vCard follows:\n"));
3764 wxPuts(vcard
.Write());
3768 #endif // TEST_VCARD
3770 // ----------------------------------------------------------------------------
3772 // ----------------------------------------------------------------------------
3774 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3780 #include "wx/volume.h"
3782 static const wxChar
*volumeKinds
[] =
3788 _T("network volume"),
3792 static void TestFSVolume()
3794 wxPuts(_T("*** Testing wxFSVolume class ***"));
3796 wxArrayString volumes
= wxFSVolume
::GetVolumes();
3797 size_t count
= volumes
.GetCount();
3801 wxPuts(_T("ERROR: no mounted volumes?"));
3805 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3807 for ( size_t n
= 0; n
< count
; n
++ )
3809 wxFSVolume
vol(volumes
[n
]);
3812 wxPuts(_T("ERROR: couldn't create volume"));
3816 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3818 vol
.GetDisplayName().c_str(),
3819 vol
.GetName().c_str(),
3820 volumeKinds
[vol
.GetKind()],
3821 vol
.IsWritable() ?
_T("rw") : _T("ro"),
3822 vol
.GetFlags() & wxFS_VOL_REMOVABLE ?
_T("removable")
3827 #endif // TEST_VOLUME
3829 // ----------------------------------------------------------------------------
3830 // wide char and Unicode support
3831 // ----------------------------------------------------------------------------
3835 static void TestUnicodeToFromAscii()
3837 wxPuts(_T("Testing wxString::To/FromAscii()\n"));
3839 static const char *msg
= "Hello, world!";
3840 wxString s
= wxString
::FromAscii(msg
);
3842 wxPrintf(_T("Message in Unicode: %s\n"), s
.c_str());
3843 printf("Message in ASCII: %s\n", (const char *)s
.ToAscii());
3845 wxPutchar(_T('\n'));
3848 #endif // TEST_UNICODE
3852 #include "wx/strconv.h"
3853 #include "wx/fontenc.h"
3854 #include "wx/encconv.h"
3855 #include "wx/buffer.h"
3857 static const unsigned char textInUtf8_
[] =
3859 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3860 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3861 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3862 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3863 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3864 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3865 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3868 #define textInUtf8 ((const char *)textInUtf8_)
3870 static void TestUtf8()
3872 wxPuts(_T("*** Testing UTF8 support ***\n"));
3876 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3878 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3882 wxCSConv
conv(_T("koi8-r"));
3883 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3885 wxPuts(_T("ERROR: conversion to KOI8-R failed."));
3889 wxPrintf(_T("The resulting string (in KOI8-R): %s\n"), buf
);
3893 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3895 wxPuts(_T("ERROR: conversion to UTF-8 failed."));
3899 wxPrintf(_T("The string in UTF-8: %s\n"), buf
);
3905 static void TestEncodingConverter()
3907 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3909 // using wxEncodingConverter should give the same result as above
3912 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3914 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3918 wxEncodingConverter ec
;
3919 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3920 ec
.Convert(wbuf
, buf
);
3921 wxPrintf(_T("The same string obtained using wxEC: %s\n"), buf
);
3927 #endif // TEST_WCHAR
3929 // ----------------------------------------------------------------------------
3931 // ----------------------------------------------------------------------------
3935 #include "wx/filesys.h"
3936 #include "wx/fs_zip.h"
3937 #include "wx/zipstrm.h"
3939 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3941 static void TestZipStreamRead()
3943 wxPuts(_T("*** Testing ZIP reading ***\n"));
3945 static const wxChar
*filename
= _T("foo");
3946 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3947 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3949 wxPrintf(_T("Dumping the file '%s':\n"), filename
);
3950 while ( !istr
.Eof() )
3952 putchar(istr
.GetC());
3956 wxPuts(_T("\n----- done ------"));
3959 static void DumpZipDirectory(wxFileSystem
& fs
,
3960 const wxString
& dir
,
3961 const wxString
& indent
)
3963 wxString prefix
= wxString
::Format(_T("%s#zip:%s"),
3964 TESTFILE_ZIP
, dir
.c_str());
3965 wxString wildcard
= prefix
+ _T("/*");
3967 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3968 while ( !dirname
.empty() )
3970 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3972 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3977 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3979 DumpZipDirectory(fs
, dirname
,
3980 indent
+ wxString(_T(' '), 4));
3982 dirname
= fs
.FindNext();
3985 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3986 while ( !filename
.empty() )
3988 if ( !filename
.StartsWith(prefix
, &filename
) )
3990 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3995 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3997 filename
= fs
.FindNext();
4001 static void TestZipFileSystem()
4003 wxPuts(_T("*** Testing ZIP file system ***\n"));
4005 wxFileSystem
::AddHandler(new wxZipFSHandler
);
4007 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
4009 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
4014 // ----------------------------------------------------------------------------
4016 // ----------------------------------------------------------------------------
4020 #include "wx/zstream.h"
4021 #include "wx/wfstream.h"
4023 static const wxChar
*FILENAME_GZ
= _T("test.gz");
4024 static const wxChar
*TEST_DATA
= _T("hello and hello and hello and hello and hello");
4026 static void TestZlibStreamWrite()
4028 wxPuts(_T("*** Testing Zlib stream reading ***\n"));
4030 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
4031 wxZlibOutputStream
ostr(fileOutStream
);
4032 wxPrintf(_T("Compressing the test string... "));
4033 ostr
.Write(TEST_DATA
, wxStrlen(TEST_DATA
) + 1);
4036 wxPuts(_T("(ERROR: failed)"));
4043 wxPuts(_T("\n----- done ------"));
4046 static void TestZlibStreamRead()
4048 wxPuts(_T("*** Testing Zlib stream reading ***\n"));
4050 wxFileInputStream
fileInStream(FILENAME_GZ
);
4051 wxZlibInputStream
istr(fileInStream
);
4052 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
4054 wxPuts(_T("Dumping the file:"));
4055 while ( !istr
.Eof() )
4057 putchar(istr
.GetC());
4061 wxPuts(_T("\n----- done ------"));
4066 // ----------------------------------------------------------------------------
4068 // ----------------------------------------------------------------------------
4070 #ifdef TEST_DATETIME
4074 #include "wx/date.h"
4075 #include "wx/datetime.h"
4080 wxDateTime
::wxDateTime_t day
;
4081 wxDateTime
::Month month
;
4083 wxDateTime
::wxDateTime_t hour
, min
, sec
;
4085 wxDateTime
::WeekDay wday
;
4086 time_t gmticks
, ticks
;
4088 void Init(const wxDateTime
::Tm
& tm
)
4097 gmticks
= ticks
= -1;
4100 wxDateTime
DT() const
4101 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
4103 bool SameDay(const wxDateTime
::Tm
& tm
) const
4105 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
4108 wxString
Format() const
4111 s
.Printf(_T("%02d:%02d:%02d %10s %02d, %4d%s"),
4113 wxDateTime
::GetMonthName(month
).c_str(),
4115 abs(wxDateTime
::ConvertYearToBC(year
)),
4116 year
> 0 ?
_T("AD") : _T("BC"));
4120 wxString
FormatDate() const
4123 s
.Printf(_T("%02d-%s-%4d%s"),
4125 wxDateTime
::GetMonthName(month
, wxDateTime
::Name_Abbr
).c_str(),
4126 abs(wxDateTime
::ConvertYearToBC(year
)),
4127 year
> 0 ?
_T("AD") : _T("BC"));
4132 static const Date testDates
[] =
4134 { 1, wxDateTime
::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime
::Thu
, 0, -3600 },
4135 { 7, wxDateTime
::Feb
, 2036, 00, 00, 00, 2464730.5, wxDateTime
::Thu
, -1, -1 },
4136 { 8, wxDateTime
::Feb
, 2036, 00, 00, 00, 2464731.5, wxDateTime
::Fri
, -1, -1 },
4137 { 1, wxDateTime
::Jan
, 2037, 00, 00, 00, 2465059.5, wxDateTime
::Thu
, -1, -1 },
4138 { 1, wxDateTime
::Jan
, 2038, 00, 00, 00, 2465424.5, wxDateTime
::Fri
, -1, -1 },
4139 { 21, wxDateTime
::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime
::Mon
, -1, -1 },
4140 { 29, wxDateTime
::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime
::Sat
, 202219200, 202212000 },
4141 { 29, wxDateTime
::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime
::Sun
, 194400000, 194396400 },
4142 { 1, wxDateTime
::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime
::Mon
, -1, -1 },
4143 { 1, wxDateTime
::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime
::Mon
, -1, -1 },
4144 { 15, wxDateTime
::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime
::Fri
, -1, -1 },
4145 { 4, wxDateTime
::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime
::Mon
, -1, -1 },
4146 { 1, wxDateTime
::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime
::Thu
, -1, -1 },
4147 { 1, wxDateTime
::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime
::Mon
, -1, -1 },
4148 { 31, wxDateTime
::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime
::Sun
, -1, -1 },
4149 { 1, wxDateTime
::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime
::Sat
, -1, -1 },
4150 { 12, wxDateTime
::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime
::Fri
, -1, -1 },
4151 { 12, wxDateTime
::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime
::Sat
, -1, -1 },
4152 { 24, wxDateTime
::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime
::Mon
, -1, -1 },
4155 // this test miscellaneous static wxDateTime functions
4156 static void TestTimeStatic()
4158 wxPuts(_T("\n*** wxDateTime static methods test ***"));
4160 // some info about the current date
4161 int year
= wxDateTime
::GetCurrentYear();
4162 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
4164 wxDateTime
::IsLeapYear(year
) ?
"" : "not ",
4165 wxDateTime
::GetNumberOfDays(year
));
4167 wxDateTime
::Month month
= wxDateTime
::GetCurrentMonth();
4168 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
4169 wxDateTime
::GetMonthName(month
, wxDateTime
::Name_Abbr
).c_str(),
4170 wxDateTime
::GetMonthName(month
).c_str(),
4171 wxDateTime
::GetNumberOfDays(month
));
4174 static const size_t nYears
= 5;
4175 static const size_t years
[2][nYears
] =
4177 // first line: the years to test
4178 { 1990, 1976, 2000, 2030, 1984, },
4180 // second line: TRUE if leap, FALSE otherwise
4181 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
4184 for ( size_t n
= 0; n
< nYears
; n
++ )
4186 int year
= years
[0][n
];
4187 bool should
= years
[1][n
] != 0,
4188 is
= wxDateTime
::IsLeapYear(year
);
4190 wxPrintf(_T("Year %d is %sa leap year (%s)\n"),
4193 should
== is ?
"ok" : "ERROR");
4195 wxASSERT( should
== wxDateTime
::IsLeapYear(year
) );
4199 // test constructing wxDateTime objects
4200 static void TestTimeSet()
4202 wxPuts(_T("\n*** wxDateTime construction test ***"));
4204 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4206 const Date
& d1
= testDates
[n
];
4207 wxDateTime dt
= d1
.DT();
4210 d2
.Init(dt
.GetTm());
4212 wxString s1
= d1
.Format(),
4215 wxPrintf(_T("Date: %s == %s (%s)\n"),
4216 s1
.c_str(), s2
.c_str(),
4217 s1
== s2 ?
_T("ok") : _T("ERROR"));
4221 // test time zones stuff
4222 static void TestTimeZones()
4224 wxPuts(_T("\n*** wxDateTime timezone test ***"));
4226 wxDateTime now
= wxDateTime
::Now();
4228 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime
::GMT0
).c_str());
4229 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime
::GMT0
).c_str());
4230 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime
::EST
).c_str());
4231 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime
::CET
).c_str());
4232 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime
::MSK
).c_str());
4233 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime
::EST
).c_str());
4235 wxDateTime
::Tm tm
= now
.GetTm();
4236 if ( wxDateTime(tm
) != now
)
4238 wxPrintf(_T("ERROR: got %s instead of %s\n"),
4239 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
4243 // test some minimal support for the dates outside the standard range
4244 static void TestTimeRange()
4246 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
4248 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
4250 wxPrintf(_T("Unix epoch:\t%s\n"),
4251 wxDateTime(2440587.5).Format(fmt
).c_str());
4252 wxPrintf(_T("Feb 29, 0: \t%s\n"),
4253 wxDateTime(29, wxDateTime
::Feb
, 0).Format(fmt
).c_str());
4254 wxPrintf(_T("JDN 0: \t%s\n"),
4255 wxDateTime(0.0).Format(fmt
).c_str());
4256 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
4257 wxDateTime(1, wxDateTime
::Jan
, 1).Format(fmt
).c_str());
4258 wxPrintf(_T("May 29, 2099:\t%s\n"),
4259 wxDateTime(29, wxDateTime
::May
, 2099).Format(fmt
).c_str());
4262 static void TestTimeTicks()
4264 wxPuts(_T("\n*** wxDateTime ticks test ***"));
4266 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4268 const Date
& d
= testDates
[n
];
4269 if ( d
.ticks
== -1 )
4272 wxDateTime dt
= d
.DT();
4273 long ticks
= (dt
.GetValue() / 1000).ToLong();
4274 wxPrintf(_T("Ticks of %s:\t% 10ld"), d
.Format().c_str(), ticks
);
4275 if ( ticks
== d
.ticks
)
4277 wxPuts(_T(" (ok)"));
4281 wxPrintf(_T(" (ERROR: should be %ld, delta = %ld)\n"),
4282 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
4285 dt
= d
.DT().ToTimezone(wxDateTime
::GMT0
);
4286 ticks
= (dt
.GetValue() / 1000).ToLong();
4287 wxPrintf(_T("GMtks of %s:\t% 10ld"), d
.Format().c_str(), ticks
);
4288 if ( ticks
== d
.gmticks
)
4290 wxPuts(_T(" (ok)"));
4294 wxPrintf(_T(" (ERROR: should be %ld, delta = %ld)\n"),
4295 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
4302 // test conversions to JDN &c
4303 static void TestTimeJDN()
4305 wxPuts(_T("\n*** wxDateTime to JDN test ***"));
4307 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4309 const Date
& d
= testDates
[n
];
4310 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
4311 double jdn
= dt
.GetJulianDayNumber();
4313 wxPrintf(_T("JDN of %s is:\t% 15.6f"), d
.Format().c_str(), jdn
);
4316 wxPuts(_T(" (ok)"));
4320 wxPrintf(_T(" (ERROR: should be %f, delta = %f)\n"),
4321 d
.jdn
, jdn
- d
.jdn
);
4326 // test week days computation
4327 static void TestTimeWDays()
4329 wxPuts(_T("\n*** wxDateTime weekday test ***"));
4331 // test GetWeekDay()
4333 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4335 const Date
& d
= testDates
[n
];
4336 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
4338 wxDateTime
::WeekDay wday
= dt
.GetWeekDay();
4339 wxPrintf(_T("%s is: %s"),
4341 wxDateTime
::GetWeekDayName(wday
).c_str());
4342 if ( wday
== d
.wday
)
4344 wxPuts(_T(" (ok)"));
4348 wxPrintf(_T(" (ERROR: should be %s)\n"),
4349 wxDateTime
::GetWeekDayName(d
.wday
).c_str());
4355 // test SetToWeekDay()
4356 struct WeekDateTestData
4358 Date date
; // the real date (precomputed)
4359 int nWeek
; // its week index in the month
4360 wxDateTime
::WeekDay wday
; // the weekday
4361 wxDateTime
::Month month
; // the month
4362 int year
; // and the year
4364 wxString
Format() const
4367 switch ( nWeek
< -1 ?
-nWeek
: nWeek
)
4369 case 1: which
= _T("first"); break;
4370 case 2: which
= _T("second"); break;
4371 case 3: which
= _T("third"); break;
4372 case 4: which
= _T("fourth"); break;
4373 case 5: which
= _T("fifth"); break;
4375 case -1: which
= _T("last"); break;
4380 which
+= _T(" from end");
4383 s
.Printf(_T("The %s %s of %s in %d"),
4385 wxDateTime
::GetWeekDayName(wday
).c_str(),
4386 wxDateTime
::GetMonthName(month
).c_str(),
4393 // the array data was generated by the following python program
4395 from DateTime import *
4396 from whrandom import *
4397 from string import *
4399 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4400 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4402 week = DateTimeDelta(7)
4405 year = randint(1900, 2100)
4406 month = randint(1, 12)
4407 day = randint(1, 28)
4408 dt = DateTime(year, month, day)
4409 wday = dt.day_of_week
4411 countFromEnd = choice([-1, 1])
4414 while dt.month is month:
4415 dt = dt - countFromEnd * week
4416 weekNum = weekNum + countFromEnd
4418 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
4420 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
4421 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
4424 static const WeekDateTestData weekDatesTestData
[] =
4426 { { 20, wxDateTime
::Mar
, 2045 }, 3, wxDateTime
::Mon
, wxDateTime
::Mar
, 2045 },
4427 { { 5, wxDateTime
::Jun
, 1985 }, -4, wxDateTime
::Wed
, wxDateTime
::Jun
, 1985 },
4428 { { 12, wxDateTime
::Nov
, 1961 }, -3, wxDateTime
::Sun
, wxDateTime
::Nov
, 1961 },
4429 { { 27, wxDateTime
::Feb
, 2093 }, -1, wxDateTime
::Fri
, wxDateTime
::Feb
, 2093 },
4430 { { 4, wxDateTime
::Jul
, 2070 }, -4, wxDateTime
::Fri
, wxDateTime
::Jul
, 2070 },
4431 { { 2, wxDateTime
::Apr
, 1906 }, -5, wxDateTime
::Mon
, wxDateTime
::Apr
, 1906 },
4432 { { 19, wxDateTime
::Jul
, 2023 }, -2, wxDateTime
::Wed
, wxDateTime
::Jul
, 2023 },
4433 { { 5, wxDateTime
::May
, 1958 }, -4, wxDateTime
::Mon
, wxDateTime
::May
, 1958 },
4434 { { 11, wxDateTime
::Aug
, 1900 }, 2, wxDateTime
::Sat
, wxDateTime
::Aug
, 1900 },
4435 { { 14, wxDateTime
::Feb
, 1945 }, 2, wxDateTime
::Wed
, wxDateTime
::Feb
, 1945 },
4436 { { 25, wxDateTime
::Jul
, 1967 }, -1, wxDateTime
::Tue
, wxDateTime
::Jul
, 1967 },
4437 { { 9, wxDateTime
::May
, 1916 }, -4, wxDateTime
::Tue
, wxDateTime
::May
, 1916 },
4438 { { 20, wxDateTime
::Jun
, 1927 }, 3, wxDateTime
::Mon
, wxDateTime
::Jun
, 1927 },
4439 { { 2, wxDateTime
::Aug
, 2000 }, 1, wxDateTime
::Wed
, wxDateTime
::Aug
, 2000 },
4440 { { 20, wxDateTime
::Apr
, 2044 }, 3, wxDateTime
::Wed
, wxDateTime
::Apr
, 2044 },
4441 { { 20, wxDateTime
::Feb
, 1932 }, -2, wxDateTime
::Sat
, wxDateTime
::Feb
, 1932 },
4442 { { 25, wxDateTime
::Jul
, 2069 }, 4, wxDateTime
::Thu
, wxDateTime
::Jul
, 2069 },
4443 { { 3, wxDateTime
::Apr
, 1925 }, 1, wxDateTime
::Fri
, wxDateTime
::Apr
, 1925 },
4444 { { 21, wxDateTime
::Mar
, 2093 }, 3, wxDateTime
::Sat
, wxDateTime
::Mar
, 2093 },
4445 { { 3, wxDateTime
::Dec
, 2074 }, -5, wxDateTime
::Mon
, wxDateTime
::Dec
, 2074 },
4448 static const wxChar
*fmt
= _T("%d-%b-%Y");
4451 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4453 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4455 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4457 wxPrintf(_T("%s is %s"), wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4459 const Date
& d
= wd
.date
;
4460 if ( d
.SameDay(dt
.GetTm()) )
4462 wxPuts(_T(" (ok)"));
4466 dt
.Set(d
.day
, d
.month
, d
.year
);
4468 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.Format(fmt
).c_str());
4473 // test the computation of (ISO) week numbers
4474 static void TestTimeWNumber()
4476 wxPuts(_T("\n*** wxDateTime week number test ***"));
4478 struct WeekNumberTestData
4480 Date date
; // the date
4481 wxDateTime
::wxDateTime_t week
; // the week number in the year
4482 wxDateTime
::wxDateTime_t wmon
; // the week number in the month
4483 wxDateTime
::wxDateTime_t wmon2
; // same but week starts with Sun
4484 wxDateTime
::wxDateTime_t dnum
; // day number in the year
4487 // data generated with the following python script:
4489 from DateTime import *
4490 from whrandom import *
4491 from string import *
4493 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4494 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4496 def GetMonthWeek(dt):
4497 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4498 if weekNumMonth < 0:
4499 weekNumMonth = weekNumMonth + 53
4502 def GetLastSundayBefore(dt):
4503 if dt.iso_week[2] == 7:
4506 return dt - DateTimeDelta(dt.iso_week[2])
4509 year = randint(1900, 2100)
4510 month = randint(1, 12)
4511 day = randint(1, 28)
4512 dt = DateTime(year, month, day)
4513 dayNum = dt.day_of_year
4514 weekNum = dt.iso_week[1]
4515 weekNumMonth = GetMonthWeek(dt)
4518 dtSunday = GetLastSundayBefore(dt)
4520 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4521 weekNumMonth2 = weekNumMonth2 + 1
4522 dtSunday = dtSunday - DateTimeDelta(7)
4524 data = { 'day': rjust(`day`, 2), \
4525 'month': monthNames[month - 1], \
4527 'weekNum': rjust(`weekNum`, 2), \
4528 'weekNumMonth': weekNumMonth, \
4529 'weekNumMonth2': weekNumMonth2, \
4530 'dayNum': rjust(`dayNum`, 3) }
4532 print " { { %(day)s, "\
4533 "wxDateTime::%(month)s, "\
4536 "%(weekNumMonth)s, "\
4537 "%(weekNumMonth2)s, "\
4538 "%(dayNum)s }," % data
4541 static const WeekNumberTestData weekNumberTestDates
[] =
4543 { { 27, wxDateTime
::Dec
, 1966 }, 52, 5, 5, 361 },
4544 { { 22, wxDateTime
::Jul
, 1926 }, 29, 4, 4, 203 },
4545 { { 22, wxDateTime
::Oct
, 2076 }, 43, 4, 4, 296 },
4546 { { 1, wxDateTime
::Jul
, 1967 }, 26, 1, 1, 182 },
4547 { { 8, wxDateTime
::Nov
, 2004 }, 46, 2, 2, 313 },
4548 { { 21, wxDateTime
::Mar
, 1920 }, 12, 3, 4, 81 },
4549 { { 7, wxDateTime
::Jan
, 1965 }, 1, 2, 2, 7 },
4550 { { 19, wxDateTime
::Oct
, 1999 }, 42, 4, 4, 292 },
4551 { { 13, wxDateTime
::Aug
, 1955 }, 32, 2, 2, 225 },
4552 { { 18, wxDateTime
::Jul
, 2087 }, 29, 3, 3, 199 },
4553 { { 2, wxDateTime
::Sep
, 2028 }, 35, 1, 1, 246 },
4554 { { 28, wxDateTime
::Jul
, 1945 }, 30, 5, 4, 209 },
4555 { { 15, wxDateTime
::Jun
, 1901 }, 24, 3, 3, 166 },
4556 { { 10, wxDateTime
::Oct
, 1939 }, 41, 3, 2, 283 },
4557 { { 3, wxDateTime
::Dec
, 1965 }, 48, 1, 1, 337 },
4558 { { 23, wxDateTime
::Feb
, 1940 }, 8, 4, 4, 54 },
4559 { { 2, wxDateTime
::Jan
, 1987 }, 1, 1, 1, 2 },
4560 { { 11, wxDateTime
::Aug
, 2079 }, 32, 2, 2, 223 },
4561 { { 2, wxDateTime
::Feb
, 2063 }, 5, 1, 1, 33 },
4562 { { 16, wxDateTime
::Oct
, 1942 }, 42, 3, 3, 289 },
4565 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4567 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4568 const Date
& d
= wn
.date
;
4570 wxDateTime dt
= d
.DT();
4572 wxDateTime
::wxDateTime_t
4573 week
= dt
.GetWeekOfYear(wxDateTime
::Monday_First
),
4574 wmon
= dt
.GetWeekOfMonth(wxDateTime
::Monday_First
),
4575 wmon2
= dt
.GetWeekOfMonth(wxDateTime
::Sunday_First
),
4576 dnum
= dt
.GetDayOfYear();
4578 wxPrintf(_T("%s: the day number is %d"), d
.FormatDate().c_str(), dnum
);
4579 if ( dnum
== wn
.dnum
)
4581 wxPrintf(_T(" (ok)"));
4585 wxPrintf(_T(" (ERROR: should be %d)"), wn
.dnum
);
4588 wxPrintf(_T(", week in month is %d"), wmon
);
4589 if ( wmon
== wn
.wmon
)
4591 wxPrintf(_T(" (ok)"));
4595 wxPrintf(_T(" (ERROR: should be %d)"), wn
.wmon
);
4598 wxPrintf(_T(" or %d"), wmon2
);
4599 if ( wmon2
== wn
.wmon2
)
4601 wxPrintf(_T(" (ok)"));
4605 wxPrintf(_T(" (ERROR: should be %d)"), wn
.wmon2
);
4608 wxPrintf(_T(", week in year is %d"), week
);
4609 if ( week
== wn
.week
)
4611 wxPuts(_T(" (ok)"));
4615 wxPrintf(_T(" (ERROR: should be %d)\n"), wn
.week
);
4620 // test DST calculations
4621 static void TestTimeDST()
4623 wxPuts(_T("\n*** wxDateTime DST test ***"));
4625 wxPrintf(_T("DST is%s in effect now.\n\n"),
4626 wxDateTime
::Now().IsDST() ?
_T("") : _T(" not"));
4628 // taken from http://www.energy.ca.gov/daylightsaving.html
4629 static const Date datesDST
[2][2004 - 1900 + 1] =
4632 { 1, wxDateTime
::Apr
, 1990 },
4633 { 7, wxDateTime
::Apr
, 1991 },
4634 { 5, wxDateTime
::Apr
, 1992 },
4635 { 4, wxDateTime
::Apr
, 1993 },
4636 { 3, wxDateTime
::Apr
, 1994 },
4637 { 2, wxDateTime
::Apr
, 1995 },
4638 { 7, wxDateTime
::Apr
, 1996 },
4639 { 6, wxDateTime
::Apr
, 1997 },
4640 { 5, wxDateTime
::Apr
, 1998 },
4641 { 4, wxDateTime
::Apr
, 1999 },
4642 { 2, wxDateTime
::Apr
, 2000 },
4643 { 1, wxDateTime
::Apr
, 2001 },
4644 { 7, wxDateTime
::Apr
, 2002 },
4645 { 6, wxDateTime
::Apr
, 2003 },
4646 { 4, wxDateTime
::Apr
, 2004 },
4649 { 28, wxDateTime
::Oct
, 1990 },
4650 { 27, wxDateTime
::Oct
, 1991 },
4651 { 25, wxDateTime
::Oct
, 1992 },
4652 { 31, wxDateTime
::Oct
, 1993 },
4653 { 30, wxDateTime
::Oct
, 1994 },
4654 { 29, wxDateTime
::Oct
, 1995 },
4655 { 27, wxDateTime
::Oct
, 1996 },
4656 { 26, wxDateTime
::Oct
, 1997 },
4657 { 25, wxDateTime
::Oct
, 1998 },
4658 { 31, wxDateTime
::Oct
, 1999 },
4659 { 29, wxDateTime
::Oct
, 2000 },
4660 { 28, wxDateTime
::Oct
, 2001 },
4661 { 27, wxDateTime
::Oct
, 2002 },
4662 { 26, wxDateTime
::Oct
, 2003 },
4663 { 31, wxDateTime
::Oct
, 2004 },
4668 for ( year
= 1990; year
< 2005; year
++ )
4670 wxDateTime dtBegin
= wxDateTime
::GetBeginDST(year
, wxDateTime
::USA
),
4671 dtEnd
= wxDateTime
::GetEndDST(year
, wxDateTime
::USA
);
4673 wxPrintf(_T("DST period in the US for year %d: from %s to %s"),
4674 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4676 size_t n
= year
- 1990;
4677 const Date
& dBegin
= datesDST
[0][n
];
4678 const Date
& dEnd
= datesDST
[1][n
];
4680 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4682 wxPuts(_T(" (ok)"));
4686 wxPrintf(_T(" (ERROR: should be %s %d to %s %d)\n"),
4687 wxDateTime
::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4688 wxDateTime
::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4694 for ( year
= 1990; year
< 2005; year
++ )
4696 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
4698 wxDateTime
::GetBeginDST(year
, wxDateTime
::Country_EEC
).Format().c_str(),
4699 wxDateTime
::GetEndDST(year
, wxDateTime
::Country_EEC
).Format().c_str());
4703 // test wxDateTime -> text conversion
4704 static void TestTimeFormat()
4706 wxPuts(_T("\n*** wxDateTime formatting test ***"));
4708 // some information may be lost during conversion, so store what kind
4709 // of info should we recover after a round trip
4712 CompareNone
, // don't try comparing
4713 CompareBoth
, // dates and times should be identical
4714 CompareDate
, // dates only
4715 CompareTime
// time only
4720 CompareKind compareKind
;
4721 const wxChar
*format
;
4722 } formatTestFormats
[] =
4724 { CompareBoth
, _T("---> %c") },
4725 { CompareDate
, _T("Date is %A, %d of %B, in year %Y") },
4726 { CompareBoth
, _T("Date is %x, time is %X") },
4727 { CompareTime
, _T("Time is %H:%M:%S or %I:%M:%S %p") },
4728 { CompareNone
, _T("The day of year: %j, the week of year: %W") },
4729 { CompareDate
, _T("ISO date without separators: %Y%m%d") },
4732 static const Date formatTestDates
[] =
4734 { 29, wxDateTime
::May
, 1976, 18, 30, 00 },
4735 { 31, wxDateTime
::Dec
, 1999, 23, 30, 00 },
4737 // this test can't work for other centuries because it uses two digit
4738 // years in formats, so don't even try it
4739 { 29, wxDateTime
::May
, 2076, 18, 30, 00 },
4740 { 29, wxDateTime
::Feb
, 2400, 02, 15, 25 },
4741 { 01, wxDateTime
::Jan
, -52, 03, 16, 47 },
4745 // an extra test (as it doesn't depend on date, don't do it in the loop)
4746 wxPrintf(_T("%s\n"), wxDateTime
::Now().Format(_T("Our timezone is %Z")).c_str());
4748 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4752 wxDateTime dt
= d
== 0 ? wxDateTime
::Now() : formatTestDates
[d
- 1].DT();
4753 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4755 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4756 wxPrintf(_T("%s"), s
.c_str());
4758 // what can we recover?
4759 int kind
= formatTestFormats
[n
].compareKind
;
4763 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4766 // converion failed - should it have?
4767 if ( kind
== CompareNone
)
4768 wxPuts(_T(" (ok)"));
4770 wxPuts(_T(" (ERROR: conversion back failed)"));
4774 // should have parsed the entire string
4775 wxPuts(_T(" (ERROR: conversion back stopped too soon)"));
4779 bool equal
= FALSE
; // suppress compilaer warning
4787 equal
= dt
.IsSameDate(dt2
);
4791 equal
= dt
.IsSameTime(dt2
);
4797 wxPrintf(_T(" (ERROR: got back '%s' instead of '%s')\n"),
4798 dt2
.Format().c_str(), dt
.Format().c_str());
4802 wxPuts(_T(" (ok)"));
4809 // test text -> wxDateTime conversion
4810 static void TestTimeParse()
4812 wxPuts(_T("\n*** wxDateTime parse test ***"));
4814 struct ParseTestData
4816 const wxChar
*format
;
4821 static const ParseTestData parseTestDates
[] =
4823 { _T("Sat, 18 Dec 1999 00:46:40 +0100"), { 18, wxDateTime
::Dec
, 1999, 00, 46, 40 }, TRUE
},
4824 { _T("Wed, 1 Dec 1999 05:17:20 +0300"), { 1, wxDateTime
::Dec
, 1999, 03, 17, 20 }, TRUE
},
4827 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4829 const wxChar
*format
= parseTestDates
[n
].format
;
4831 wxPrintf(_T("%s => "), format
);
4834 if ( dt
.ParseRfc822Date(format
) )
4836 wxPrintf(_T("%s "), dt
.Format().c_str());
4838 if ( parseTestDates
[n
].good
)
4840 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4847 wxPrintf(_T("(ERROR: should be %s)\n"), dtReal
.Format().c_str());
4852 wxPuts(_T("(ERROR: bad format)"));
4857 wxPrintf(_T("bad format (%s)\n"),
4858 parseTestDates
[n
].good ?
"ERROR" : "ok");
4863 static void TestDateTimeInteractive()
4865 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
4871 wxPrintf(_T("Enter a date: "));
4872 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
4875 // kill the last '\n'
4876 buf
[wxStrlen(buf
) - 1] = 0;
4879 const wxChar
*p
= dt
.ParseDate(buf
);
4882 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
4888 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
4891 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
4892 dt
.Format(_T("%b %d, %Y")).c_str(),
4894 dt
.GetWeekOfMonth(wxDateTime
::Monday_First
),
4895 dt
.GetWeekOfMonth(wxDateTime
::Sunday_First
),
4896 dt
.GetWeekOfYear(wxDateTime
::Monday_First
));
4899 wxPuts(_T("\n*** done ***"));
4902 static void TestTimeMS()
4904 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
4906 wxDateTime dt1
= wxDateTime
::Now(),
4907 dt2
= wxDateTime
::UNow();
4909 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
4910 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
4911 wxPrintf(_T("Dummy loop: "));
4912 for ( int i
= 0; i
< 6000; i
++ )
4914 //for ( int j = 0; j < 10; j++ )
4917 s
.Printf(_T("%g"), sqrt(i
));
4923 wxPuts(_T(", done"));
4926 dt2
= wxDateTime
::UNow();
4927 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
4929 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
4931 wxPuts(_T("\n*** done ***"));
4934 static void TestTimeArithmetics()
4936 wxPuts(_T("\n*** testing arithmetic operations on wxDateTime ***"));
4938 static const struct ArithmData
4940 ArithmData(const wxDateSpan
& sp
, const wxChar
*nam
)
4941 : span(sp
), name(nam
) { }
4945 } testArithmData
[] =
4947 ArithmData(wxDateSpan
::Day(), _T("day")),
4948 ArithmData(wxDateSpan
::Week(), _T("week")),
4949 ArithmData(wxDateSpan
::Month(), _T("month")),
4950 ArithmData(wxDateSpan
::Year(), _T("year")),
4951 ArithmData(wxDateSpan(1, 2, 3, 4), _T("year, 2 months, 3 weeks, 4 days")),
4954 wxDateTime
dt(29, wxDateTime
::Dec
, 1999), dt1
, dt2
;
4956 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4958 wxDateSpan span
= testArithmData
[n
].span
;
4962 const wxChar
*name
= testArithmData
[n
].name
;
4963 wxPrintf(_T("%s + %s = %s, %s - %s = %s\n"),
4964 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4965 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4967 wxPrintf(_T("Going back: %s"), (dt1
- span
).FormatISODate().c_str());
4968 if ( dt1
- span
== dt
)
4970 wxPuts(_T(" (ok)"));
4974 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.FormatISODate().c_str());
4977 wxPrintf(_T("Going forward: %s"), (dt2
+ span
).FormatISODate().c_str());
4978 if ( dt2
+ span
== dt
)
4980 wxPuts(_T(" (ok)"));
4984 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.FormatISODate().c_str());
4987 wxPrintf(_T("Double increment: %s"), (dt2
+ 2*span
).FormatISODate().c_str());
4988 if ( dt2
+ 2*span
== dt1
)
4990 wxPuts(_T(" (ok)"));
4994 wxPrintf(_T(" (ERROR: should be %s)\n"), dt2
.FormatISODate().c_str());
5001 static void TestTimeHolidays()
5003 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
5005 wxDateTime
::Tm tm
= wxDateTime(29, wxDateTime
::May
, 2000).GetTm();
5006 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
5007 dtEnd
= dtStart
.GetLastMonthDay();
5009 wxDateTimeArray hol
;
5010 wxDateTimeHolidayAuthority
::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
5012 const wxChar
*format
= _T("%d-%b-%Y (%a)");
5014 wxPrintf(_T("All holidays between %s and %s:\n"),
5015 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
5017 size_t count
= hol
.GetCount();
5018 for ( size_t n
= 0; n
< count
; n
++ )
5020 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
5026 static void TestTimeZoneBug()
5028 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
5030 wxDateTime date
= wxDateTime(1, wxDateTime
::Mar
, 2000);
5031 for ( int i
= 0; i
< 31; i
++ )
5033 wxPrintf(_T("Date %s: week day %s.\n"),
5034 date
.Format(_T("%d-%m-%Y")).c_str(),
5035 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
5037 date
+= wxDateSpan
::Day();
5043 static void TestTimeSpanFormat()
5045 wxPuts(_T("\n*** wxTimeSpan tests ***"));
5047 static const wxChar
*formats
[] =
5049 _T("(default) %H:%M:%S"),
5050 _T("%E weeks and %D days"),
5051 _T("%l milliseconds"),
5052 _T("(with ms) %H:%M:%S:%l"),
5053 _T("100%% of minutes is %M"), // test "%%"
5054 _T("%D days and %H hours"),
5055 _T("or also %S seconds"),
5058 wxTimeSpan
ts1(1, 2, 3, 4),
5060 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
5062 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
5063 ts1
.Format(formats
[n
]).c_str(),
5064 ts2
.Format(formats
[n
]).c_str());
5072 // test compatibility with the old wxDate/wxTime classes
5073 static void TestTimeCompatibility()
5075 wxPuts(_T("\n*** wxDateTime compatibility test ***"));
5077 wxPrintf(_T("wxDate for JDN 0: %s\n"), wxDate(0l).FormatDate().c_str());
5078 wxPrintf(_T("wxDate for MJD 0: %s\n"), wxDate(2400000).FormatDate().c_str());
5080 double jdnNow
= wxDateTime
::Now().GetJDN();
5081 long jdnMidnight
= (long)(jdnNow
- 0.5);
5082 wxPrintf(_T("wxDate for today: %s\n"), wxDate(jdnMidnight
).FormatDate().c_str());
5084 jdnMidnight
= wxDate().Set().GetJulianDate();
5085 wxPrintf(_T("wxDateTime for today: %s\n"),
5086 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime
::GMT0
).c_str());
5088 int flags
= wxEUROPEAN
;//wxFULL;
5091 wxPrintf(_T("Today is %s\n"), date
.FormatDate(flags
).c_str());
5092 for ( int n
= 0; n
< 7; n
++ )
5094 wxPrintf(_T("Previous %s is %s\n"),
5095 wxDateTime
::GetWeekDayName((wxDateTime
::WeekDay
)n
),
5096 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
5102 #endif // TEST_DATETIME
5104 // ----------------------------------------------------------------------------
5106 // ----------------------------------------------------------------------------
5110 #include "wx/thread.h"
5112 static size_t gs_counter
= (size_t)-1;
5113 static wxCriticalSection gs_critsect
;
5114 static wxSemaphore gs_cond
;
5116 class MyJoinableThread
: public wxThread
5119 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
5120 { m_n
= n
; Create(); }
5122 // thread execution starts here
5123 virtual ExitCode
Entry();
5129 wxThread
::ExitCode MyJoinableThread
::Entry()
5131 unsigned long res
= 1;
5132 for ( size_t n
= 1; n
< m_n
; n
++ )
5136 // it's a loooong calculation :-)
5140 return (ExitCode
)res
;
5143 class MyDetachedThread
: public wxThread
5146 MyDetachedThread(size_t n
, wxChar ch
)
5150 m_cancelled
= FALSE
;
5155 // thread execution starts here
5156 virtual ExitCode
Entry();
5159 virtual void OnExit();
5162 size_t m_n
; // number of characters to write
5163 wxChar m_ch
; // character to write
5165 bool m_cancelled
; // FALSE if we exit normally
5168 wxThread
::ExitCode MyDetachedThread
::Entry()
5171 wxCriticalSectionLocker
lock(gs_critsect
);
5172 if ( gs_counter
== (size_t)-1 )
5178 for ( size_t n
= 0; n
< m_n
; n
++ )
5180 if ( TestDestroy() )
5190 wxThread
::Sleep(100);
5196 void MyDetachedThread
::OnExit()
5198 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
5200 wxCriticalSectionLocker
lock(gs_critsect
);
5201 if ( !--gs_counter
&& !m_cancelled
)
5205 static void TestDetachedThreads()
5207 wxPuts(_T("\n*** Testing detached threads ***"));
5209 static const size_t nThreads
= 3;
5210 MyDetachedThread
*threads
[nThreads
];
5212 for ( n
= 0; n
< nThreads
; n
++ )
5214 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
5217 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
5218 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
5220 for ( n
= 0; n
< nThreads
; n
++ )
5225 // wait until all threads terminate
5231 static void TestJoinableThreads()
5233 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
5235 // calc 10! in the background
5236 MyJoinableThread
thread(10);
5239 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
5240 (unsigned long)thread
.Wait());
5243 static void TestThreadSuspend()
5245 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
5247 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
5251 // this is for this demo only, in a real life program we'd use another
5252 // condition variable which would be signaled from wxThread::Entry() to
5253 // tell us that the thread really started running - but here just wait a
5254 // bit and hope that it will be enough (the problem is, of course, that
5255 // the thread might still not run when we call Pause() which will result
5257 wxThread
::Sleep(300);
5259 for ( size_t n
= 0; n
< 3; n
++ )
5263 wxPuts(_T("\nThread suspended"));
5266 // don't sleep but resume immediately the first time
5267 wxThread
::Sleep(300);
5269 wxPuts(_T("Going to resume the thread"));
5274 wxPuts(_T("Waiting until it terminates now"));
5276 // wait until the thread terminates
5282 static void TestThreadDelete()
5284 // As above, using Sleep() is only for testing here - we must use some
5285 // synchronisation object instead to ensure that the thread is still
5286 // running when we delete it - deleting a detached thread which already
5287 // terminated will lead to a crash!
5289 wxPuts(_T("\n*** Testing thread delete function ***"));
5291 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
5295 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
5297 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
5301 wxThread
::Sleep(300);
5305 wxPuts(_T("\nDeleted a running thread."));
5307 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
5311 wxThread
::Sleep(300);
5317 wxPuts(_T("\nDeleted a sleeping thread."));
5319 MyJoinableThread
thread3(20);
5324 wxPuts(_T("\nDeleted a joinable thread."));
5326 MyJoinableThread
thread4(2);
5329 wxThread
::Sleep(300);
5333 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
5338 class MyWaitingThread
: public wxThread
5341 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
5344 m_condition
= condition
;
5349 virtual ExitCode
Entry()
5351 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
5356 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
5360 m_condition
->Wait();
5363 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
5371 wxCondition
*m_condition
;
5374 static void TestThreadConditions()
5377 wxCondition
condition(mutex
);
5379 // otherwise its difficult to understand which log messages pertain to
5381 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
5382 // condition.GetId(), gs_cond.GetId());
5384 // create and launch threads
5385 MyWaitingThread
*threads
[10];
5388 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5390 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
5393 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5398 // wait until all threads run
5399 wxPuts(_T("Main thread is waiting for the other threads to start"));
5402 size_t nRunning
= 0;
5403 while ( nRunning
< WXSIZEOF(threads
) )
5409 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
5413 wxPuts(_T("Main thread: all threads started up."));
5416 wxThread
::Sleep(500);
5419 // now wake one of them up
5420 wxPrintf(_T("Main thread: about to signal the condition.\n"));
5425 wxThread
::Sleep(200);
5427 // wake all the (remaining) threads up, so that they can exit
5428 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
5430 condition
.Broadcast();
5432 // give them time to terminate (dirty!)
5433 wxThread
::Sleep(500);
5436 #include "wx/utils.h"
5438 class MyExecThread
: public wxThread
5441 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5447 virtual ExitCode
Entry()
5449 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5456 static void TestThreadExec()
5458 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5460 MyExecThread
thread(_T("true"));
5463 wxPrintf(_T("Main program exit code: %ld.\n"),
5464 wxExecute(_T("false"), wxEXEC_SYNC
));
5466 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5470 #include "wx/datetime.h"
5472 class MySemaphoreThread
: public wxThread
5475 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5476 : wxThread(wxTHREAD_JOINABLE
),
5483 virtual ExitCode
Entry()
5485 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
5486 wxDateTime
::Now().FormatTime().c_str(), m_i
, (long)GetId());
5490 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
5491 wxDateTime
::Now().FormatTime().c_str(), m_i
, (long)GetId());
5495 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
5496 wxDateTime
::Now().FormatTime().c_str(), m_i
, (long)GetId());
5508 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5510 static void TestSemaphore()
5512 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5514 static const int SEM_LIMIT
= 3;
5516 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5517 ArrayThreads threads
;
5519 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5521 threads
.Add(new MySemaphoreThread(i
, &sem
));
5522 threads
.Last()->Run();
5525 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5532 #endif // TEST_THREADS
5534 // ----------------------------------------------------------------------------
5536 // ----------------------------------------------------------------------------
5540 #include "wx/dynarray.h"
5542 typedef unsigned short ushort
;
5544 #define DefineCompare(name, T) \
5546 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5548 return first - second; \
5551 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5553 return *first - *second; \
5556 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5558 return *second - *first; \
5561 DefineCompare(UShort, ushort);
5562 DefineCompare(Int
, int);
5564 // test compilation of all macros
5565 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5566 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5567 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5568 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5570 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5571 #include "wx/arrimpl.cpp"
5572 WX_DEFINE_OBJARRAY(ArrayBars
);
5574 static void PrintArray(const wxChar
* name
, const wxArrayString
& array
)
5576 wxPrintf(_T("Dump of the array '%s'\n"), name
);
5578 size_t nCount
= array
.GetCount();
5579 for ( size_t n
= 0; n
< nCount
; n
++ )
5581 wxPrintf(_T("\t%s[%u] = '%s'\n"), name
, n
, array
[n
].c_str());
5585 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5586 const wxString
& second
)
5588 return first
.length() - second
.length();
5591 #define TestArrayOf(name) \
5593 static void PrintArray(const wxChar* name, const wxSortedArray##name & array) \
5595 wxPrintf(_T("Dump of the array '%s'\n"), name); \
5597 size_t nCount = array.GetCount(); \
5598 for ( size_t n = 0; n < nCount; n++ ) \
5600 wxPrintf(_T("\t%s[%u] = %d\n"), name, n, array[n]); \
5604 static void PrintArray(const wxChar* name, const wxArray##name & array) \
5606 wxPrintf(_T("Dump of the array '%s'\n"), name); \
5608 size_t nCount = array.GetCount(); \
5609 for ( size_t n = 0; n < nCount; n++ ) \
5611 wxPrintf(_T("\t%s[%u] = %d\n"), name, n, array[n]); \
5615 static void TestArrayOf ## name ## s() \
5617 wxPrintf(_T("*** Testing wxArray%s ***\n"), #name); \
5625 wxPuts(_T("Initially:")); \
5626 PrintArray(_T("a"), a); \
5628 wxPuts(_T("After sort:")); \
5629 a.Sort(name ## Compare); \
5630 PrintArray(_T("a"), a); \
5632 wxPuts(_T("After reverse sort:")); \
5633 a.Sort(name ## RevCompare); \
5634 PrintArray(_T("a"), a); \
5636 wxSortedArray##name b; \
5642 wxPuts(_T("Sorted array initially:")); \
5643 PrintArray(_T("b"), b); \
5646 TestArrayOf(UShort
);
5649 static void TestArrayOfObjects()
5651 wxPuts(_T("*** Testing wxObjArray ***\n"));
5655 Bar
bar("second bar (two copies!)");
5657 wxPrintf(_T("Initially: %u objects in the array, %u objects total.\n"),
5658 bars
.GetCount(), Bar
::GetNumber());
5660 bars
.Add(new Bar("first bar"));
5663 wxPrintf(_T("Now: %u objects in the array, %u objects total.\n"),
5664 bars
.GetCount(), Bar
::GetNumber());
5666 bars
.RemoveAt(1, bars
.GetCount() - 1);
5668 wxPrintf(_T("After removing all but first element: %u objects in the ")
5669 _T("array, %u objects total.\n"),
5670 bars
.GetCount(), Bar
::GetNumber());
5674 wxPrintf(_T("After Empty(): %u objects in the array, %u objects total.\n"),
5675 bars
.GetCount(), Bar
::GetNumber());
5678 wxPrintf(_T("Finally: no more objects in the array, %u objects total.\n"),
5682 #endif // TEST_ARRAYS
5684 // ----------------------------------------------------------------------------
5686 // ----------------------------------------------------------------------------
5690 #include "wx/timer.h"
5691 #include "wx/tokenzr.h"
5693 static void TestStringConstruction()
5695 wxPuts(_T("*** Testing wxString constructores ***"));
5697 #define TEST_CTOR(args, res) \
5700 wxPrintf(_T("wxString%s = %s "), #args, s.c_str()); \
5703 wxPuts(_T("(ok)")); \
5707 wxPrintf(_T("(ERROR: should be %s)\n"), res); \
5711 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5712 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5713 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5714 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5716 static const wxChar
*s
= _T("?really!");
5717 const wxChar
*start
= wxStrchr(s
, _T('r'));
5718 const wxChar
*end
= wxStrchr(s
, _T('!'));
5719 TEST_CTOR((start
, end
), _T("really"));
5724 static void TestString()
5734 for (int i
= 0; i
< 1000000; ++i
)
5738 c
= "! How'ya doin'?";
5741 c
= "Hello world! What's up?";
5746 wxPrintf(_T("TestString elapsed time: %ld\n"), sw
.Time());
5749 static void TestPChar()
5757 for (int i
= 0; i
< 1000000; ++i
)
5759 wxStrcpy (a
, _T("Hello"));
5760 wxStrcpy (b
, _T(" world"));
5761 wxStrcpy (c
, _T("! How'ya doin'?"));
5764 wxStrcpy (c
, _T("Hello world! What's up?"));
5765 if (wxStrcmp (c
, a
) == 0)
5766 wxStrcpy (c
, _T("Doh!"));
5769 wxPrintf(_T("TestPChar elapsed time: %ld\n"), sw
.Time());
5772 static void TestStringSub()
5774 wxString
s("Hello, world!");
5776 wxPuts(_T("*** Testing wxString substring extraction ***"));
5778 wxPrintf(_T("String = '%s'\n"), s
.c_str());
5779 wxPrintf(_T("Left(5) = '%s'\n"), s
.Left(5).c_str());
5780 wxPrintf(_T("Right(6) = '%s'\n"), s
.Right(6).c_str());
5781 wxPrintf(_T("Mid(3, 5) = '%s'\n"), s(3, 5).c_str());
5782 wxPrintf(_T("Mid(3) = '%s'\n"), s
.Mid(3).c_str());
5783 wxPrintf(_T("substr(3, 5) = '%s'\n"), s
.substr(3, 5).c_str());
5784 wxPrintf(_T("substr(3) = '%s'\n"), s
.substr(3).c_str());
5786 static const wxChar
*prefixes
[] =
5790 _T("Hello, world!"),
5791 _T("Hello, world!!!"),
5797 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5799 wxString prefix
= prefixes
[n
], rest
;
5800 bool rc
= s
.StartsWith(prefix
, &rest
);
5801 wxPrintf(_T("StartsWith('%s') = %s"), prefix
.c_str(), rc ?
_T("TRUE") : _T("FALSE"));
5804 wxPrintf(_T(" (the rest is '%s')\n"), rest
.c_str());
5815 static void TestStringFormat()
5817 wxPuts(_T("*** Testing wxString formatting ***"));
5820 s
.Printf(_T("%03d"), 18);
5822 wxPrintf(_T("Number 18: %s\n"), wxString
::Format(_T("%03d"), 18).c_str());
5823 wxPrintf(_T("Number 18: %s\n"), s
.c_str());
5828 // returns "not found" for npos, value for all others
5829 static wxString
PosToString(size_t res
)
5831 wxString s
= res
== wxString
::npos ?
wxString(_T("not found"))
5832 : wxString
::Format(_T("%u"), res
);
5836 static void TestStringFind()
5838 wxPuts(_T("*** Testing wxString find() functions ***"));
5840 static const wxChar
*strToFind
= _T("ell");
5841 static const struct StringFindTest
5845 result
; // of searching "ell" in str
5848 { _T("Well, hello world"), 0, 1 },
5849 { _T("Well, hello world"), 6, 7 },
5850 { _T("Well, hello world"), 9, wxString
::npos
},
5853 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5855 const StringFindTest
& ft
= findTestData
[n
];
5856 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5858 wxPrintf(_T("Index of '%s' in '%s' starting from %u is %s "),
5859 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5861 size_t resTrue
= ft
.result
;
5862 if ( res
== resTrue
)
5868 wxPrintf(_T("(ERROR: should be %s)\n"),
5869 PosToString(resTrue
).c_str());
5876 static void TestStringTokenizer()
5878 wxPuts(_T("*** Testing wxStringTokenizer ***"));
5880 static const wxChar
*modeNames
[] =
5884 _T("return all empty"),
5889 static const struct StringTokenizerTest
5891 const wxChar
*str
; // string to tokenize
5892 const wxChar
*delims
; // delimiters to use
5893 size_t count
; // count of token
5894 wxStringTokenizerMode mode
; // how should we tokenize it
5895 } tokenizerTestData
[] =
5897 { _T(""), _T(" "), 0 },
5898 { _T("Hello, world"), _T(" "), 2 },
5899 { _T("Hello, world "), _T(" "), 2 },
5900 { _T("Hello, world"), _T(","), 2 },
5901 { _T("Hello, world!"), _T(",!"), 2 },
5902 { _T("Hello,, world!"), _T(",!"), 3 },
5903 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5904 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5905 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5906 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5907 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5908 { _T("01/02/99"), _T("/-"), 3 },
5909 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5912 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5914 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5915 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5917 size_t count
= tkz
.CountTokens();
5918 wxPrintf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5919 MakePrintable(tt
.str
).c_str(),
5921 MakePrintable(tt
.delims
).c_str(),
5922 modeNames
[tkz
.GetMode()]);
5923 if ( count
== tt
.count
)
5929 wxPrintf(_T("(ERROR: should be %u)\n"), tt
.count
);
5934 // if we emulate strtok(), check that we do it correctly
5935 wxChar
*buf
, *s
= NULL
, *last
;
5937 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5939 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5940 wxStrcpy(buf
, tt
.str
);
5942 s
= wxStrtok(buf
, tt
.delims
, &last
);
5949 // now show the tokens themselves
5951 while ( tkz
.HasMoreTokens() )
5953 wxString token
= tkz
.GetNextToken();
5955 wxPrintf(_T("\ttoken %u: '%s'"),
5957 MakePrintable(token
).c_str());
5963 wxPuts(_T(" (ok)"));
5967 wxPrintf(_T(" (ERROR: should be %s)\n"), s
);
5970 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5974 // nothing to compare with
5979 if ( count2
!= count
)
5981 wxPuts(_T("\tERROR: token count mismatch"));
5990 static void TestStringReplace()
5992 wxPuts(_T("*** Testing wxString::replace ***"));
5994 static const struct StringReplaceTestData
5996 const wxChar
*original
; // original test string
5997 size_t start
, len
; // the part to replace
5998 const wxChar
*replacement
; // the replacement string
5999 const wxChar
*result
; // and the expected result
6000 } stringReplaceTestData
[] =
6002 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
6003 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
6004 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
6005 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
6006 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
6009 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
6011 const StringReplaceTestData data
= stringReplaceTestData
[n
];
6013 wxString original
= data
.original
;
6014 original
.replace(data
.start
, data
.len
, data
.replacement
);
6016 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
6017 data
.original
, data
.start
, data
.len
, data
.replacement
,
6020 if ( original
== data
.result
)
6026 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
6033 static void TestStringMatch()
6035 wxPuts(_T("*** Testing wxString::Matches() ***"));
6037 static const struct StringMatchTestData
6040 const wxChar
*wildcard
;
6042 } stringMatchTestData
[] =
6044 { _T("foobar"), _T("foo*"), 1 },
6045 { _T("foobar"), _T("*oo*"), 1 },
6046 { _T("foobar"), _T("*bar"), 1 },
6047 { _T("foobar"), _T("??????"), 1 },
6048 { _T("foobar"), _T("f??b*"), 1 },
6049 { _T("foobar"), _T("f?b*"), 0 },
6050 { _T("foobar"), _T("*goo*"), 0 },
6051 { _T("foobar"), _T("*foo"), 0 },
6052 { _T("foobarfoo"), _T("*foo"), 1 },
6053 { _T(""), _T("*"), 1 },
6054 { _T(""), _T("?"), 0 },
6057 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
6059 const StringMatchTestData
& data
= stringMatchTestData
[n
];
6060 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
6061 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
6063 matches ?
_T("matches") : _T("doesn't match"),
6065 matches
== data
.matches ?
_T("ok") : _T("ERROR"));
6071 #endif // TEST_STRINGS
6073 // ----------------------------------------------------------------------------
6075 // ----------------------------------------------------------------------------
6077 #ifdef TEST_SNGLINST
6078 #include "wx/snglinst.h"
6079 #endif // TEST_SNGLINST
6081 int main(int argc
, char **argv
)
6083 wxApp
::CheckBuildOptions(wxBuildOptions());
6085 wxInitializer initializer
;
6088 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
6093 #ifdef TEST_SNGLINST
6094 wxSingleInstanceChecker checker
;
6095 if ( checker
.Create(_T(".wxconsole.lock")) )
6097 if ( checker
.IsAnotherRunning() )
6099 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
6104 // wait some time to give time to launch another instance
6105 wxPrintf(_T("Press \"Enter\" to continue..."));
6108 else // failed to create
6110 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
6112 #endif // TEST_SNGLINST
6116 #endif // TEST_CHARSET
6119 TestCmdLineConvert();
6121 #if wxUSE_CMDLINE_PARSER
6122 static const wxCmdLineEntryDesc cmdLineDesc
[] =
6124 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
6125 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
6126 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
6127 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
6129 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
6130 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
6131 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
6132 wxCMD_LINE_VAL_NUMBER
},
6133 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
6134 wxCMD_LINE_VAL_DATE
},
6136 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
6137 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
6143 wxChar
**wargv
= new wxChar
*[argc
+ 1];
6146 for ( int n
= 0; n
< argc
; n
++ )
6148 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
6149 wargv
[n
] = wxStrdup(warg
);
6156 #endif // wxUSE_UNICODE
6158 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
6162 for ( int n
= 0; n
< argc
; n
++ )
6167 #endif // wxUSE_UNICODE
6169 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
6170 wxCMD_LINE_VAL_STRING
,
6171 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
6173 switch ( parser
.Parse() )
6176 wxLogMessage(_T("Help was given, terminating."));
6180 ShowCmdLine(parser
);
6184 wxLogMessage(_T("Syntax error detected, aborting."));
6187 #endif // wxUSE_CMDLINE_PARSER
6189 #endif // TEST_CMDLINE
6197 TestStringConstruction();
6200 TestStringTokenizer();
6201 TestStringReplace();
6207 #endif // TEST_STRINGS
6213 a1
.Add(_T("tiger"));
6215 a1
.Add(_T("lion"), 3);
6217 a1
.Add(_T("human"));
6220 wxPuts(_T("*** Initially:"));
6222 PrintArray(_T("a1"), a1
);
6224 wxArrayString
a2(a1
);
6225 PrintArray(_T("a2"), a2
);
6227 wxSortedArrayString
a3(a1
);
6228 PrintArray(_T("a3"), a3
);
6230 wxPuts(_T("*** After deleting three strings from a1"));
6233 PrintArray(_T("a1"), a1
);
6234 PrintArray(_T("a2"), a2
);
6235 PrintArray(_T("a3"), a3
);
6237 wxPuts(_T("*** After reassigning a1 to a2 and a3"));
6239 PrintArray(_T("a2"), a2
);
6240 PrintArray(_T("a3"), a3
);
6242 wxPuts(_T("*** After sorting a1"));
6244 PrintArray(_T("a1"), a1
);
6246 wxPuts(_T("*** After sorting a1 in reverse order"));
6248 PrintArray(_T("a1"), a1
);
6250 wxPuts(_T("*** After sorting a1 by the string length"));
6251 a1
.Sort(StringLenCompare
);
6252 PrintArray(_T("a1"), a1
);
6254 TestArrayOfObjects();
6255 TestArrayOfUShorts();
6259 #endif // TEST_ARRAYS
6270 #ifdef TEST_DLLLOADER
6272 #endif // TEST_DLLLOADER
6276 #endif // TEST_ENVIRON
6280 #endif // TEST_EXECUTE
6282 #ifdef TEST_FILECONF
6284 #endif // TEST_FILECONF
6292 #endif // TEST_LOCALE
6296 for ( size_t n
= 0; n
< 8000; n
++ )
6298 s
<< (wxChar
)(_T('A') + (n
% 26));
6302 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
6304 // this one shouldn't be truncated
6307 // but this one will because log functions use fixed size buffer
6308 // (note that it doesn't need '\n' at the end neither - will be added
6310 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
6322 #ifdef TEST_FILENAME
6326 fn
.Assign(_T("c:\\foo"), _T("bar.baz"));
6327 fn
.Assign(_T("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc"));
6332 TestFileNameConstruction();
6335 TestFileNameConstruction();
6336 TestFileNameMakeRelative();
6337 TestFileNameSplit();
6340 TestFileNameComparison();
6341 TestFileNameOperations();
6343 #endif // TEST_FILENAME
6345 #ifdef TEST_FILETIME
6349 #endif // TEST_FILETIME
6352 wxLog
::AddTraceMask(FTP_TRACE_MASK
);
6353 if ( TestFtpConnect() )
6364 if ( TEST_INTERACTIVE
)
6365 TestFtpInteractive();
6367 //else: connecting to the FTP server failed
6373 #ifdef TEST_LONGLONG
6374 // seed pseudo random generator
6375 srand((unsigned)time(NULL
));
6384 TestMultiplication();
6387 TestLongLongConversion();
6388 TestBitOperations();
6389 TestLongLongComparison();
6390 TestLongLongPrint();
6392 #endif // TEST_LONGLONG
6400 #endif // TEST_HASHMAP
6403 wxLog
::AddTraceMask(_T("mime"));
6408 TestMimeAssociate();
6413 #ifdef TEST_INFO_FUNCTIONS
6419 if ( TEST_INTERACTIVE
)
6422 #endif // TEST_INFO_FUNCTIONS
6424 #ifdef TEST_PATHLIST
6426 #endif // TEST_PATHLIST
6434 #endif // TEST_PRINTF
6438 #endif // TEST_REGCONF
6441 // TODO: write a real test using src/regex/tests file
6446 TestRegExSubmatch();
6447 TestRegExReplacement();
6449 if ( TEST_INTERACTIVE
)
6450 TestRegExInteractive();
6452 #endif // TEST_REGEX
6454 #ifdef TEST_REGISTRY
6456 TestRegistryAssociation();
6457 #endif // TEST_REGISTRY
6462 #endif // TEST_SOCKETS
6470 #endif // TEST_STREAMS
6473 int nCPUs
= wxThread
::GetCPUCount();
6474 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
6476 wxThread
::SetConcurrency(nCPUs
);
6478 TestDetachedThreads();
6481 TestJoinableThreads();
6482 TestThreadSuspend();
6484 TestThreadConditions();
6488 #endif // TEST_THREADS
6492 #endif // TEST_TIMER
6494 #ifdef TEST_DATETIME
6507 TestTimeArithmetics();
6510 TestTimeSpanFormat();
6517 if ( TEST_INTERACTIVE
)
6518 TestDateTimeInteractive();
6519 #endif // TEST_DATETIME
6522 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
6524 #endif // TEST_USLEEP
6529 #endif // TEST_VCARD
6533 #endif // TEST_VOLUME
6536 TestUnicodeToFromAscii();
6537 #endif // TEST_UNICODE
6541 TestEncodingConverter();
6542 #endif // TEST_WCHAR
6545 TestZipStreamRead();
6546 TestZipFileSystem();
6550 TestZlibStreamWrite();
6551 TestZlibStreamRead();