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"
33 // without this pragma, the stupid compiler precompiles #defines below so that
34 // changing them doesn't "take place" later!
39 // ----------------------------------------------------------------------------
40 // conditional compilation
41 // ----------------------------------------------------------------------------
44 A note about all these conditional compilation macros: this file is used
45 both as a test suite for various non-GUI wxWindows classes and as a
46 scratchpad for quick tests. So there are two compilation modes: if you
47 define TEST_ALL all tests are run, otherwise you may enable the individual
48 tests individually in the "#else" branch below.
51 // what to test (in alphabetic order)? uncomment the line below to do all tests
59 #define TEST_DLLLOADER
69 #define TEST_INFO_FUNCTIONS
85 #define TEST_TEXTSTREAM
89 // #define TEST_VCARD -- don't enable this (VZ)
96 static const bool TEST_ALL
= true;
100 static const bool TEST_ALL
= false;
103 // some tests are interactive, define this to run them
104 #ifdef TEST_INTERACTIVE
105 #undef TEST_INTERACTIVE
107 static const bool TEST_INTERACTIVE
= true;
109 static const bool TEST_INTERACTIVE
= false;
112 // ----------------------------------------------------------------------------
113 // test class for container objects
114 // ----------------------------------------------------------------------------
116 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
118 class Bar
// Foo is already taken in the hash test
121 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
122 Bar(const Bar
& bar
) : m_name(bar
.m_name
) { ms_bars
++; }
123 ~Bar() { ms_bars
--; }
125 static size_t GetNumber() { return ms_bars
; }
127 const wxChar
*GetName() const { return m_name
; }
132 static size_t ms_bars
;
135 size_t Bar::ms_bars
= 0;
137 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
139 // ============================================================================
141 // ============================================================================
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
149 // replace TABs with \t and CRs with \n
150 static wxString
MakePrintable(const wxChar
*s
)
153 (void)str
.Replace(_T("\t"), _T("\\t"));
154 (void)str
.Replace(_T("\n"), _T("\\n"));
155 (void)str
.Replace(_T("\r"), _T("\\r"));
160 #endif // MakePrintable() is used
162 // ----------------------------------------------------------------------------
163 // wxFontMapper::CharsetToEncoding
164 // ----------------------------------------------------------------------------
168 #include "wx/fontmap.h"
170 static void TestCharset()
172 static const wxChar
*charsets
[] =
174 // some vali charsets
183 // and now some bogus ones
190 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
192 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(charsets
[n
]);
193 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
195 wxFontMapper::Get()->GetEncodingName(enc
).c_str(),
196 wxFontMapper::Get()->GetEncodingDescription(enc
).c_str());
200 #endif // TEST_CHARSET
202 // ----------------------------------------------------------------------------
204 // ----------------------------------------------------------------------------
208 #include "wx/cmdline.h"
209 #include "wx/datetime.h"
211 #if wxUSE_CMDLINE_PARSER
213 static void ShowCmdLine(const wxCmdLineParser
& parser
)
215 wxString s
= _T("Input files: ");
217 size_t count
= parser
.GetParamCount();
218 for ( size_t param
= 0; param
< count
; param
++ )
220 s
<< parser
.GetParam(param
) << ' ';
224 << _T("Verbose:\t") << (parser
.Found(_T("v")) ? _T("yes") : _T("no")) << '\n'
225 << _T("Quiet:\t") << (parser
.Found(_T("q")) ? _T("yes") : _T("no")) << '\n';
230 if ( parser
.Found(_T("o"), &strVal
) )
231 s
<< _T("Output file:\t") << strVal
<< '\n';
232 if ( parser
.Found(_T("i"), &strVal
) )
233 s
<< _T("Input dir:\t") << strVal
<< '\n';
234 if ( parser
.Found(_T("s"), &lVal
) )
235 s
<< _T("Size:\t") << lVal
<< '\n';
236 if ( parser
.Found(_T("d"), &dt
) )
237 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
238 if ( parser
.Found(_T("project_name"), &strVal
) )
239 s
<< _T("Project:\t") << strVal
<< '\n';
244 #endif // wxUSE_CMDLINE_PARSER
246 static void TestCmdLineConvert()
248 static const wxChar
*cmdlines
[] =
251 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
252 _T("literal \\\" and \"\""),
255 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
257 const wxChar
*cmdline
= cmdlines
[n
];
258 wxPrintf(_T("Parsing: %s\n"), cmdline
);
259 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
261 size_t count
= args
.GetCount();
262 wxPrintf(_T("\targc = %u\n"), count
);
263 for ( size_t arg
= 0; arg
< count
; arg
++ )
265 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
270 #endif // TEST_CMDLINE
272 // ----------------------------------------------------------------------------
274 // ----------------------------------------------------------------------------
281 static const wxChar
*ROOTDIR
= _T("/");
282 static const wxChar
*TESTDIR
= _T("/usr/local/share");
283 #elif defined(__WXMSW__)
284 static const wxChar
*ROOTDIR
= _T("c:\\");
285 static const wxChar
*TESTDIR
= _T("d:\\");
287 #error "don't know where the root directory is"
290 static void TestDirEnumHelper(wxDir
& dir
,
291 int flags
= wxDIR_DEFAULT
,
292 const wxString
& filespec
= wxEmptyString
)
296 if ( !dir
.IsOpened() )
299 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
302 wxPrintf(_T("\t%s\n"), filename
.c_str());
304 cont
= dir
.GetNext(&filename
);
310 static void TestDirEnum()
312 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
314 wxString cwd
= wxGetCwd();
315 if ( !wxDir::Exists(cwd
) )
317 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
322 if ( !dir
.IsOpened() )
324 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
328 wxPuts(_T("Enumerating everything in current directory:"));
329 TestDirEnumHelper(dir
);
331 wxPuts(_T("Enumerating really everything in current directory:"));
332 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
334 wxPuts(_T("Enumerating object files in current directory:"));
335 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o*");
337 wxPuts(_T("Enumerating directories in current directory:"));
338 TestDirEnumHelper(dir
, wxDIR_DIRS
);
340 wxPuts(_T("Enumerating files in current directory:"));
341 TestDirEnumHelper(dir
, wxDIR_FILES
);
343 wxPuts(_T("Enumerating files including hidden in current directory:"));
344 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
348 wxPuts(_T("Enumerating everything in root directory:"));
349 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
351 wxPuts(_T("Enumerating directories in root directory:"));
352 TestDirEnumHelper(dir
, wxDIR_DIRS
);
354 wxPuts(_T("Enumerating files in root directory:"));
355 TestDirEnumHelper(dir
, wxDIR_FILES
);
357 wxPuts(_T("Enumerating files including hidden in root directory:"));
358 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
360 wxPuts(_T("Enumerating files in non existing directory:"));
361 wxDir
dirNo("nosuchdir");
362 TestDirEnumHelper(dirNo
);
365 class DirPrintTraverser
: public wxDirTraverser
368 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
370 return wxDIR_CONTINUE
;
373 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
375 wxString path
, name
, ext
;
376 wxSplitPath(dirname
, &path
, &name
, &ext
);
379 name
<< _T('.') << ext
;
382 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
384 if ( wxIsPathSeparator(*p
) )
388 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
390 return wxDIR_CONTINUE
;
394 static void TestDirTraverse()
396 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
400 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
401 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
404 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
405 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
408 // enum again with custom traverser
409 wxPuts(_T("Now enumerating directories:"));
411 DirPrintTraverser traverser
;
412 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
415 static void TestDirExists()
417 wxPuts(_T("*** Testing wxDir::Exists() ***"));
419 static const wxChar
*dirnames
[] =
422 #if defined(__WXMSW__)
425 _T("\\\\share\\file"),
429 _T("c:\\autoexec.bat"),
430 #elif defined(__UNIX__)
439 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
441 wxPrintf(_T("%-40s: %s\n"),
443 wxDir::Exists(dirnames
[n
]) ? _T("exists")
444 : _T("doesn't exist"));
450 // ----------------------------------------------------------------------------
452 // ----------------------------------------------------------------------------
454 #ifdef TEST_DLLLOADER
456 #include "wx/dynlib.h"
458 static void TestDllLoad()
460 #if defined(__WXMSW__)
461 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
462 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
463 #elif defined(__UNIX__)
464 // weird: using just libc.so does *not* work!
465 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
466 static const wxChar
*FUNC_NAME
= _T("strlen");
468 #error "don't know how to test wxDllLoader on this platform"
471 wxPuts(_T("*** testing wxDllLoader ***\n"));
473 wxDynamicLibrary
lib(LIB_NAME
);
474 if ( !lib
.IsLoaded() )
476 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
480 typedef int (*wxStrlenType
)(const char *);
481 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
484 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
485 FUNC_NAME
, LIB_NAME
);
489 if ( pfnStrlen("foo") != 3 )
491 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
495 wxPuts(_T("... ok"));
501 #endif // TEST_DLLLOADER
503 // ----------------------------------------------------------------------------
505 // ----------------------------------------------------------------------------
509 #include "wx/utils.h"
511 static wxString
MyGetEnv(const wxString
& var
)
514 if ( !wxGetEnv(var
, &val
) )
517 val
= wxString(_T('\'')) + val
+ _T('\'');
522 static void TestEnvironment()
524 const wxChar
*var
= _T("wxTestVar");
526 wxPuts(_T("*** testing environment access functions ***"));
528 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
529 wxSetEnv(var
, _T("value for wxTestVar"));
530 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
531 wxSetEnv(var
, _T("another value"));
532 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
534 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
535 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
538 #endif // TEST_ENVIRON
540 // ----------------------------------------------------------------------------
542 // ----------------------------------------------------------------------------
546 #include "wx/utils.h"
548 static void TestExecute()
550 wxPuts(_T("*** testing wxExecute ***"));
553 #define COMMAND "cat -n ../../Makefile" // "echo hi"
554 #define SHELL_COMMAND "echo hi from shell"
555 #define REDIRECT_COMMAND COMMAND // "date"
556 #elif defined(__WXMSW__)
557 #define COMMAND "command.com /c echo hi"
558 #define SHELL_COMMAND "echo hi"
559 #define REDIRECT_COMMAND COMMAND
561 #error "no command to exec"
564 wxPrintf(_T("Testing wxShell: "));
566 if ( wxShell(SHELL_COMMAND
) )
569 wxPuts(_T("ERROR."));
571 wxPrintf(_T("Testing wxExecute: "));
573 if ( wxExecute(COMMAND
, true /* sync */) == 0 )
576 wxPuts(_T("ERROR."));
578 #if 0 // no, it doesn't work (yet?)
579 wxPrintf(_T("Testing async wxExecute: "));
581 if ( wxExecute(COMMAND
) != 0 )
582 wxPuts(_T("Ok (command launched)."));
584 wxPuts(_T("ERROR."));
587 wxPrintf(_T("Testing wxExecute with redirection:\n"));
588 wxArrayString output
;
589 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
591 wxPuts(_T("ERROR."));
595 size_t count
= output
.GetCount();
596 for ( size_t n
= 0; n
< count
; n
++ )
598 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
605 #endif // TEST_EXECUTE
607 // ----------------------------------------------------------------------------
609 // ----------------------------------------------------------------------------
614 #include "wx/ffile.h"
615 #include "wx/textfile.h"
617 static void TestFileRead()
619 wxPuts(_T("*** wxFile read test ***"));
621 wxFile
file(_T("testdata.fc"));
622 if ( file
.IsOpened() )
624 wxPrintf(_T("File length: %lu\n"), file
.Length());
626 wxPuts(_T("File dump:\n----------"));
628 static const off_t len
= 1024;
632 off_t nRead
= file
.Read(buf
, len
);
633 if ( nRead
== wxInvalidOffset
)
635 wxPrintf(_T("Failed to read the file."));
639 fwrite(buf
, nRead
, 1, stdout
);
645 wxPuts(_T("----------"));
649 wxPrintf(_T("ERROR: can't open test file.\n"));
655 static void TestTextFileRead()
657 wxPuts(_T("*** wxTextFile read test ***"));
659 wxTextFile
file(_T("testdata.fc"));
662 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
663 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
667 wxPuts(_T("\nDumping the entire file:"));
668 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
670 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
672 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
674 wxPuts(_T("\nAnd now backwards:"));
675 for ( s
= file
.GetLastLine();
676 file
.GetCurrentLine() != 0;
677 s
= file
.GetPrevLine() )
679 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
681 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
685 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
691 static void TestFileCopy()
693 wxPuts(_T("*** Testing wxCopyFile ***"));
695 static const wxChar
*filename1
= _T("testdata.fc");
696 static const wxChar
*filename2
= _T("test2");
697 if ( !wxCopyFile(filename1
, filename2
) )
699 wxPuts(_T("ERROR: failed to copy file"));
703 wxFFile
f1(filename1
, "rb"),
706 if ( !f1
.IsOpened() || !f2
.IsOpened() )
708 wxPuts(_T("ERROR: failed to open file(s)"));
713 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
715 wxPuts(_T("ERROR: failed to read file(s)"));
719 if ( (s1
.length() != s2
.length()) ||
720 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
722 wxPuts(_T("ERROR: copy error!"));
726 wxPuts(_T("File was copied ok."));
732 if ( !wxRemoveFile(filename2
) )
734 wxPuts(_T("ERROR: failed to remove the file"));
742 // ----------------------------------------------------------------------------
744 // ----------------------------------------------------------------------------
748 #include "wx/confbase.h"
749 #include "wx/fileconf.h"
751 static const struct FileConfTestData
753 const wxChar
*name
; // value name
754 const wxChar
*value
; // the value from the file
757 { _T("value1"), _T("one") },
758 { _T("value2"), _T("two") },
759 { _T("novalue"), _T("default") },
762 static void TestFileConfRead()
764 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
766 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
767 _T("testdata.fc"), wxEmptyString
,
768 wxCONFIG_USE_RELATIVE_PATH
);
770 // test simple reading
771 wxPuts(_T("\nReading config file:"));
772 wxString
defValue(_T("default")), value
;
773 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
775 const FileConfTestData
& data
= fcTestData
[n
];
776 value
= fileconf
.Read(data
.name
, defValue
);
777 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
778 if ( value
== data
.value
)
784 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
788 // test enumerating the entries
789 wxPuts(_T("\nEnumerating all root entries:"));
792 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
795 wxPrintf(_T("\t%s = %s\n"),
797 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
799 cont
= fileconf
.GetNextEntry(name
, dummy
);
803 #endif // TEST_FILECONF
805 // ----------------------------------------------------------------------------
807 // ----------------------------------------------------------------------------
811 #include "wx/filename.h"
813 static void DumpFileName(const wxFileName
& fn
)
815 wxString full
= fn
.GetFullPath();
817 wxString vol
, path
, name
, ext
;
818 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
820 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
821 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
823 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
824 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
825 path
.c_str(), name
.c_str(), ext
.c_str());
827 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
828 wxPrintf(_T("with volume: \t'%s'\n"),
829 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
830 wxPrintf(_T("with separator:\t'%s'\n"),
831 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
832 wxPrintf(_T("with both: \t'%s'\n"),
833 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
835 wxPuts(_T("The directories in the path are:"));
836 wxArrayString dirs
= fn
.GetDirs();
837 size_t count
= dirs
.GetCount();
838 for ( size_t n
= 0; n
< count
; n
++ )
840 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
844 static struct FileNameInfo
846 const wxChar
*fullname
;
847 const wxChar
*volume
;
856 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), true, wxPATH_UNIX
},
857 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), true, wxPATH_UNIX
},
858 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), true, wxPATH_UNIX
},
859 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), false, wxPATH_UNIX
},
860 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), false, wxPATH_UNIX
},
861 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), true, wxPATH_UNIX
},
862 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), true, wxPATH_UNIX
},
863 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), false, wxPATH_UNIX
},
864 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), true, wxPATH_UNIX
},
866 // Windows file names
867 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), false, wxPATH_DOS
},
868 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), false, wxPATH_DOS
},
869 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), false, wxPATH_DOS
},
870 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), true, wxPATH_DOS
},
871 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), true, wxPATH_DOS
},
872 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), true, wxPATH_DOS
},
873 { _T("\\\\server\\dir\\foo.bar"), _T("server"), _T("\\dir"), _T("foo"), _T("bar"), true, wxPATH_DOS
},
875 // wxFileName support for Mac file names is broken currently
878 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), true, wxPATH_MAC
},
879 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), true, wxPATH_MAC
},
880 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), true, wxPATH_MAC
},
881 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), false, wxPATH_MAC
},
882 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), false, wxPATH_MAC
},
883 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), false, wxPATH_MAC
},
887 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), true, wxPATH_VMS
},
888 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), false, wxPATH_VMS
},
891 static void TestFileNameConstruction()
893 wxPuts(_T("*** testing wxFileName construction ***"));
895 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
897 const FileNameInfo
& fni
= filenames
[n
];
899 wxFileName
fn(fni
.fullname
, fni
.format
);
901 wxString fullname
= fn
.GetFullPath(fni
.format
);
902 if ( fullname
!= fni
.fullname
)
904 wxPrintf(_T("ERROR: fullname should be '%s'\n"), fni
.fullname
);
907 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
908 wxPrintf(_T("'%s' is %s (%s)\n\t"),
910 isAbsolute
? "absolute" : "relative",
911 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
913 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
915 wxPuts(_T("ERROR (couldn't be normalized)"));
919 wxPrintf(_T("normalized: '%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
926 static void TestFileNameSplit()
928 wxPuts(_T("*** testing wxFileName splitting ***"));
930 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
932 const FileNameInfo
& fni
= filenames
[n
];
933 wxString volume
, path
, name
, ext
;
934 wxFileName::SplitPath(fni
.fullname
,
935 &volume
, &path
, &name
, &ext
, fni
.format
);
937 wxPrintf(_T("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'"),
939 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
941 if ( volume
!= fni
.volume
)
942 wxPrintf(_T(" (ERROR: volume = '%s')"), fni
.volume
);
943 if ( path
!= fni
.path
)
944 wxPrintf(_T(" (ERROR: path = '%s')"), fni
.path
);
945 if ( name
!= fni
.name
)
946 wxPrintf(_T(" (ERROR: name = '%s')"), fni
.name
);
947 if ( ext
!= fni
.ext
)
948 wxPrintf(_T(" (ERROR: ext = '%s')"), fni
.ext
);
954 static void TestFileNameTemp()
956 wxPuts(_T("*** testing wxFileName temp file creation ***"));
958 static const wxChar
*tmpprefixes
[] =
966 _T("/tmp/foo/bar"), // this one must be an error
970 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
972 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
975 // "error" is not in upper case because it may be ok
976 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
980 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
981 tmpprefixes
[n
], path
.c_str());
983 if ( !wxRemoveFile(path
) )
985 wxLogWarning(_T("Failed to remove temp file '%s'"),
992 static void TestFileNameMakeRelative()
994 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
996 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
998 const FileNameInfo
& fni
= filenames
[n
];
1000 wxFileName
fn(fni
.fullname
, fni
.format
);
1002 // choose the base dir of the same format
1004 switch ( fni
.format
)
1016 // TODO: I don't know how this is supposed to work there
1019 case wxPATH_NATIVE
: // make gcc happy
1021 wxFAIL_MSG( "unexpected path format" );
1024 wxPrintf(_T("'%s' relative to '%s': "),
1025 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
1027 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
1029 wxPuts(_T("unchanged"));
1033 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
1038 static void TestFileNameMakeAbsolute()
1040 wxPuts(_T("*** testing wxFileName::MakeAbsolute() ***"));
1042 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1044 const FileNameInfo
& fni
= filenames
[n
];
1045 wxFileName
fn(fni
.fullname
, fni
.format
);
1047 wxPrintf(_T("'%s' absolutized: "),
1048 fn
.GetFullPath(fni
.format
).c_str());
1050 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
1056 static void TestFileNameComparison()
1061 static void TestFileNameOperations()
1066 static void TestFileNameCwd()
1071 #endif // TEST_FILENAME
1073 // ----------------------------------------------------------------------------
1074 // wxFileName time functions
1075 // ----------------------------------------------------------------------------
1077 #ifdef TEST_FILETIME
1079 #include <wx/filename.h>
1080 #include <wx/datetime.h>
1082 static void TestFileGetTimes()
1084 wxFileName
fn(_T("testdata.fc"));
1086 wxDateTime dtAccess
, dtMod
, dtCreate
;
1087 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1089 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1093 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1095 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1096 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1097 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1098 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1102 static void TestFileSetTimes()
1104 wxFileName
fn(_T("testdata.fc"));
1108 wxPrintf(_T("ERROR: Touch() failed.\n"));
1112 #endif // TEST_FILETIME
1114 // ----------------------------------------------------------------------------
1116 // ----------------------------------------------------------------------------
1120 #include "wx/hash.h"
1124 Foo(int n_
) { n
= n_
; count
++; }
1129 static size_t count
;
1132 size_t Foo::count
= 0;
1134 WX_DECLARE_LIST(Foo
, wxListFoos
);
1135 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1137 #include "wx/listimpl.cpp"
1139 WX_DEFINE_LIST(wxListFoos
);
1141 static void TestHash()
1143 wxPuts(_T("*** Testing wxHashTable ***\n"));
1147 hash
.DeleteContents(true);
1149 wxPrintf(_T("Hash created: %u foos in hash, %u foos totally\n"),
1150 hash
.GetCount(), Foo::count
);
1152 static const int hashTestData
[] =
1154 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1158 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1160 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1163 wxPrintf(_T("Hash filled: %u foos in hash, %u foos totally\n"),
1164 hash
.GetCount(), Foo::count
);
1166 wxPuts(_T("Hash access test:"));
1167 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1169 wxPrintf(_T("\tGetting element with key %d, value %d: "),
1170 hashTestData
[n
], n
);
1171 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1174 wxPrintf(_T("ERROR, not found.\n"));
1178 wxPrintf(_T("%d (%s)\n"), foo
->n
,
1179 (size_t)foo
->n
== n
? "ok" : "ERROR");
1183 wxPrintf(_T("\nTrying to get an element not in hash: "));
1185 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1187 wxPuts(_T("ERROR: found!"));
1191 wxPuts(_T("ok (not found)"));
1195 wxPrintf(_T("Hash destroyed: %u foos left\n"), Foo::count
);
1200 // ----------------------------------------------------------------------------
1202 // ----------------------------------------------------------------------------
1206 #include "wx/hashmap.h"
1208 // test compilation of basic map types
1209 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1210 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1211 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1212 myUnsignedHashMap
);
1213 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1215 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1217 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1219 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1223 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1224 // myStringHashMap );
1225 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1227 typedef myStringHashMap::iterator Itor
;
1229 static void TestHashMap()
1231 wxPuts(_T("*** Testing wxHashMap ***\n"));
1232 myStringHashMap
sh(0); // as small as possible
1235 const size_t count
= 10000;
1237 // init with some data
1238 for( i
= 0; i
< count
; ++i
)
1240 buf
.Printf(wxT("%d"), i
);
1241 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1244 // test that insertion worked
1245 if( sh
.size() != count
)
1247 wxPrintf(_T("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n"), sh
.size(), count
);
1250 for( i
= 0; i
< count
; ++i
)
1252 buf
.Printf(wxT("%d"), i
);
1253 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1255 wxPrintf(_T("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n"));
1260 // check that iterators work
1262 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1266 wxPrintf(_T("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n"));
1270 if( it
->second
!= sh
[it
->first
] )
1272 wxPrintf(_T("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n"));
1277 if( sh
.size() != i
)
1279 wxPrintf(_T("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n"), i
, count
);
1282 // test copy ctor, assignment operator
1283 myStringHashMap
h1( sh
), h2( 0 );
1286 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1288 if( h1
[it
->first
] != it
->second
)
1290 wxPrintf(_T("*** ERROR: COPY CTOR BROKEN %s ***\n"), it
->first
.c_str());
1293 if( h2
[it
->first
] != it
->second
)
1295 wxPrintf(_T("*** ERROR: OPERATOR= BROKEN %s ***\n"), it
->first
.c_str());
1300 for( i
= 0; i
< count
; ++i
)
1302 buf
.Printf(wxT("%d"), i
);
1303 size_t sz
= sh
.size();
1305 // test find() and erase(it)
1308 it
= sh
.find( buf
);
1309 if( it
!= sh
.end() )
1313 if( sh
.find( buf
) != sh
.end() )
1315 wxPrintf(_T("*** ERROR: FOUND DELETED ELEMENT %u ***\n"), i
);
1319 wxPrintf(_T("*** ERROR: CANT FIND ELEMENT %u ***\n"), i
);
1324 size_t c
= sh
.erase( buf
);
1326 wxPrintf(_T("*** ERROR: SHOULD RETURN 1 ***\n"));
1328 if( sh
.find( buf
) != sh
.end() )
1330 wxPrintf(_T("*** ERROR: FOUND DELETED ELEMENT %u ***\n"), i
);
1334 // count should decrease
1335 if( sh
.size() != sz
- 1 )
1337 wxPrintf(_T("*** ERROR: COUNT DID NOT DECREASE ***\n"));
1341 wxPrintf(_T("*** Finished testing wxHashMap ***\n"));
1344 #endif // TEST_HASHMAP
1346 // ----------------------------------------------------------------------------
1348 // ----------------------------------------------------------------------------
1352 #include "wx/list.h"
1354 WX_DECLARE_LIST(Bar
, wxListBars
);
1355 #include "wx/listimpl.cpp"
1356 WX_DEFINE_LIST(wxListBars
);
1358 static void TestListCtor()
1360 wxPuts(_T("*** Testing wxList construction ***\n"));
1364 list1
.Append(new Bar(_T("first")));
1365 list1
.Append(new Bar(_T("second")));
1367 wxPrintf(_T("After 1st list creation: %u objects in the list, %u objects total.\n"),
1368 list1
.GetCount(), Bar::GetNumber());
1373 wxPrintf(_T("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n"),
1374 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1376 list1
.DeleteContents(true);
1379 wxPrintf(_T("After list destruction: %u objects left.\n"), Bar::GetNumber());
1384 // ----------------------------------------------------------------------------
1386 // ----------------------------------------------------------------------------
1390 #include "wx/intl.h"
1391 #include "wx/utils.h" // for wxSetEnv
1393 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1395 // find the name of the language from its value
1396 static const wxChar
*GetLangName(int lang
)
1398 static const wxChar
*languageNames
[] =
1408 _T("ARABIC_ALGERIA"),
1409 _T("ARABIC_BAHRAIN"),
1412 _T("ARABIC_JORDAN"),
1413 _T("ARABIC_KUWAIT"),
1414 _T("ARABIC_LEBANON"),
1416 _T("ARABIC_MOROCCO"),
1419 _T("ARABIC_SAUDI_ARABIA"),
1422 _T("ARABIC_TUNISIA"),
1429 _T("AZERI_CYRILLIC"),
1444 _T("CHINESE_SIMPLIFIED"),
1445 _T("CHINESE_TRADITIONAL"),
1446 _T("CHINESE_HONGKONG"),
1447 _T("CHINESE_MACAU"),
1448 _T("CHINESE_SINGAPORE"),
1449 _T("CHINESE_TAIWAN"),
1455 _T("DUTCH_BELGIAN"),
1459 _T("ENGLISH_AUSTRALIA"),
1460 _T("ENGLISH_BELIZE"),
1461 _T("ENGLISH_BOTSWANA"),
1462 _T("ENGLISH_CANADA"),
1463 _T("ENGLISH_CARIBBEAN"),
1464 _T("ENGLISH_DENMARK"),
1466 _T("ENGLISH_JAMAICA"),
1467 _T("ENGLISH_NEW_ZEALAND"),
1468 _T("ENGLISH_PHILIPPINES"),
1469 _T("ENGLISH_SOUTH_AFRICA"),
1470 _T("ENGLISH_TRINIDAD"),
1471 _T("ENGLISH_ZIMBABWE"),
1479 _T("FRENCH_BELGIAN"),
1480 _T("FRENCH_CANADIAN"),
1481 _T("FRENCH_LUXEMBOURG"),
1482 _T("FRENCH_MONACO"),
1488 _T("GERMAN_AUSTRIAN"),
1489 _T("GERMAN_BELGIUM"),
1490 _T("GERMAN_LIECHTENSTEIN"),
1491 _T("GERMAN_LUXEMBOURG"),
1509 _T("ITALIAN_SWISS"),
1514 _T("KASHMIRI_INDIA"),
1532 _T("MALAY_BRUNEI_DARUSSALAM"),
1533 _T("MALAY_MALAYSIA"),
1543 _T("NORWEGIAN_BOKMAL"),
1544 _T("NORWEGIAN_NYNORSK"),
1551 _T("PORTUGUESE_BRAZILIAN"),
1554 _T("RHAETO_ROMANCE"),
1557 _T("RUSSIAN_UKRAINE"),
1563 _T("SERBIAN_CYRILLIC"),
1564 _T("SERBIAN_LATIN"),
1565 _T("SERBO_CROATIAN"),
1576 _T("SPANISH_ARGENTINA"),
1577 _T("SPANISH_BOLIVIA"),
1578 _T("SPANISH_CHILE"),
1579 _T("SPANISH_COLOMBIA"),
1580 _T("SPANISH_COSTA_RICA"),
1581 _T("SPANISH_DOMINICAN_REPUBLIC"),
1582 _T("SPANISH_ECUADOR"),
1583 _T("SPANISH_EL_SALVADOR"),
1584 _T("SPANISH_GUATEMALA"),
1585 _T("SPANISH_HONDURAS"),
1586 _T("SPANISH_MEXICAN"),
1587 _T("SPANISH_MODERN"),
1588 _T("SPANISH_NICARAGUA"),
1589 _T("SPANISH_PANAMA"),
1590 _T("SPANISH_PARAGUAY"),
1592 _T("SPANISH_PUERTO_RICO"),
1593 _T("SPANISH_URUGUAY"),
1595 _T("SPANISH_VENEZUELA"),
1599 _T("SWEDISH_FINLAND"),
1617 _T("URDU_PAKISTAN"),
1619 _T("UZBEK_CYRILLIC"),
1632 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1633 return languageNames
[lang
];
1635 return _T("INVALID");
1638 static void TestDefaultLang()
1640 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1642 static const wxChar
*langStrings
[] =
1644 NULL
, // system default
1651 _T("de_DE.iso88591"),
1653 _T("?"), // invalid lang spec
1654 _T("klingonese"), // I bet on some systems it does exist...
1657 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1658 wxLocale::GetSystemEncodingName().c_str(),
1659 wxLocale::GetSystemEncoding());
1661 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1663 const wxChar
*langStr
= langStrings
[n
];
1666 // FIXME: this doesn't do anything at all under Windows, we need
1667 // to create a new wxLocale!
1668 wxSetEnv(_T("LC_ALL"), langStr
);
1671 int lang
= gs_localeDefault
.GetSystemLanguage();
1672 wxPrintf(_T("Locale for '%s' is %s.\n"),
1673 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1677 #endif // TEST_LOCALE
1679 // ----------------------------------------------------------------------------
1681 // ----------------------------------------------------------------------------
1685 #include "wx/mimetype.h"
1687 static void TestMimeEnum()
1689 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1691 wxArrayString mimetypes
;
1693 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1695 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1700 for ( size_t n
= 0; n
< count
; n
++ )
1702 wxFileType
*filetype
=
1703 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1706 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1707 mimetypes
[n
].c_str());
1711 filetype
->GetDescription(&desc
);
1712 filetype
->GetExtensions(exts
);
1714 filetype
->GetIcon(NULL
);
1717 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1720 extsAll
<< _T(", ");
1724 wxPrintf(_T("\t%s: %s (%s)\n"),
1725 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1731 static void TestMimeOverride()
1733 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1735 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1736 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1738 if ( wxFile::Exists(mailcap
) )
1739 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1741 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1743 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1746 if ( wxFile::Exists(mimetypes
) )
1747 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1749 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1751 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1757 static void TestMimeFilename()
1759 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1761 static const wxChar
*filenames
[] =
1769 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1771 const wxString fname
= filenames
[n
];
1772 wxString ext
= fname
.AfterLast(_T('.'));
1773 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1776 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1781 if ( !ft
->GetDescription(&desc
) )
1782 desc
= _T("<no description>");
1785 if ( !ft
->GetOpenCommand(&cmd
,
1786 wxFileType::MessageParameters(fname
, _T(""))) )
1787 cmd
= _T("<no command available>");
1789 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1791 wxPrintf(_T("To open %s (%s) do %s.\n"),
1792 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1801 static void TestMimeAssociate()
1803 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1805 wxFileTypeInfo
ftInfo(
1806 _T("application/x-xyz"),
1807 _T("xyzview '%s'"), // open cmd
1808 _T(""), // print cmd
1809 _T("XYZ File"), // description
1810 _T(".xyz"), // extensions
1811 NULL
// end of extensions
1813 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1815 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1818 wxPuts(_T("ERROR: failed to create association!"));
1822 // TODO: read it back
1831 // ----------------------------------------------------------------------------
1832 // misc information functions
1833 // ----------------------------------------------------------------------------
1835 #ifdef TEST_INFO_FUNCTIONS
1837 #include "wx/utils.h"
1839 static void TestDiskInfo()
1841 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1845 wxChar pathname
[128];
1846 wxPrintf(_T("\nEnter a directory name: "));
1847 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1850 // kill the last '\n'
1851 pathname
[wxStrlen(pathname
) - 1] = 0;
1853 wxLongLong total
, free
;
1854 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1856 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1860 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1861 (total
/ 1024).ToString().c_str(),
1862 (free
/ 1024).ToString().c_str(),
1868 static void TestOsInfo()
1870 wxPuts(_T("*** Testing OS info functions ***\n"));
1873 wxGetOsVersion(&major
, &minor
);
1874 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1875 wxGetOsDescription().c_str(), major
, minor
);
1877 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1879 wxPrintf(_T("Host name is %s (%s).\n"),
1880 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1885 static void TestUserInfo()
1887 wxPuts(_T("*** Testing user info functions ***\n"));
1889 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1890 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1891 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1892 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1897 #endif // TEST_INFO_FUNCTIONS
1899 // ----------------------------------------------------------------------------
1901 // ----------------------------------------------------------------------------
1903 #ifdef TEST_LONGLONG
1905 #include "wx/longlong.h"
1906 #include "wx/timer.h"
1908 // make a 64 bit number from 4 16 bit ones
1909 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1911 // get a random 64 bit number
1912 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1914 static const long testLongs
[] =
1925 #if wxUSE_LONGLONG_WX
1926 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1927 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1928 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1929 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1930 #endif // wxUSE_LONGLONG_WX
1932 static void TestSpeed()
1934 static const long max
= 100000000;
1941 for ( n
= 0; n
< max
; n
++ )
1946 wxPrintf(_T("Summing longs took %ld milliseconds.\n"), sw
.Time());
1949 #if wxUSE_LONGLONG_NATIVE
1954 for ( n
= 0; n
< max
; n
++ )
1959 wxPrintf(_T("Summing wxLongLong_t took %ld milliseconds.\n"), sw
.Time());
1961 #endif // wxUSE_LONGLONG_NATIVE
1967 for ( n
= 0; n
< max
; n
++ )
1972 wxPrintf(_T("Summing wxLongLongs took %ld milliseconds.\n"), sw
.Time());
1976 static void TestLongLongConversion()
1978 wxPuts(_T("*** Testing wxLongLong conversions ***\n"));
1982 for ( size_t n
= 0; n
< 100000; n
++ )
1986 #if wxUSE_LONGLONG_NATIVE
1987 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1989 wxASSERT_MSG( a
== b
, "conversions failure" );
1991 wxPuts(_T("Can't do it without native long long type, test skipped."));
1994 #endif // wxUSE_LONGLONG_NATIVE
1996 if ( !(nTested
% 1000) )
2005 wxPuts(_T(" done!"));
2008 static void TestMultiplication()
2010 wxPuts(_T("*** Testing wxLongLong multiplication ***\n"));
2014 for ( size_t n
= 0; n
< 100000; n
++ )
2019 #if wxUSE_LONGLONG_NATIVE
2020 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
2021 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
2023 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
2024 #else // !wxUSE_LONGLONG_NATIVE
2025 wxPuts(_T("Can't do it without native long long type, test skipped."));
2028 #endif // wxUSE_LONGLONG_NATIVE
2030 if ( !(nTested
% 1000) )
2039 wxPuts(_T(" done!"));
2042 static void TestDivision()
2044 wxPuts(_T("*** Testing wxLongLong division ***\n"));
2048 for ( size_t n
= 0; n
< 100000; n
++ )
2050 // get a random wxLongLong (shifting by 12 the MSB ensures that the
2051 // multiplication will not overflow)
2052 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
2054 // get a random (but non null) long (not wxLongLong for now) to divide
2066 #if wxUSE_LONGLONG_NATIVE
2067 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
2069 wxLongLongNative p
= m
/ l
, s
= m
% l
;
2070 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
2071 #else // !wxUSE_LONGLONG_NATIVE
2072 // verify the result
2073 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
2074 #endif // wxUSE_LONGLONG_NATIVE
2076 if ( !(nTested
% 1000) )
2085 wxPuts(_T(" done!"));
2088 static void TestAddition()
2090 wxPuts(_T("*** Testing wxLongLong addition ***\n"));
2094 for ( size_t n
= 0; n
< 100000; n
++ )
2100 #if wxUSE_LONGLONG_NATIVE
2101 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2102 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2103 "addition failure" );
2104 #else // !wxUSE_LONGLONG_NATIVE
2105 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2106 #endif // wxUSE_LONGLONG_NATIVE
2108 if ( !(nTested
% 1000) )
2117 wxPuts(_T(" done!"));
2120 static void TestBitOperations()
2122 wxPuts(_T("*** Testing wxLongLong bit operation ***\n"));
2126 for ( size_t n
= 0; n
< 100000; n
++ )
2130 #if wxUSE_LONGLONG_NATIVE
2131 for ( size_t n
= 0; n
< 33; n
++ )
2134 #else // !wxUSE_LONGLONG_NATIVE
2135 wxPuts(_T("Can't do it without native long long type, test skipped."));
2138 #endif // wxUSE_LONGLONG_NATIVE
2140 if ( !(nTested
% 1000) )
2149 wxPuts(_T(" done!"));
2152 static void TestLongLongComparison()
2154 #if wxUSE_LONGLONG_WX
2155 wxPuts(_T("*** Testing wxLongLong comparison ***\n"));
2157 static const long ls
[2] =
2163 wxLongLongWx lls
[2];
2167 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2171 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2173 res
= lls
[m
] > testLongs
[n
];
2174 wxPrintf(_T("0x%lx > 0x%lx is %s (%s)\n"),
2175 ls
[m
], testLongs
[n
], res
? "true" : "false",
2176 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2178 res
= lls
[m
] < testLongs
[n
];
2179 wxPrintf(_T("0x%lx < 0x%lx is %s (%s)\n"),
2180 ls
[m
], testLongs
[n
], res
? "true" : "false",
2181 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2183 res
= lls
[m
] == testLongs
[n
];
2184 wxPrintf(_T("0x%lx == 0x%lx is %s (%s)\n"),
2185 ls
[m
], testLongs
[n
], res
? "true" : "false",
2186 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2189 #endif // wxUSE_LONGLONG_WX
2192 static void TestLongLongToString()
2194 wxPuts(_T("*** Testing wxLongLong::ToString() ***\n"));
2196 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2198 wxLongLong ll
= testLongs
[n
];
2199 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2202 wxLongLong
ll(0x12345678, 0x87654321);
2203 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2206 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2209 static void TestLongLongPrintf()
2211 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2213 #ifdef wxLongLongFmtSpec
2214 wxLongLong ll
= wxLL(0x1234567890abcdef);
2215 wxString s
= wxString::Format(_T("%") wxLongLongFmtSpec
_T("x"), ll
);
2216 wxPrintf(_T("0x1234567890abcdef -> %s (%s)\n"),
2217 s
.c_str(), s
== _T("1234567890abcdef") ? _T("ok") : _T("ERROR"));
2218 #else // !wxLongLongFmtSpec
2219 #error "wxLongLongFmtSpec not defined for this compiler/platform"
2226 #endif // TEST_LONGLONG
2228 // ----------------------------------------------------------------------------
2230 // ----------------------------------------------------------------------------
2232 #ifdef TEST_PATHLIST
2235 #define CMD_IN_PATH _T("ls")
2237 #define CMD_IN_PATH _T("command.com")
2240 static void TestPathList()
2242 wxPuts(_T("*** Testing wxPathList ***\n"));
2244 wxPathList pathlist
;
2245 pathlist
.AddEnvList(_T("PATH"));
2246 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
2249 wxPrintf(_T("ERROR: command not found in the path.\n"));
2253 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
2257 #endif // TEST_PATHLIST
2259 // ----------------------------------------------------------------------------
2260 // regular expressions
2261 // ----------------------------------------------------------------------------
2265 #include "wx/regex.h"
2267 static void TestRegExCompile()
2269 wxPuts(_T("*** Testing RE compilation ***\n"));
2271 static struct RegExCompTestData
2273 const wxChar
*pattern
;
2275 } regExCompTestData
[] =
2277 { _T("foo"), true },
2278 { _T("foo("), false },
2279 { _T("foo(bar"), false },
2280 { _T("foo(bar)"), true },
2281 { _T("foo["), false },
2282 { _T("foo[bar"), false },
2283 { _T("foo[bar]"), true },
2284 { _T("foo{"), true },
2285 { _T("foo{1"), false },
2286 { _T("foo{bar"), true },
2287 { _T("foo{1}"), true },
2288 { _T("foo{1,2}"), true },
2289 { _T("foo{bar}"), true },
2290 { _T("foo*"), true },
2291 { _T("foo**"), false },
2292 { _T("foo+"), true },
2293 { _T("foo++"), false },
2294 { _T("foo?"), true },
2295 { _T("foo??"), false },
2296 { _T("foo?+"), false },
2300 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2302 const RegExCompTestData
& data
= regExCompTestData
[n
];
2303 bool ok
= re
.Compile(data
.pattern
);
2305 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2307 ok
? _T("") : _T("not "),
2308 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2312 static void TestRegExMatch()
2314 wxPuts(_T("*** Testing RE matching ***\n"));
2316 static struct RegExMatchTestData
2318 const wxChar
*pattern
;
2321 } regExMatchTestData
[] =
2323 { _T("foo"), _T("bar"), false },
2324 { _T("foo"), _T("foobar"), true },
2325 { _T("^foo"), _T("foobar"), true },
2326 { _T("^foo"), _T("barfoo"), false },
2327 { _T("bar$"), _T("barbar"), true },
2328 { _T("bar$"), _T("barbar "), false },
2331 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2333 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2335 wxRegEx
re(data
.pattern
);
2336 bool ok
= re
.Matches(data
.text
);
2338 wxPrintf(_T("'%s' %s %s (%s)\n"),
2340 ok
? _T("matches") : _T("doesn't match"),
2342 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2346 static void TestRegExSubmatch()
2348 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2350 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2351 if ( !re
.IsValid() )
2353 wxPuts(_T("ERROR: compilation failed."));
2357 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2359 if ( !re
.Matches(text
) )
2361 wxPuts(_T("ERROR: match expected."));
2365 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2367 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2368 re
.GetMatch(text
, 3).c_str(),
2369 re
.GetMatch(text
, 2).c_str(),
2370 re
.GetMatch(text
, 4).c_str(),
2371 re
.GetMatch(text
, 1).c_str());
2375 static void TestRegExReplacement()
2377 wxPuts(_T("*** Testing RE replacement ***"));
2379 static struct RegExReplTestData
2383 const wxChar
*result
;
2385 } regExReplTestData
[] =
2387 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2388 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2389 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2390 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2391 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2392 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2393 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2396 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2397 wxRegEx
re(pattern
);
2399 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2401 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2403 const RegExReplTestData
& data
= regExReplTestData
[n
];
2405 wxString text
= data
.text
;
2406 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2408 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2409 data
.text
, data
.repl
,
2410 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2412 if ( text
== data
.result
&& nRepl
== data
.count
)
2418 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2419 data
.count
, data
.result
);
2424 static void TestRegExInteractive()
2426 wxPuts(_T("*** Testing RE interactively ***"));
2430 wxChar pattern
[128];
2431 wxPrintf(_T("\nEnter a pattern: "));
2432 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2435 // kill the last '\n'
2436 pattern
[wxStrlen(pattern
) - 1] = 0;
2439 if ( !re
.Compile(pattern
) )
2447 wxPrintf(_T("Enter text to match: "));
2448 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
2451 // kill the last '\n'
2452 text
[wxStrlen(text
) - 1] = 0;
2454 if ( !re
.Matches(text
) )
2456 wxPrintf(_T("No match.\n"));
2460 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
2463 for ( size_t n
= 1; ; n
++ )
2465 if ( !re
.GetMatch(&start
, &len
, n
) )
2470 wxPrintf(_T("Subexpr %u matched '%s'\n"),
2471 n
, wxString(text
+ start
, len
).c_str());
2478 #endif // TEST_REGEX
2480 // ----------------------------------------------------------------------------
2482 // ----------------------------------------------------------------------------
2492 static void TestDbOpen()
2500 // ----------------------------------------------------------------------------
2502 // ----------------------------------------------------------------------------
2505 NB: this stuff was taken from the glibc test suite and modified to build
2506 in wxWindows: if I read the copyright below properly, this shouldn't
2512 #ifdef wxTEST_PRINTF
2513 // use our functions from wxchar.cpp
2517 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
2518 // in the tests below
2519 int wxPrintf( const wxChar
*format
, ... );
2520 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
2523 #include "wx/longlong.h"
2527 static void rfg1 (void);
2528 static void rfg2 (void);
2532 fmtchk (const wxChar
*fmt
)
2534 (void) wxPrintf(_T("%s:\t`"), fmt
);
2535 (void) wxPrintf(fmt
, 0x12);
2536 (void) wxPrintf(_T("'\n"));
2540 fmtst1chk (const wxChar
*fmt
)
2542 (void) wxPrintf(_T("%s:\t`"), fmt
);
2543 (void) wxPrintf(fmt
, 4, 0x12);
2544 (void) wxPrintf(_T("'\n"));
2548 fmtst2chk (const wxChar
*fmt
)
2550 (void) wxPrintf(_T("%s:\t`"), fmt
);
2551 (void) wxPrintf(fmt
, 4, 4, 0x12);
2552 (void) wxPrintf(_T("'\n"));
2555 /* This page is covered by the following copyright: */
2557 /* (C) Copyright C E Chew
2559 * Feel free to copy, use and distribute this software provided:
2561 * 1. you do not pretend that you wrote it
2562 * 2. you leave this copyright notice intact.
2566 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
2573 /* Formatted Output Test
2575 * This exercises the output formatting code.
2583 wxChar
*prefix
= buf
;
2586 wxPuts(_T("\nFormatted output test"));
2587 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
2588 wxStrcpy(prefix
, _T("%"));
2589 for (i
= 0; i
< 2; i
++) {
2590 for (j
= 0; j
< 2; j
++) {
2591 for (k
= 0; k
< 2; k
++) {
2592 for (l
= 0; l
< 2; l
++) {
2593 wxStrcpy(prefix
, _T("%"));
2594 if (i
== 0) wxStrcat(prefix
, _T("-"));
2595 if (j
== 0) wxStrcat(prefix
, _T("+"));
2596 if (k
== 0) wxStrcat(prefix
, _T("#"));
2597 if (l
== 0) wxStrcat(prefix
, _T("0"));
2598 wxPrintf(_T("%5s |"), prefix
);
2599 wxStrcpy(tp
, prefix
);
2600 wxStrcat(tp
, _T("6d |"));
2602 wxStrcpy(tp
, prefix
);
2603 wxStrcat(tp
, _T("6o |"));
2605 wxStrcpy(tp
, prefix
);
2606 wxStrcat(tp
, _T("6x |"));
2608 wxStrcpy(tp
, prefix
);
2609 wxStrcat(tp
, _T("6X |"));
2611 wxStrcpy(tp
, prefix
);
2612 wxStrcat(tp
, _T("6u |"));
2619 wxPrintf(_T("%10s\n"), (wxChar
*) NULL
);
2620 wxPrintf(_T("%-10s\n"), (wxChar
*) NULL
);
2623 static void TestPrintf()
2625 static wxChar shortstr
[] = _T("Hi, Z.");
2626 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
2627 I am ready for my first lesson today.");
2632 fmtchk(_T("%4.4x"));
2633 fmtchk(_T("%04.4x"));
2634 fmtchk(_T("%4.3x"));
2635 fmtchk(_T("%04.3x"));
2637 fmtst1chk(_T("%.*x"));
2638 fmtst1chk(_T("%0*x"));
2639 fmtst2chk(_T("%*.*x"));
2640 fmtst2chk(_T("%0*.*x"));
2642 wxPrintf(_T("bad format:\t\"%b\"\n"));
2643 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
2645 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
2646 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
2647 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
2648 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
2649 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
2650 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
2651 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
2652 wxPrintf(_T("left-adjusted ZLDN:\t\"%-010ld\"\n"), -123456);
2653 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
2654 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
2656 wxPrintf(_T("zero-padded string:\t\"%010s\"\n"), shortstr
);
2657 wxPrintf(_T("left-adjusted Z string:\t\"%-010s\"\n"), shortstr
);
2658 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
2659 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
2660 wxPrintf(_T("null string:\t\"%s\"\n"), (wxChar
*)NULL
);
2661 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
2663 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
2664 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
2665 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
2666 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
2667 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
2668 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
2669 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
2670 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
2671 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
2672 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
2673 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
2674 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
2676 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
2677 wxPrintf (_T(" %6.5f\n"), .1);
2678 wxPrintf (_T("x%5.4fx\n"), .5);
2680 wxPrintf (_T("%#03x\n"), 1);
2682 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
2688 while (niter
-- != 0)
2689 wxPrintf (_T("%.17e\n"), d
/ 2);
2693 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
2695 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
2696 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
2697 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
2698 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
2699 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
2700 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
2701 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
2702 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
2703 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
2704 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
2709 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
2711 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
2712 rc
, WXSIZEOF(buf
), buf
);
2715 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
2716 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
2722 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
2723 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
2724 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
2725 wxPrintf (_T("%g should be 123.456\n"), 123.456);
2726 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
2727 wxPrintf (_T("%g should be 10\n"), 10.0);
2728 wxPrintf (_T("%g should be 0.02\n"), 0.02);
2732 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
2738 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
2740 result
|= wxStrcmp (buf
,
2741 _T("onetwo three "));
2743 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
2750 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
2751 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
2753 if (wxStrcmp (buf
, _T("40000000000")) != 0)
2756 wxPuts (_T("\tFAILED"));
2760 #endif // wxLongLong_t
2762 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
2763 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
2765 wxPuts (_T("--- Should be no further output. ---"));
2774 memset (bytes
, '\xff', sizeof bytes
);
2775 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
2776 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
2777 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
2779 wxPuts (_T("%hhn overwrite more bytes"));
2784 wxPuts (_T("%hhn wrote incorrect value"));
2796 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
2797 if (wxStrcmp (buf
, _T(" ")) != 0)
2798 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
2799 wxSprintf (buf
, _T("%5.f"), 33.3);
2800 if (wxStrcmp (buf
, _T(" 33")) != 0)
2801 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
2802 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
2803 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
2804 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
2805 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
2806 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
2807 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
2808 wxSprintf (buf
, _T("%.g"), 33.3);
2809 if (wxStrcmp (buf
, _T("3e+01")) != 0)
2810 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
2811 wxSprintf (buf
, _T("%.G"), 33.3);
2812 if (wxStrcmp (buf
, _T("3E+01")) != 0)
2813 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
2823 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
2824 if (wxStrcmp (buf
, _T("3")) != 0)
2825 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2827 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
2828 if (wxStrcmp (buf
, _T("3")) != 0)
2829 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2831 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
2832 if (wxStrcmp (buf
, _T(" 3")) != 0)
2833 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
2835 wxSprintf (buf
, _T("%04.*o"), prec
, 33);
2836 if (wxStrcmp (buf
, _T(" 041")) != 0)
2837 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
2839 wxSprintf (buf
, _T("%09.*u"), prec
, 33);
2840 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
2841 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
2843 wxSprintf (buf
, _T("%04.*x"), prec
, 33);
2844 if (wxStrcmp (buf
, _T(" 021")) != 0)
2845 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2847 wxSprintf (buf
, _T("%04.*X"), prec
, 33);
2848 if (wxStrcmp (buf
, _T(" 021")) != 0)
2849 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2852 #endif // TEST_PRINTF
2854 // ----------------------------------------------------------------------------
2855 // registry and related stuff
2856 // ----------------------------------------------------------------------------
2858 // this is for MSW only
2861 #undef TEST_REGISTRY
2866 #include "wx/confbase.h"
2867 #include "wx/msw/regconf.h"
2869 static void TestRegConfWrite()
2871 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2872 regconf
.Write(_T("Hello"), wxString(_T("world")));
2875 #endif // TEST_REGCONF
2877 #ifdef TEST_REGISTRY
2879 #include "wx/msw/registry.h"
2881 // I chose this one because I liked its name, but it probably only exists under
2883 static const wxChar
*TESTKEY
=
2884 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2886 static void TestRegistryRead()
2888 wxPuts(_T("*** testing registry reading ***"));
2890 wxRegKey
key(TESTKEY
);
2891 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2894 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2899 size_t nSubKeys
, nValues
;
2900 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2902 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2905 wxPrintf(_T("Enumerating values:\n"));
2909 bool cont
= key
.GetFirstValue(value
, dummy
);
2912 wxPrintf(_T("Value '%s': type "), value
.c_str());
2913 switch ( key
.GetValueType(value
) )
2915 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2916 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2917 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2918 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2919 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2920 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2921 default: wxPrintf(_T("other (unknown)")); break;
2924 wxPrintf(_T(", value = "));
2925 if ( key
.IsNumericValue(value
) )
2928 key
.QueryValue(value
, &val
);
2929 wxPrintf(_T("%ld"), val
);
2934 key
.QueryValue(value
, val
);
2935 wxPrintf(_T("'%s'"), val
.c_str());
2937 key
.QueryRawValue(value
, val
);
2938 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2943 cont
= key
.GetNextValue(value
, dummy
);
2947 static void TestRegistryAssociation()
2950 The second call to deleteself genertaes an error message, with a
2951 messagebox saying .flo is crucial to system operation, while the .ddf
2952 call also fails, but with no error message
2957 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2959 key
= "ddxf_auto_file" ;
2960 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2962 key
= "ddxf_auto_file" ;
2963 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2966 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2968 key
= "program \"%1\"" ;
2970 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2972 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2974 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2976 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2980 #endif // TEST_REGISTRY
2982 // ----------------------------------------------------------------------------
2984 // ----------------------------------------------------------------------------
2988 #include "wx/socket.h"
2989 #include "wx/protocol/protocol.h"
2990 #include "wx/protocol/http.h"
2992 static void TestSocketServer()
2994 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2996 static const int PORT
= 3000;
3001 wxSocketServer
*server
= new wxSocketServer(addr
);
3002 if ( !server
->Ok() )
3004 wxPuts(_T("ERROR: failed to bind"));
3012 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
3014 wxSocketBase
*socket
= server
->Accept();
3017 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
3021 wxPuts(_T("Server: got a client."));
3023 server
->SetTimeout(60); // 1 min
3026 while ( !close
&& socket
->IsConnected() )
3029 wxChar ch
= _T('\0');
3032 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
3034 // don't log error if the client just close the connection
3035 if ( socket
->IsConnected() )
3037 wxPuts(_T("ERROR: in wxSocket::Read."));
3057 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
3058 if ( s
== _T("close") )
3060 wxPuts(_T("Closing connection"));
3064 else if ( s
== _T("quit") )
3069 wxPuts(_T("Shutting down the server"));
3071 else // not a special command
3073 socket
->Write(s
.MakeUpper().c_str(), s
.length());
3074 socket
->Write("\r\n", 2);
3075 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
3081 wxPuts(_T("Server: lost a client unexpectedly."));
3087 // same as "delete server" but is consistent with GUI programs
3091 static void TestSocketClient()
3093 wxPuts(_T("*** Testing wxSocketClient ***\n"));
3095 static const wxChar
*hostname
= _T("www.wxwindows.org");
3098 addr
.Hostname(hostname
);
3101 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
3103 wxSocketClient client
;
3104 if ( !client
.Connect(addr
) )
3106 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
3110 wxPrintf(_T("--- Connected to %s:%u...\n"),
3111 addr
.Hostname().c_str(), addr
.Service());
3115 // could use simply "GET" here I suppose
3117 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
3118 client
.Write(cmdGet
, cmdGet
.length());
3119 wxPrintf(_T("--- Sent command '%s' to the server\n"),
3120 MakePrintable(cmdGet
).c_str());
3121 client
.Read(buf
, WXSIZEOF(buf
));
3122 wxPrintf(_T("--- Server replied:\n%s"), buf
);
3126 #endif // TEST_SOCKETS
3128 // ----------------------------------------------------------------------------
3130 // ----------------------------------------------------------------------------
3134 #include "wx/protocol/ftp.h"
3138 #define FTP_ANONYMOUS
3140 #ifdef FTP_ANONYMOUS
3141 static const wxChar
*directory
= _T("/pub");
3142 static const wxChar
*filename
= _T("welcome.msg");
3144 static const wxChar
*directory
= _T("/etc");
3145 static const wxChar
*filename
= _T("issue");
3148 static bool TestFtpConnect()
3150 wxPuts(_T("*** Testing FTP connect ***"));
3152 #ifdef FTP_ANONYMOUS
3153 static const wxChar
*hostname
= _T("ftp.wxwindows.org");
3155 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
3156 #else // !FTP_ANONYMOUS
3157 static const wxChar
*hostname
= "localhost";
3160 wxFgets(user
, WXSIZEOF(user
), stdin
);
3161 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
3164 wxChar password
[256];
3165 wxPrintf(_T("Password for %s: "), password
);
3166 wxFgets(password
, WXSIZEOF(password
), stdin
);
3167 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
3168 ftp
.SetPassword(password
);
3170 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
3171 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
3173 if ( !ftp
.Connect(hostname
) )
3175 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
3181 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
3182 hostname
, ftp
.Pwd().c_str());
3188 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
3189 static void TestFtpWuFtpd()
3192 static const wxChar
*hostname
= _T("ftp.eudora.com");
3193 if ( !ftp
.Connect(hostname
) )
3195 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
3199 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
3200 wxInputStream
*in
= ftp
.GetInputStream(filename
);
3203 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
3207 size_t size
= in
->GetSize();
3208 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
3210 wxChar
*data
= new wxChar
[size
];
3211 if ( !in
->Read(data
, size
) )
3213 wxPuts(_T("ERROR: read error"));
3217 wxPrintf(_T("Successfully retrieved the file.\n"));
3226 static void TestFtpList()
3228 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
3231 if ( !ftp
.ChDir(directory
) )
3233 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
3236 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
3238 // test NLIST and LIST
3239 wxArrayString files
;
3240 if ( !ftp
.GetFilesList(files
) )
3242 wxPuts(_T("ERROR: failed to get NLIST of files"));
3246 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
3247 size_t count
= files
.GetCount();
3248 for ( size_t n
= 0; n
< count
; n
++ )
3250 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3252 wxPuts(_T("End of the file list"));
3255 if ( !ftp
.GetDirList(files
) )
3257 wxPuts(_T("ERROR: failed to get LIST of files"));
3261 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
3262 size_t count
= files
.GetCount();
3263 for ( size_t n
= 0; n
< count
; n
++ )
3265 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3267 wxPuts(_T("End of the file list"));
3270 if ( !ftp
.ChDir(_T("..")) )
3272 wxPuts(_T("ERROR: failed to cd to .."));
3275 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
3278 static void TestFtpDownload()
3280 wxPuts(_T("*** Testing wxFTP download ***\n"));
3283 wxInputStream
*in
= ftp
.GetInputStream(filename
);
3286 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
3290 size_t size
= in
->GetSize();
3291 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
3294 wxChar
*data
= new wxChar
[size
];
3295 if ( !in
->Read(data
, size
) )
3297 wxPuts(_T("ERROR: read error"));
3301 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
3309 static void TestFtpFileSize()
3311 wxPuts(_T("*** Testing FTP SIZE command ***"));
3313 if ( !ftp
.ChDir(directory
) )
3315 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
3318 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
3320 if ( ftp
.FileExists(filename
) )
3322 int size
= ftp
.GetFileSize(filename
);
3324 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
3326 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
3330 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
3334 static void TestFtpMisc()
3336 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
3338 if ( ftp
.SendCommand("STAT") != '2' )
3340 wxPuts(_T("ERROR: STAT failed"));
3344 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
3347 if ( ftp
.SendCommand("HELP SITE") != '2' )
3349 wxPuts(_T("ERROR: HELP SITE failed"));
3353 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
3354 ftp
.GetLastResult().c_str());
3358 static void TestFtpInteractive()
3360 wxPuts(_T("\n*** Interactive wxFTP test ***"));
3366 wxPrintf(_T("Enter FTP command: "));
3367 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3370 // kill the last '\n'
3371 buf
[wxStrlen(buf
) - 1] = 0;
3373 // special handling of LIST and NLST as they require data connection
3374 wxString
start(buf
, 4);
3376 if ( start
== "LIST" || start
== "NLST" )
3379 if ( wxStrlen(buf
) > 4 )
3382 wxArrayString files
;
3383 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
3385 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
3389 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
3390 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
3391 size_t count
= files
.GetCount();
3392 for ( size_t n
= 0; n
< count
; n
++ )
3394 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3396 wxPuts(_T("--- End of the file list"));
3401 wxChar ch
= ftp
.SendCommand(buf
);
3402 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
3405 wxPrintf(_T(" (return code %c)"), ch
);
3408 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
3412 wxPuts(_T("\n*** done ***"));
3415 static void TestFtpUpload()
3417 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
3420 static const wxChar
*file1
= _T("test1");
3421 static const wxChar
*file2
= _T("test2");
3422 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
3425 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
3426 out
->Write("First hello", 11);
3430 // send a command to check the remote file
3431 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
3433 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
3437 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
3438 file1
, ftp
.GetLastResult().c_str());
3441 out
= ftp
.GetOutputStream(file2
);
3444 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
3445 out
->Write("Second hello", 12);
3452 // ----------------------------------------------------------------------------
3454 // ----------------------------------------------------------------------------
3458 #include "wx/wfstream.h"
3459 #include "wx/mstream.h"
3461 static void TestFileStream()
3463 wxPuts(_T("*** Testing wxFileInputStream ***"));
3465 static const wxChar
*filename
= _T("testdata.fs");
3467 wxFileOutputStream
fsOut(filename
);
3468 fsOut
.Write("foo", 3);
3471 wxFileInputStream
fsIn(filename
);
3472 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
3473 while ( !fsIn
.Eof() )
3475 putchar(fsIn
.GetC());
3478 if ( !wxRemoveFile(filename
) )
3480 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
);
3483 wxPuts(_T("\n*** wxFileInputStream test done ***"));
3486 static void TestMemoryStream()
3488 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
3490 wxMemoryOutputStream memOutStream
;
3491 wxPrintf(_T("Initially out stream offset: %lu\n"),
3492 (unsigned long)memOutStream
.TellO());
3494 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
3496 memOutStream
.PutC(*p
);
3499 wxPrintf(_T("Final out stream offset: %lu\n"),
3500 (unsigned long)memOutStream
.TellO());
3502 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
3505 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
3507 wxMemoryInputStream
memInpStream(buf
, len
);
3508 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3509 while ( !memInpStream
.Eof() )
3511 putchar(memInpStream
.GetC());
3514 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
3517 #endif // TEST_STREAMS
3519 // ----------------------------------------------------------------------------
3521 // ----------------------------------------------------------------------------
3525 #include "wx/timer.h"
3526 #include "wx/utils.h"
3528 static void TestStopWatch()
3530 wxPuts(_T("*** Testing wxStopWatch ***\n"));
3534 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
3537 wxPrintf(_T("\t%ldms\n"), sw
.Time());
3539 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
3543 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3546 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
3549 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3552 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
3555 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3558 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
3559 for ( size_t n
= 0; n
< 70; n
++ )
3563 for ( size_t m
= 0; m
< 100000; m
++ )
3565 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3567 wxPuts(_T("\ntime is negative - ERROR!"));
3575 wxPuts(_T(", ok."));
3578 #endif // TEST_TIMER
3580 // ----------------------------------------------------------------------------
3582 // ----------------------------------------------------------------------------
3586 #include "wx/vcard.h"
3588 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3591 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3594 wxPrintf(_T("%s%s"),
3595 wxString(_T('\t'), level
).c_str(),
3596 vcObj
->GetName().c_str());
3599 switch ( vcObj
->GetType() )
3601 case wxVCardObject::String
:
3602 case wxVCardObject::UString
:
3605 vcObj
->GetValue(&val
);
3606 value
<< _T('"') << val
<< _T('"');
3610 case wxVCardObject::Int
:
3613 vcObj
->GetValue(&i
);
3614 value
.Printf(_T("%u"), i
);
3618 case wxVCardObject::Long
:
3621 vcObj
->GetValue(&l
);
3622 value
.Printf(_T("%lu"), l
);
3626 case wxVCardObject::None
:
3629 case wxVCardObject::Object
:
3630 value
= _T("<node>");
3634 value
= _T("<unknown value type>");
3638 wxPrintf(_T(" = %s"), value
.c_str());
3641 DumpVObject(level
+ 1, *vcObj
);
3644 vcObj
= vcard
.GetNextProp(&cookie
);
3648 static void DumpVCardAddresses(const wxVCard
& vcard
)
3650 wxPuts(_T("\nShowing all addresses from vCard:\n"));
3654 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3658 int flags
= addr
->GetFlags();
3659 if ( flags
& wxVCardAddress::Domestic
)
3661 flagsStr
<< _T("domestic ");
3663 if ( flags
& wxVCardAddress::Intl
)
3665 flagsStr
<< _T("international ");
3667 if ( flags
& wxVCardAddress::Postal
)
3669 flagsStr
<< _T("postal ");
3671 if ( flags
& wxVCardAddress::Parcel
)
3673 flagsStr
<< _T("parcel ");
3675 if ( flags
& wxVCardAddress::Home
)
3677 flagsStr
<< _T("home ");
3679 if ( flags
& wxVCardAddress::Work
)
3681 flagsStr
<< _T("work ");
3684 wxPrintf(_T("Address %u:\n")
3686 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3689 addr
->GetPostOffice().c_str(),
3690 addr
->GetExtAddress().c_str(),
3691 addr
->GetStreet().c_str(),
3692 addr
->GetLocality().c_str(),
3693 addr
->GetRegion().c_str(),
3694 addr
->GetPostalCode().c_str(),
3695 addr
->GetCountry().c_str()
3699 addr
= vcard
.GetNextAddress(&cookie
);
3703 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3705 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
3709 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3713 int flags
= phone
->GetFlags();
3714 if ( flags
& wxVCardPhoneNumber::Voice
)
3716 flagsStr
<< _T("voice ");
3718 if ( flags
& wxVCardPhoneNumber::Fax
)
3720 flagsStr
<< _T("fax ");
3722 if ( flags
& wxVCardPhoneNumber::Cellular
)
3724 flagsStr
<< _T("cellular ");
3726 if ( flags
& wxVCardPhoneNumber::Modem
)
3728 flagsStr
<< _T("modem ");
3730 if ( flags
& wxVCardPhoneNumber::Home
)
3732 flagsStr
<< _T("home ");
3734 if ( flags
& wxVCardPhoneNumber::Work
)
3736 flagsStr
<< _T("work ");
3739 wxPrintf(_T("Phone number %u:\n")
3744 phone
->GetNumber().c_str()
3748 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3752 static void TestVCardRead()
3754 wxPuts(_T("*** Testing wxVCard reading ***\n"));
3756 wxVCard
vcard(_T("vcard.vcf"));
3757 if ( !vcard
.IsOk() )
3759 wxPuts(_T("ERROR: couldn't load vCard."));
3763 // read individual vCard properties
3764 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3768 vcObj
->GetValue(&value
);
3773 value
= _T("<none>");
3776 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
3779 if ( !vcard
.GetFullName(&value
) )
3781 value
= _T("<none>");
3784 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
3786 // now show how to deal with multiply occuring properties
3787 DumpVCardAddresses(vcard
);
3788 DumpVCardPhoneNumbers(vcard
);
3790 // and finally show all
3791 wxPuts(_T("\nNow dumping the entire vCard:\n")
3792 "-----------------------------\n");
3794 DumpVObject(0, vcard
);
3798 static void TestVCardWrite()
3800 wxPuts(_T("*** Testing wxVCard writing ***\n"));
3803 if ( !vcard
.IsOk() )
3805 wxPuts(_T("ERROR: couldn't create vCard."));
3810 vcard
.SetName("Zeitlin", "Vadim");
3811 vcard
.SetFullName("Vadim Zeitlin");
3812 vcard
.SetOrganization("wxWindows", "R&D");
3814 // just dump the vCard back
3815 wxPuts(_T("Entire vCard follows:\n"));
3816 wxPuts(vcard
.Write());
3820 #endif // TEST_VCARD
3822 // ----------------------------------------------------------------------------
3824 // ----------------------------------------------------------------------------
3826 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3832 #include "wx/volume.h"
3834 static const wxChar
*volumeKinds
[] =
3840 _T("network volume"),
3844 static void TestFSVolume()
3846 wxPuts(_T("*** Testing wxFSVolume class ***"));
3848 wxArrayString volumes
= wxFSVolume::GetVolumes();
3849 size_t count
= volumes
.GetCount();
3853 wxPuts(_T("ERROR: no mounted volumes?"));
3857 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3859 for ( size_t n
= 0; n
< count
; n
++ )
3861 wxFSVolume
vol(volumes
[n
]);
3864 wxPuts(_T("ERROR: couldn't create volume"));
3868 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3870 vol
.GetDisplayName().c_str(),
3871 vol
.GetName().c_str(),
3872 volumeKinds
[vol
.GetKind()],
3873 vol
.IsWritable() ? _T("rw") : _T("ro"),
3874 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3879 #endif // TEST_VOLUME
3881 // ----------------------------------------------------------------------------
3882 // wide char and Unicode support
3883 // ----------------------------------------------------------------------------
3887 static void TestUnicodeToFromAscii()
3889 wxPuts(_T("Testing wxString::To/FromAscii()\n"));
3891 static const char *msg
= "Hello, world!";
3892 wxString s
= wxString::FromAscii(msg
);
3894 wxPrintf(_T("Message in Unicode: %s\n"), s
.c_str());
3895 printf("Message in ASCII: %s\n", (const char *)s
.ToAscii());
3897 wxPutchar(_T('\n'));
3900 #endif // TEST_UNICODE
3904 #include "wx/strconv.h"
3905 #include "wx/fontenc.h"
3906 #include "wx/encconv.h"
3907 #include "wx/buffer.h"
3909 static const unsigned char utf8koi8r
[] =
3911 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3912 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3913 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3914 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3915 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3916 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3917 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3920 static const unsigned char utf8iso8859_1
[] =
3922 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3923 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3924 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3925 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3926 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3929 static const unsigned char utf8Invalid
[] =
3931 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3932 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3933 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3934 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3938 static const struct Utf8Data
3940 const unsigned char *text
;
3942 const wxChar
*charset
;
3943 wxFontEncoding encoding
;
3946 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3947 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3948 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3951 static void TestUtf8()
3953 wxPuts(_T("*** Testing UTF8 support ***\n"));
3958 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3960 const Utf8Data
& u8d
= utf8data
[n
];
3961 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3962 WXSIZEOF(wbuf
)) == (size_t)-1 )
3964 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3968 wxCSConv
conv(u8d
.charset
);
3969 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3971 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3975 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3979 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
), *wxConvCurrent
);
3981 s
= _T("<< conversion failed >>");
3982 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3989 static void TestEncodingConverter()
3991 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3993 // using wxEncodingConverter should give the same result as above
3996 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3997 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3999 wxPuts(_T("ERROR: UTF-8 decoding failed."));
4003 wxEncodingConverter ec
;
4004 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
4005 ec
.Convert(wbuf
, buf
);
4006 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
4012 #endif // TEST_WCHAR
4014 // ----------------------------------------------------------------------------
4016 // ----------------------------------------------------------------------------
4020 #include "wx/filesys.h"
4021 #include "wx/fs_zip.h"
4022 #include "wx/zipstrm.h"
4024 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
4026 static void TestZipStreamRead()
4028 wxPuts(_T("*** Testing ZIP reading ***\n"));
4030 static const wxChar
*filename
= _T("foo");
4031 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
4032 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
4034 wxPrintf(_T("Dumping the file '%s':\n"), filename
);
4035 while ( !istr
.Eof() )
4037 putchar(istr
.GetC());
4041 wxPuts(_T("\n----- done ------"));
4044 static void DumpZipDirectory(wxFileSystem
& fs
,
4045 const wxString
& dir
,
4046 const wxString
& indent
)
4048 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
4049 TESTFILE_ZIP
, dir
.c_str());
4050 wxString wildcard
= prefix
+ _T("/*");
4052 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
4053 while ( !dirname
.empty() )
4055 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
4057 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
4062 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
4064 DumpZipDirectory(fs
, dirname
,
4065 indent
+ wxString(_T(' '), 4));
4067 dirname
= fs
.FindNext();
4070 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
4071 while ( !filename
.empty() )
4073 if ( !filename
.StartsWith(prefix
, &filename
) )
4075 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
4080 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
4082 filename
= fs
.FindNext();
4086 static void TestZipFileSystem()
4088 wxPuts(_T("*** Testing ZIP file system ***\n"));
4090 wxFileSystem::AddHandler(new wxZipFSHandler
);
4092 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
4094 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
4099 // ----------------------------------------------------------------------------
4101 // ----------------------------------------------------------------------------
4105 #include "wx/zstream.h"
4106 #include "wx/wfstream.h"
4108 static const wxChar
*FILENAME_GZ
= _T("test.gz");
4109 static const wxChar
*TEST_DATA
= _T("hello and hello and hello and hello and hello");
4111 static void TestZlibStreamWrite()
4113 wxPuts(_T("*** Testing Zlib stream reading ***\n"));
4115 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
4116 wxZlibOutputStream
ostr(fileOutStream
);
4117 wxPrintf(_T("Compressing the test string... "));
4118 ostr
.Write(TEST_DATA
, wxStrlen(TEST_DATA
) + 1);
4121 wxPuts(_T("(ERROR: failed)"));
4128 wxPuts(_T("\n----- done ------"));
4131 static void TestZlibStreamRead()
4133 wxPuts(_T("*** Testing Zlib stream reading ***\n"));
4135 wxFileInputStream
fileInStream(FILENAME_GZ
);
4136 wxZlibInputStream
istr(fileInStream
);
4137 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
4139 wxPuts(_T("Dumping the file:"));
4140 while ( !istr
.Eof() )
4142 putchar(istr
.GetC());
4146 wxPuts(_T("\n----- done ------"));
4151 // ----------------------------------------------------------------------------
4153 // ----------------------------------------------------------------------------
4155 #ifdef TEST_DATETIME
4159 #include "wx/date.h"
4160 #include "wx/datetime.h"
4165 wxDateTime::wxDateTime_t day
;
4166 wxDateTime::Month month
;
4168 wxDateTime::wxDateTime_t hour
, min
, sec
;
4170 wxDateTime::WeekDay wday
;
4171 time_t gmticks
, ticks
;
4173 void Init(const wxDateTime::Tm
& tm
)
4182 gmticks
= ticks
= -1;
4185 wxDateTime
DT() const
4186 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
4188 bool SameDay(const wxDateTime::Tm
& tm
) const
4190 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
4193 wxString
Format() const
4196 s
.Printf(_T("%02d:%02d:%02d %10s %02d, %4d%s"),
4198 wxDateTime::GetMonthName(month
).c_str(),
4200 abs(wxDateTime::ConvertYearToBC(year
)),
4201 year
> 0 ? _T("AD") : _T("BC"));
4205 wxString
FormatDate() const
4208 s
.Printf(_T("%02d-%s-%4d%s"),
4210 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
4211 abs(wxDateTime::ConvertYearToBC(year
)),
4212 year
> 0 ? _T("AD") : _T("BC"));
4217 static const Date testDates
[] =
4219 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
4220 { 7, wxDateTime::Feb
, 2036, 00, 00, 00, 2464730.5, wxDateTime::Thu
, -1, -1 },
4221 { 8, wxDateTime::Feb
, 2036, 00, 00, 00, 2464731.5, wxDateTime::Fri
, -1, -1 },
4222 { 1, wxDateTime::Jan
, 2037, 00, 00, 00, 2465059.5, wxDateTime::Thu
, -1, -1 },
4223 { 1, wxDateTime::Jan
, 2038, 00, 00, 00, 2465424.5, wxDateTime::Fri
, -1, -1 },
4224 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
4225 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
4226 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
4227 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
4228 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
4229 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
4230 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
4231 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
4232 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
4233 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
4234 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
4235 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
4236 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
4237 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
4240 // this test miscellaneous static wxDateTime functions
4241 static void TestTimeStatic()
4243 wxPuts(_T("\n*** wxDateTime static methods test ***"));
4245 // some info about the current date
4246 int year
= wxDateTime::GetCurrentYear();
4247 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
4249 wxDateTime::IsLeapYear(year
) ? "" : "not ",
4250 wxDateTime::GetNumberOfDays(year
));
4252 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
4253 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
4254 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
4255 wxDateTime::GetMonthName(month
).c_str(),
4256 wxDateTime::GetNumberOfDays(month
));
4259 static const size_t nYears
= 5;
4260 static const size_t years
[2][nYears
] =
4262 // first line: the years to test
4263 { 1990, 1976, 2000, 2030, 1984, },
4265 // second line: true if leap, false otherwise
4266 { false, true, true, false, true }
4269 for ( size_t n
= 0; n
< nYears
; n
++ )
4271 int year
= years
[0][n
];
4272 bool should
= years
[1][n
] != 0,
4273 is
= wxDateTime::IsLeapYear(year
);
4275 wxPrintf(_T("Year %d is %sa leap year (%s)\n"),
4278 should
== is
? "ok" : "ERROR");
4280 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
4284 // test constructing wxDateTime objects
4285 static void TestTimeSet()
4287 wxPuts(_T("\n*** wxDateTime construction test ***"));
4289 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4291 const Date
& d1
= testDates
[n
];
4292 wxDateTime dt
= d1
.DT();
4295 d2
.Init(dt
.GetTm());
4297 wxString s1
= d1
.Format(),
4300 wxPrintf(_T("Date: %s == %s (%s)\n"),
4301 s1
.c_str(), s2
.c_str(),
4302 s1
== s2
? _T("ok") : _T("ERROR"));
4306 // test time zones stuff
4307 static void TestTimeZones()
4309 wxPuts(_T("\n*** wxDateTime timezone test ***"));
4311 wxDateTime now
= wxDateTime::Now();
4313 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
4314 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
4315 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
4316 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
4317 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
4318 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
4320 wxDateTime::Tm tm
= now
.GetTm();
4321 if ( wxDateTime(tm
) != now
)
4323 wxPrintf(_T("ERROR: got %s instead of %s\n"),
4324 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
4328 // test some minimal support for the dates outside the standard range
4329 static void TestTimeRange()
4331 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
4333 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
4335 wxPrintf(_T("Unix epoch:\t%s\n"),
4336 wxDateTime(2440587.5).Format(fmt
).c_str());
4337 wxPrintf(_T("Feb 29, 0: \t%s\n"),
4338 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
4339 wxPrintf(_T("JDN 0: \t%s\n"),
4340 wxDateTime(0.0).Format(fmt
).c_str());
4341 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
4342 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
4343 wxPrintf(_T("May 29, 2099:\t%s\n"),
4344 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
4347 static void TestTimeTicks()
4349 wxPuts(_T("\n*** wxDateTime ticks test ***"));
4351 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4353 const Date
& d
= testDates
[n
];
4354 if ( d
.ticks
== -1 )
4357 wxDateTime dt
= d
.DT();
4358 long ticks
= (dt
.GetValue() / 1000).ToLong();
4359 wxPrintf(_T("Ticks of %s:\t% 10ld"), d
.Format().c_str(), ticks
);
4360 if ( ticks
== d
.ticks
)
4362 wxPuts(_T(" (ok)"));
4366 wxPrintf(_T(" (ERROR: should be %ld, delta = %ld)\n"),
4367 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
4370 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
4371 ticks
= (dt
.GetValue() / 1000).ToLong();
4372 wxPrintf(_T("GMtks of %s:\t% 10ld"), d
.Format().c_str(), ticks
);
4373 if ( ticks
== d
.gmticks
)
4375 wxPuts(_T(" (ok)"));
4379 wxPrintf(_T(" (ERROR: should be %ld, delta = %ld)\n"),
4380 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
4387 // test conversions to JDN &c
4388 static void TestTimeJDN()
4390 wxPuts(_T("\n*** wxDateTime to JDN test ***"));
4392 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4394 const Date
& d
= testDates
[n
];
4395 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
4396 double jdn
= dt
.GetJulianDayNumber();
4398 wxPrintf(_T("JDN of %s is:\t% 15.6f"), d
.Format().c_str(), jdn
);
4401 wxPuts(_T(" (ok)"));
4405 wxPrintf(_T(" (ERROR: should be %f, delta = %f)\n"),
4406 d
.jdn
, jdn
- d
.jdn
);
4411 // test week days computation
4412 static void TestTimeWDays()
4414 wxPuts(_T("\n*** wxDateTime weekday test ***"));
4416 // test GetWeekDay()
4418 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4420 const Date
& d
= testDates
[n
];
4421 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
4423 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
4424 wxPrintf(_T("%s is: %s"),
4426 wxDateTime::GetWeekDayName(wday
).c_str());
4427 if ( wday
== d
.wday
)
4429 wxPuts(_T(" (ok)"));
4433 wxPrintf(_T(" (ERROR: should be %s)\n"),
4434 wxDateTime::GetWeekDayName(d
.wday
).c_str());
4440 // test SetToWeekDay()
4441 struct WeekDateTestData
4443 Date date
; // the real date (precomputed)
4444 int nWeek
; // its week index in the month
4445 wxDateTime::WeekDay wday
; // the weekday
4446 wxDateTime::Month month
; // the month
4447 int year
; // and the year
4449 wxString
Format() const
4452 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
4454 case 1: which
= _T("first"); break;
4455 case 2: which
= _T("second"); break;
4456 case 3: which
= _T("third"); break;
4457 case 4: which
= _T("fourth"); break;
4458 case 5: which
= _T("fifth"); break;
4460 case -1: which
= _T("last"); break;
4465 which
+= _T(" from end");
4468 s
.Printf(_T("The %s %s of %s in %d"),
4470 wxDateTime::GetWeekDayName(wday
).c_str(),
4471 wxDateTime::GetMonthName(month
).c_str(),
4478 // the array data was generated by the following python program
4480 from DateTime import *
4481 from whrandom import *
4482 from string import *
4484 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4485 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4487 week = DateTimeDelta(7)
4490 year = randint(1900, 2100)
4491 month = randint(1, 12)
4492 day = randint(1, 28)
4493 dt = DateTime(year, month, day)
4494 wday = dt.day_of_week
4496 countFromEnd = choice([-1, 1])
4499 while dt.month is month:
4500 dt = dt - countFromEnd * week
4501 weekNum = weekNum + countFromEnd
4503 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
4505 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
4506 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
4509 static const WeekDateTestData weekDatesTestData
[] =
4511 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
4512 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
4513 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
4514 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
4515 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
4516 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
4517 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
4518 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
4519 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
4520 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
4521 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
4522 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
4523 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
4524 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
4525 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
4526 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
4527 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
4528 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
4529 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
4530 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4533 static const wxChar
*fmt
= _T("%d-%b-%Y");
4536 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4538 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4540 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4542 wxPrintf(_T("%s is %s"), wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4544 const Date
& d
= wd
.date
;
4545 if ( d
.SameDay(dt
.GetTm()) )
4547 wxPuts(_T(" (ok)"));
4551 dt
.Set(d
.day
, d
.month
, d
.year
);
4553 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.Format(fmt
).c_str());
4558 // test the computation of (ISO) week numbers
4559 static void TestTimeWNumber()
4561 wxPuts(_T("\n*** wxDateTime week number test ***"));
4563 struct WeekNumberTestData
4565 Date date
; // the date
4566 wxDateTime::wxDateTime_t week
; // the week number in the year
4567 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4568 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4569 wxDateTime::wxDateTime_t dnum
; // day number in the year
4572 // data generated with the following python script:
4574 from DateTime import *
4575 from whrandom import *
4576 from string import *
4578 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4579 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4581 def GetMonthWeek(dt):
4582 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4583 if weekNumMonth < 0:
4584 weekNumMonth = weekNumMonth + 53
4587 def GetLastSundayBefore(dt):
4588 if dt.iso_week[2] == 7:
4591 return dt - DateTimeDelta(dt.iso_week[2])
4594 year = randint(1900, 2100)
4595 month = randint(1, 12)
4596 day = randint(1, 28)
4597 dt = DateTime(year, month, day)
4598 dayNum = dt.day_of_year
4599 weekNum = dt.iso_week[1]
4600 weekNumMonth = GetMonthWeek(dt)
4603 dtSunday = GetLastSundayBefore(dt)
4605 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4606 weekNumMonth2 = weekNumMonth2 + 1
4607 dtSunday = dtSunday - DateTimeDelta(7)
4609 data = { 'day': rjust(`day`, 2), \
4610 'month': monthNames[month - 1], \
4612 'weekNum': rjust(`weekNum`, 2), \
4613 'weekNumMonth': weekNumMonth, \
4614 'weekNumMonth2': weekNumMonth2, \
4615 'dayNum': rjust(`dayNum`, 3) }
4617 print " { { %(day)s, "\
4618 "wxDateTime::%(month)s, "\
4621 "%(weekNumMonth)s, "\
4622 "%(weekNumMonth2)s, "\
4623 "%(dayNum)s }," % data
4626 static const WeekNumberTestData weekNumberTestDates
[] =
4628 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4629 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4630 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4631 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4632 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4633 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4634 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4635 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4636 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4637 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4638 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4639 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4640 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4641 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4642 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4643 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4644 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4645 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4646 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4647 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4650 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4652 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4653 const Date
& d
= wn
.date
;
4655 wxDateTime dt
= d
.DT();
4657 wxDateTime::wxDateTime_t
4658 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4659 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4660 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4661 dnum
= dt
.GetDayOfYear();
4663 wxPrintf(_T("%s: the day number is %d"), d
.FormatDate().c_str(), dnum
);
4664 if ( dnum
== wn
.dnum
)
4666 wxPrintf(_T(" (ok)"));
4670 wxPrintf(_T(" (ERROR: should be %d)"), wn
.dnum
);
4673 wxPrintf(_T(", week in month = %d"), wmon
);
4674 if ( wmon
!= wn
.wmon
)
4676 wxPrintf(_T(" (ERROR: should be %d)"), wn
.wmon
);
4679 wxPrintf(_T(" or %d"), wmon2
);
4680 if ( wmon2
== wn
.wmon2
)
4682 wxPrintf(_T(" (ok)"));
4686 wxPrintf(_T(" (ERROR: should be %d)"), wn
.wmon2
);
4689 wxPrintf(_T(", week in year = %d"), week
);
4690 if ( week
!= wn
.week
)
4692 wxPrintf(_T(" (ERROR: should be %d)"), wn
.week
);
4695 wxPutchar(_T('\n'));
4697 wxDateTime
dt2(1, wxDateTime::Jan
, d
.year
);
4698 dt2
.SetToTheWeek(wn
.week
, dt
.GetWeekDay());
4702 d2
.Init(dt2
.GetTm());
4703 wxPrintf(_T("ERROR: SetToTheWeek() returned %s\n"),
4704 d2
.FormatDate().c_str());
4709 // test DST calculations
4710 static void TestTimeDST()
4712 wxPuts(_T("\n*** wxDateTime DST test ***"));
4714 wxPrintf(_T("DST is%s in effect now.\n\n"),
4715 wxDateTime::Now().IsDST() ? _T("") : _T(" not"));
4717 // taken from http://www.energy.ca.gov/daylightsaving.html
4718 static const Date datesDST
[2][2004 - 1900 + 1] =
4721 { 1, wxDateTime::Apr
, 1990 },
4722 { 7, wxDateTime::Apr
, 1991 },
4723 { 5, wxDateTime::Apr
, 1992 },
4724 { 4, wxDateTime::Apr
, 1993 },
4725 { 3, wxDateTime::Apr
, 1994 },
4726 { 2, wxDateTime::Apr
, 1995 },
4727 { 7, wxDateTime::Apr
, 1996 },
4728 { 6, wxDateTime::Apr
, 1997 },
4729 { 5, wxDateTime::Apr
, 1998 },
4730 { 4, wxDateTime::Apr
, 1999 },
4731 { 2, wxDateTime::Apr
, 2000 },
4732 { 1, wxDateTime::Apr
, 2001 },
4733 { 7, wxDateTime::Apr
, 2002 },
4734 { 6, wxDateTime::Apr
, 2003 },
4735 { 4, wxDateTime::Apr
, 2004 },
4738 { 28, wxDateTime::Oct
, 1990 },
4739 { 27, wxDateTime::Oct
, 1991 },
4740 { 25, wxDateTime::Oct
, 1992 },
4741 { 31, wxDateTime::Oct
, 1993 },
4742 { 30, wxDateTime::Oct
, 1994 },
4743 { 29, wxDateTime::Oct
, 1995 },
4744 { 27, wxDateTime::Oct
, 1996 },
4745 { 26, wxDateTime::Oct
, 1997 },
4746 { 25, wxDateTime::Oct
, 1998 },
4747 { 31, wxDateTime::Oct
, 1999 },
4748 { 29, wxDateTime::Oct
, 2000 },
4749 { 28, wxDateTime::Oct
, 2001 },
4750 { 27, wxDateTime::Oct
, 2002 },
4751 { 26, wxDateTime::Oct
, 2003 },
4752 { 31, wxDateTime::Oct
, 2004 },
4757 for ( year
= 1990; year
< 2005; year
++ )
4759 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4760 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4762 wxPrintf(_T("DST period in the US for year %d: from %s to %s"),
4763 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4765 size_t n
= year
- 1990;
4766 const Date
& dBegin
= datesDST
[0][n
];
4767 const Date
& dEnd
= datesDST
[1][n
];
4769 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4771 wxPuts(_T(" (ok)"));
4775 wxPrintf(_T(" (ERROR: should be %s %d to %s %d)\n"),
4776 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4777 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4783 for ( year
= 1990; year
< 2005; year
++ )
4785 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
4787 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4788 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4792 // test wxDateTime -> text conversion
4793 static void TestTimeFormat()
4795 wxPuts(_T("\n*** wxDateTime formatting test ***"));
4797 // some information may be lost during conversion, so store what kind
4798 // of info should we recover after a round trip
4801 CompareNone
, // don't try comparing
4802 CompareBoth
, // dates and times should be identical
4803 CompareDate
, // dates only
4804 CompareTime
// time only
4809 CompareKind compareKind
;
4810 const wxChar
*format
;
4811 } formatTestFormats
[] =
4813 { CompareBoth
, _T("---> %c") },
4814 { CompareDate
, _T("Date is %A, %d of %B, in year %Y") },
4815 { CompareBoth
, _T("Date is %x, time is %X") },
4816 { CompareTime
, _T("Time is %H:%M:%S or %I:%M:%S %p") },
4817 { CompareNone
, _T("The day of year: %j, the week of year: %W") },
4818 { CompareDate
, _T("ISO date without separators: %Y%m%d") },
4821 static const Date formatTestDates
[] =
4823 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4824 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4826 // this test can't work for other centuries because it uses two digit
4827 // years in formats, so don't even try it
4828 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4829 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4830 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4834 // an extra test (as it doesn't depend on date, don't do it in the loop)
4835 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
4837 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4841 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4842 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4844 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4845 wxPrintf(_T("%s"), s
.c_str());
4847 // what can we recover?
4848 int kind
= formatTestFormats
[n
].compareKind
;
4852 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4855 // converion failed - should it have?
4856 if ( kind
== CompareNone
)
4857 wxPuts(_T(" (ok)"));
4859 wxPuts(_T(" (ERROR: conversion back failed)"));
4863 // should have parsed the entire string
4864 wxPuts(_T(" (ERROR: conversion back stopped too soon)"));
4868 bool equal
= false; // suppress compilaer warning
4876 equal
= dt
.IsSameDate(dt2
);
4880 equal
= dt
.IsSameTime(dt2
);
4886 wxPrintf(_T(" (ERROR: got back '%s' instead of '%s')\n"),
4887 dt2
.Format().c_str(), dt
.Format().c_str());
4891 wxPuts(_T(" (ok)"));
4898 // test text -> wxDateTime conversion
4899 static void TestTimeParse()
4901 wxPuts(_T("\n*** wxDateTime parse test ***"));
4903 struct ParseTestData
4905 const wxChar
*format
;
4910 static const ParseTestData parseTestDates
[] =
4912 { _T("Sat, 18 Dec 1999 00:46:40 +0100"), { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, true },
4913 { _T("Wed, 1 Dec 1999 05:17:20 +0300"), { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, true },
4916 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4918 const wxChar
*format
= parseTestDates
[n
].format
;
4920 wxPrintf(_T("%s => "), format
);
4923 if ( dt
.ParseRfc822Date(format
) )
4925 wxPrintf(_T("%s "), dt
.Format().c_str());
4927 if ( parseTestDates
[n
].good
)
4929 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4936 wxPrintf(_T("(ERROR: should be %s)\n"), dtReal
.Format().c_str());
4941 wxPuts(_T("(ERROR: bad format)"));
4946 wxPrintf(_T("bad format (%s)\n"),
4947 parseTestDates
[n
].good
? "ERROR" : "ok");
4952 static void TestDateTimeInteractive()
4954 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
4960 wxPrintf(_T("Enter a date: "));
4961 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
4964 // kill the last '\n'
4965 buf
[wxStrlen(buf
) - 1] = 0;
4968 const wxChar
*p
= dt
.ParseDate(buf
);
4971 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
4977 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
4980 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
4981 dt
.Format(_T("%b %d, %Y")).c_str(),
4983 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4984 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4985 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4988 wxPuts(_T("\n*** done ***"));
4991 static void TestTimeMS()
4993 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
4995 wxDateTime dt1
= wxDateTime::Now(),
4996 dt2
= wxDateTime::UNow();
4998 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
4999 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
5000 wxPrintf(_T("Dummy loop: "));
5001 for ( int i
= 0; i
< 6000; i
++ )
5003 //for ( int j = 0; j < 10; j++ )
5006 s
.Printf(_T("%g"), sqrt(i
));
5012 wxPuts(_T(", done"));
5015 dt2
= wxDateTime::UNow();
5016 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
5018 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
5020 wxPuts(_T("\n*** done ***"));
5023 static void TestTimeArithmetics()
5025 wxPuts(_T("\n*** testing arithmetic operations on wxDateTime ***"));
5027 static const struct ArithmData
5029 ArithmData(const wxDateSpan
& sp
, const wxChar
*nam
)
5030 : span(sp
), name(nam
) { }
5034 } testArithmData
[] =
5036 ArithmData(wxDateSpan::Day(), _T("day")),
5037 ArithmData(wxDateSpan::Week(), _T("week")),
5038 ArithmData(wxDateSpan::Month(), _T("month")),
5039 ArithmData(wxDateSpan::Year(), _T("year")),
5040 ArithmData(wxDateSpan(1, 2, 3, 4), _T("year, 2 months, 3 weeks, 4 days")),
5043 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
5045 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
5047 wxDateSpan span
= testArithmData
[n
].span
;
5051 const wxChar
*name
= testArithmData
[n
].name
;
5052 wxPrintf(_T("%s + %s = %s, %s - %s = %s\n"),
5053 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
5054 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
5056 wxPrintf(_T("Going back: %s"), (dt1
- span
).FormatISODate().c_str());
5057 if ( dt1
- span
== dt
)
5059 wxPuts(_T(" (ok)"));
5063 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.FormatISODate().c_str());
5066 wxPrintf(_T("Going forward: %s"), (dt2
+ span
).FormatISODate().c_str());
5067 if ( dt2
+ span
== dt
)
5069 wxPuts(_T(" (ok)"));
5073 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.FormatISODate().c_str());
5076 wxPrintf(_T("Double increment: %s"), (dt2
+ 2*span
).FormatISODate().c_str());
5077 if ( dt2
+ 2*span
== dt1
)
5079 wxPuts(_T(" (ok)"));
5083 wxPrintf(_T(" (ERROR: should be %s)\n"), dt2
.FormatISODate().c_str());
5090 static void TestTimeHolidays()
5092 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
5094 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
5095 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
5096 dtEnd
= dtStart
.GetLastMonthDay();
5098 wxDateTimeArray hol
;
5099 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
5101 const wxChar
*format
= _T("%d-%b-%Y (%a)");
5103 wxPrintf(_T("All holidays between %s and %s:\n"),
5104 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
5106 size_t count
= hol
.GetCount();
5107 for ( size_t n
= 0; n
< count
; n
++ )
5109 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
5115 static void TestTimeZoneBug()
5117 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
5119 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
5120 for ( int i
= 0; i
< 31; i
++ )
5122 wxPrintf(_T("Date %s: week day %s.\n"),
5123 date
.Format(_T("%d-%m-%Y")).c_str(),
5124 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
5126 date
+= wxDateSpan::Day();
5132 static void TestTimeSpanFormat()
5134 wxPuts(_T("\n*** wxTimeSpan tests ***"));
5136 static const wxChar
*formats
[] =
5138 _T("(default) %H:%M:%S"),
5139 _T("%E weeks and %D days"),
5140 _T("%l milliseconds"),
5141 _T("(with ms) %H:%M:%S:%l"),
5142 _T("100%% of minutes is %M"), // test "%%"
5143 _T("%D days and %H hours"),
5144 _T("or also %S seconds"),
5147 wxTimeSpan
ts1(1, 2, 3, 4),
5149 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
5151 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
5152 ts1
.Format(formats
[n
]).c_str(),
5153 ts2
.Format(formats
[n
]).c_str());
5161 // test compatibility with the old wxDate/wxTime classes
5162 static void TestTimeCompatibility()
5164 wxPuts(_T("\n*** wxDateTime compatibility test ***"));
5166 wxPrintf(_T("wxDate for JDN 0: %s\n"), wxDate(0l).FormatDate().c_str());
5167 wxPrintf(_T("wxDate for MJD 0: %s\n"), wxDate(2400000).FormatDate().c_str());
5169 double jdnNow
= wxDateTime::Now().GetJDN();
5170 long jdnMidnight
= (long)(jdnNow
- 0.5);
5171 wxPrintf(_T("wxDate for today: %s\n"), wxDate(jdnMidnight
).FormatDate().c_str());
5173 jdnMidnight
= wxDate().Set().GetJulianDate();
5174 wxPrintf(_T("wxDateTime for today: %s\n"),
5175 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
5177 int flags
= wxEUROPEAN
;//wxFULL;
5180 wxPrintf(_T("Today is %s\n"), date
.FormatDate(flags
).c_str());
5181 for ( int n
= 0; n
< 7; n
++ )
5183 wxPrintf(_T("Previous %s is %s\n"),
5184 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
5185 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
5191 #endif // TEST_DATETIME
5193 // ----------------------------------------------------------------------------
5194 // wxTextInput/OutputStream
5195 // ----------------------------------------------------------------------------
5197 #ifdef TEST_TEXTSTREAM
5199 #include "wx/txtstrm.h"
5200 #include "wx/wfstream.h"
5202 static void TestTextInputStream()
5204 wxPuts(_T("\n*** wxTextInputStream test ***"));
5206 wxFileInputStream
fsIn(_T("testdata.fc"));
5209 wxPuts(_T("ERROR: couldn't open file."));
5213 wxTextInputStream
tis(fsIn
);
5218 const wxString s
= tis
.ReadLine();
5220 // line could be non empty if the last line of the file isn't
5221 // terminated with EOL
5222 if ( fsIn
.Eof() && s
.empty() )
5225 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
5230 #endif // TEST_TEXTSTREAM
5232 // ----------------------------------------------------------------------------
5234 // ----------------------------------------------------------------------------
5238 #include "wx/thread.h"
5240 static size_t gs_counter
= (size_t)-1;
5241 static wxCriticalSection gs_critsect
;
5242 static wxSemaphore gs_cond
;
5244 class MyJoinableThread
: public wxThread
5247 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
5248 { m_n
= n
; Create(); }
5250 // thread execution starts here
5251 virtual ExitCode
Entry();
5257 wxThread::ExitCode
MyJoinableThread::Entry()
5259 unsigned long res
= 1;
5260 for ( size_t n
= 1; n
< m_n
; n
++ )
5264 // it's a loooong calculation :-)
5268 return (ExitCode
)res
;
5271 class MyDetachedThread
: public wxThread
5274 MyDetachedThread(size_t n
, wxChar ch
)
5278 m_cancelled
= false;
5283 // thread execution starts here
5284 virtual ExitCode
Entry();
5287 virtual void OnExit();
5290 size_t m_n
; // number of characters to write
5291 wxChar m_ch
; // character to write
5293 bool m_cancelled
; // false if we exit normally
5296 wxThread::ExitCode
MyDetachedThread::Entry()
5299 wxCriticalSectionLocker
lock(gs_critsect
);
5300 if ( gs_counter
== (size_t)-1 )
5306 for ( size_t n
= 0; n
< m_n
; n
++ )
5308 if ( TestDestroy() )
5318 wxThread::Sleep(100);
5324 void MyDetachedThread::OnExit()
5326 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
5328 wxCriticalSectionLocker
lock(gs_critsect
);
5329 if ( !--gs_counter
&& !m_cancelled
)
5333 static void TestDetachedThreads()
5335 wxPuts(_T("\n*** Testing detached threads ***"));
5337 static const size_t nThreads
= 3;
5338 MyDetachedThread
*threads
[nThreads
];
5340 for ( n
= 0; n
< nThreads
; n
++ )
5342 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
5345 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
5346 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
5348 for ( n
= 0; n
< nThreads
; n
++ )
5353 // wait until all threads terminate
5359 static void TestJoinableThreads()
5361 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
5363 // calc 10! in the background
5364 MyJoinableThread
thread(10);
5367 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
5368 (unsigned long)thread
.Wait());
5371 static void TestThreadSuspend()
5373 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
5375 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
5379 // this is for this demo only, in a real life program we'd use another
5380 // condition variable which would be signaled from wxThread::Entry() to
5381 // tell us that the thread really started running - but here just wait a
5382 // bit and hope that it will be enough (the problem is, of course, that
5383 // the thread might still not run when we call Pause() which will result
5385 wxThread::Sleep(300);
5387 for ( size_t n
= 0; n
< 3; n
++ )
5391 wxPuts(_T("\nThread suspended"));
5394 // don't sleep but resume immediately the first time
5395 wxThread::Sleep(300);
5397 wxPuts(_T("Going to resume the thread"));
5402 wxPuts(_T("Waiting until it terminates now"));
5404 // wait until the thread terminates
5410 static void TestThreadDelete()
5412 // As above, using Sleep() is only for testing here - we must use some
5413 // synchronisation object instead to ensure that the thread is still
5414 // running when we delete it - deleting a detached thread which already
5415 // terminated will lead to a crash!
5417 wxPuts(_T("\n*** Testing thread delete function ***"));
5419 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
5423 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
5425 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
5429 wxThread::Sleep(300);
5433 wxPuts(_T("\nDeleted a running thread."));
5435 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
5439 wxThread::Sleep(300);
5445 wxPuts(_T("\nDeleted a sleeping thread."));
5447 MyJoinableThread
thread3(20);
5452 wxPuts(_T("\nDeleted a joinable thread."));
5454 MyJoinableThread
thread4(2);
5457 wxThread::Sleep(300);
5461 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
5466 class MyWaitingThread
: public wxThread
5469 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
5472 m_condition
= condition
;
5477 virtual ExitCode
Entry()
5479 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
5484 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
5488 m_condition
->Wait();
5491 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
5499 wxCondition
*m_condition
;
5502 static void TestThreadConditions()
5505 wxCondition
condition(mutex
);
5507 // otherwise its difficult to understand which log messages pertain to
5509 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
5510 // condition.GetId(), gs_cond.GetId());
5512 // create and launch threads
5513 MyWaitingThread
*threads
[10];
5516 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5518 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
5521 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5526 // wait until all threads run
5527 wxPuts(_T("Main thread is waiting for the other threads to start"));
5530 size_t nRunning
= 0;
5531 while ( nRunning
< WXSIZEOF(threads
) )
5537 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
5541 wxPuts(_T("Main thread: all threads started up."));
5544 wxThread::Sleep(500);
5547 // now wake one of them up
5548 wxPrintf(_T("Main thread: about to signal the condition.\n"));
5553 wxThread::Sleep(200);
5555 // wake all the (remaining) threads up, so that they can exit
5556 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
5558 condition
.Broadcast();
5560 // give them time to terminate (dirty!)
5561 wxThread::Sleep(500);
5564 #include "wx/utils.h"
5566 class MyExecThread
: public wxThread
5569 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5575 virtual ExitCode
Entry()
5577 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5584 static void TestThreadExec()
5586 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5588 MyExecThread
thread(_T("true"));
5591 wxPrintf(_T("Main program exit code: %ld.\n"),
5592 wxExecute(_T("false"), wxEXEC_SYNC
));
5594 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5598 #include "wx/datetime.h"
5600 class MySemaphoreThread
: public wxThread
5603 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5604 : wxThread(wxTHREAD_JOINABLE
),
5611 virtual ExitCode
Entry()
5613 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
5614 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5618 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
5619 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5623 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
5624 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5636 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5638 static void TestSemaphore()
5640 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5642 static const int SEM_LIMIT
= 3;
5644 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5645 ArrayThreads threads
;
5647 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5649 threads
.Add(new MySemaphoreThread(i
, &sem
));
5650 threads
.Last()->Run();
5653 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5660 #endif // TEST_THREADS
5662 // ----------------------------------------------------------------------------
5664 // ----------------------------------------------------------------------------
5668 #include "wx/dynarray.h"
5670 typedef unsigned short ushort
;
5672 #define DefineCompare(name, T) \
5674 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5676 return first - second; \
5679 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5681 return *first - *second; \
5684 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5686 return *second - *first; \
5689 DefineCompare(UShort, ushort);
5690 DefineCompare(Int
, int);
5692 // test compilation of all macros
5693 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5694 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5695 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5696 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5698 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5699 #include "wx/arrimpl.cpp"
5700 WX_DEFINE_OBJARRAY(ArrayBars
);
5702 static void PrintArray(const wxChar
* name
, const wxArrayString
& array
)
5704 wxPrintf(_T("Dump of the array '%s'\n"), name
);
5706 size_t nCount
= array
.GetCount();
5707 for ( size_t n
= 0; n
< nCount
; n
++ )
5709 wxPrintf(_T("\t%s[%u] = '%s'\n"), name
, n
, array
[n
].c_str());
5713 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5714 const wxString
& second
)
5716 return first
.length() - second
.length();
5719 #define TestArrayOf(name) \
5721 static void PrintArray(const wxChar* name, const wxSortedArray##name & array) \
5723 wxPrintf(_T("Dump of the array '%s'\n"), name); \
5725 size_t nCount = array.GetCount(); \
5726 for ( size_t n = 0; n < nCount; n++ ) \
5728 wxPrintf(_T("\t%s[%u] = %d\n"), name, n, array[n]); \
5732 static void PrintArray(const wxChar* name, const wxArray##name & array) \
5734 wxPrintf(_T("Dump of the array '%s'\n"), name); \
5736 size_t nCount = array.GetCount(); \
5737 for ( size_t n = 0; n < nCount; n++ ) \
5739 wxPrintf(_T("\t%s[%u] = %d\n"), name, n, array[n]); \
5743 static void TestArrayOf ## name ## s() \
5745 wxPrintf(_T("*** Testing wxArray%s ***\n"), #name); \
5753 wxPuts(_T("Initially:")); \
5754 PrintArray(_T("a"), a); \
5756 wxPuts(_T("After sort:")); \
5757 a.Sort(name ## Compare); \
5758 PrintArray(_T("a"), a); \
5760 wxPuts(_T("After reverse sort:")); \
5761 a.Sort(name ## RevCompare); \
5762 PrintArray(_T("a"), a); \
5764 wxSortedArray##name b; \
5770 wxPuts(_T("Sorted array initially:")); \
5771 PrintArray(_T("b"), b); \
5774 TestArrayOf(UShort
);
5777 static void TestArrayOfObjects()
5779 wxPuts(_T("*** Testing wxObjArray ***\n"));
5783 Bar
bar("second bar (two copies!)");
5785 wxPrintf(_T("Initially: %u objects in the array, %u objects total.\n"),
5786 bars
.GetCount(), Bar::GetNumber());
5788 bars
.Add(new Bar("first bar"));
5791 wxPrintf(_T("Now: %u objects in the array, %u objects total.\n"),
5792 bars
.GetCount(), Bar::GetNumber());
5794 bars
.RemoveAt(1, bars
.GetCount() - 1);
5796 wxPrintf(_T("After removing all but first element: %u objects in the ")
5797 _T("array, %u objects total.\n"),
5798 bars
.GetCount(), Bar::GetNumber());
5802 wxPrintf(_T("After Empty(): %u objects in the array, %u objects total.\n"),
5803 bars
.GetCount(), Bar::GetNumber());
5806 wxPrintf(_T("Finally: no more objects in the array, %u objects total.\n"),
5810 #endif // TEST_ARRAYS
5812 // ----------------------------------------------------------------------------
5814 // ----------------------------------------------------------------------------
5818 #include "wx/timer.h"
5819 #include "wx/tokenzr.h"
5821 static void TestStringConstruction()
5823 wxPuts(_T("*** Testing wxString constructores ***"));
5825 #define TEST_CTOR(args, res) \
5828 wxPrintf(_T("wxString%s = %s "), #args, s.c_str()); \
5831 wxPuts(_T("(ok)")); \
5835 wxPrintf(_T("(ERROR: should be %s)\n"), res); \
5839 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5840 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5841 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5842 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5844 static const wxChar
*s
= _T("?really!");
5845 const wxChar
*start
= wxStrchr(s
, _T('r'));
5846 const wxChar
*end
= wxStrchr(s
, _T('!'));
5847 TEST_CTOR((start
, end
), _T("really"));
5852 static void TestString()
5862 for (int i
= 0; i
< 1000000; ++i
)
5866 c
= "! How'ya doin'?";
5869 c
= "Hello world! What's up?";
5874 wxPrintf(_T("TestString elapsed time: %ld\n"), sw
.Time());
5877 static void TestPChar()
5885 for (int i
= 0; i
< 1000000; ++i
)
5887 wxStrcpy (a
, _T("Hello"));
5888 wxStrcpy (b
, _T(" world"));
5889 wxStrcpy (c
, _T("! How'ya doin'?"));
5892 wxStrcpy (c
, _T("Hello world! What's up?"));
5893 if (wxStrcmp (c
, a
) == 0)
5894 wxStrcpy (c
, _T("Doh!"));
5897 wxPrintf(_T("TestPChar elapsed time: %ld\n"), sw
.Time());
5900 static void TestStringSub()
5902 wxString
s("Hello, world!");
5904 wxPuts(_T("*** Testing wxString substring extraction ***"));
5906 wxPrintf(_T("String = '%s'\n"), s
.c_str());
5907 wxPrintf(_T("Left(5) = '%s'\n"), s
.Left(5).c_str());
5908 wxPrintf(_T("Right(6) = '%s'\n"), s
.Right(6).c_str());
5909 wxPrintf(_T("Mid(3, 5) = '%s'\n"), s(3, 5).c_str());
5910 wxPrintf(_T("Mid(3) = '%s'\n"), s
.Mid(3).c_str());
5911 wxPrintf(_T("substr(3, 5) = '%s'\n"), s
.substr(3, 5).c_str());
5912 wxPrintf(_T("substr(3) = '%s'\n"), s
.substr(3).c_str());
5914 static const wxChar
*prefixes
[] =
5918 _T("Hello, world!"),
5919 _T("Hello, world!!!"),
5925 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5927 wxString prefix
= prefixes
[n
], rest
;
5928 bool rc
= s
.StartsWith(prefix
, &rest
);
5929 wxPrintf(_T("StartsWith('%s') = %s"), prefix
.c_str(), rc
? _T("true") : _T("false"));
5932 wxPrintf(_T(" (the rest is '%s')\n"), rest
.c_str());
5943 static void TestStringFormat()
5945 wxPuts(_T("*** Testing wxString formatting ***"));
5948 s
.Printf(_T("%03d"), 18);
5950 wxPrintf(_T("Number 18: %s\n"), wxString::Format(_T("%03d"), 18).c_str());
5951 wxPrintf(_T("Number 18: %s\n"), s
.c_str());
5956 // returns "not found" for npos, value for all others
5957 static wxString
PosToString(size_t res
)
5959 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5960 : wxString::Format(_T("%u"), res
);
5964 static void TestStringFind()
5966 wxPuts(_T("*** Testing wxString find() functions ***"));
5968 static const wxChar
*strToFind
= _T("ell");
5969 static const struct StringFindTest
5973 result
; // of searching "ell" in str
5976 { _T("Well, hello world"), 0, 1 },
5977 { _T("Well, hello world"), 6, 7 },
5978 { _T("Well, hello world"), 9, wxString::npos
},
5981 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5983 const StringFindTest
& ft
= findTestData
[n
];
5984 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5986 wxPrintf(_T("Index of '%s' in '%s' starting from %u is %s "),
5987 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5989 size_t resTrue
= ft
.result
;
5990 if ( res
== resTrue
)
5996 wxPrintf(_T("(ERROR: should be %s)\n"),
5997 PosToString(resTrue
).c_str());
6004 static void TestStringTokenizer()
6006 wxPuts(_T("*** Testing wxStringTokenizer ***"));
6008 static const wxChar
*modeNames
[] =
6012 _T("return all empty"),
6017 static const struct StringTokenizerTest
6019 const wxChar
*str
; // string to tokenize
6020 const wxChar
*delims
; // delimiters to use
6021 size_t count
; // count of token
6022 wxStringTokenizerMode mode
; // how should we tokenize it
6023 } tokenizerTestData
[] =
6025 { _T(""), _T(" "), 0 },
6026 { _T("Hello, world"), _T(" "), 2 },
6027 { _T("Hello, world "), _T(" "), 2 },
6028 { _T("Hello, world"), _T(","), 2 },
6029 { _T("Hello, world!"), _T(",!"), 2 },
6030 { _T("Hello,, world!"), _T(",!"), 3 },
6031 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
6032 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
6033 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
6034 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
6035 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
6036 { _T("01/02/99"), _T("/-"), 3 },
6037 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
6040 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
6042 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
6043 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
6045 size_t count
= tkz
.CountTokens();
6046 wxPrintf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
6047 MakePrintable(tt
.str
).c_str(),
6049 MakePrintable(tt
.delims
).c_str(),
6050 modeNames
[tkz
.GetMode()]);
6051 if ( count
== tt
.count
)
6057 wxPrintf(_T("(ERROR: should be %u)\n"), tt
.count
);
6062 // if we emulate strtok(), check that we do it correctly
6063 wxChar
*buf
, *s
= NULL
, *last
;
6065 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
6067 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
6068 wxStrcpy(buf
, tt
.str
);
6070 s
= wxStrtok(buf
, tt
.delims
, &last
);
6077 // now show the tokens themselves
6079 while ( tkz
.HasMoreTokens() )
6081 wxString token
= tkz
.GetNextToken();
6083 wxPrintf(_T("\ttoken %u: '%s'"),
6085 MakePrintable(token
).c_str());
6091 wxPuts(_T(" (ok)"));
6095 wxPrintf(_T(" (ERROR: should be %s)\n"), s
);
6098 s
= wxStrtok(NULL
, tt
.delims
, &last
);
6102 // nothing to compare with
6107 if ( count2
!= count
)
6109 wxPuts(_T("\tERROR: token count mismatch"));
6118 static void TestStringReplace()
6120 wxPuts(_T("*** Testing wxString::replace ***"));
6122 static const struct StringReplaceTestData
6124 const wxChar
*original
; // original test string
6125 size_t start
, len
; // the part to replace
6126 const wxChar
*replacement
; // the replacement string
6127 const wxChar
*result
; // and the expected result
6128 } stringReplaceTestData
[] =
6130 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
6131 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
6132 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
6133 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
6134 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
6137 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
6139 const StringReplaceTestData data
= stringReplaceTestData
[n
];
6141 wxString original
= data
.original
;
6142 original
.replace(data
.start
, data
.len
, data
.replacement
);
6144 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
6145 data
.original
, data
.start
, data
.len
, data
.replacement
,
6148 if ( original
== data
.result
)
6154 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
6161 static void TestStringMatch()
6163 wxPuts(_T("*** Testing wxString::Matches() ***"));
6165 static const struct StringMatchTestData
6168 const wxChar
*wildcard
;
6170 } stringMatchTestData
[] =
6172 { _T("foobar"), _T("foo*"), 1 },
6173 { _T("foobar"), _T("*oo*"), 1 },
6174 { _T("foobar"), _T("*bar"), 1 },
6175 { _T("foobar"), _T("??????"), 1 },
6176 { _T("foobar"), _T("f??b*"), 1 },
6177 { _T("foobar"), _T("f?b*"), 0 },
6178 { _T("foobar"), _T("*goo*"), 0 },
6179 { _T("foobar"), _T("*foo"), 0 },
6180 { _T("foobarfoo"), _T("*foo"), 1 },
6181 { _T(""), _T("*"), 1 },
6182 { _T(""), _T("?"), 0 },
6185 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
6187 const StringMatchTestData
& data
= stringMatchTestData
[n
];
6188 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
6189 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
6191 matches
? _T("matches") : _T("doesn't match"),
6193 matches
== data
.matches
? _T("ok") : _T("ERROR"));
6199 #endif // TEST_STRINGS
6201 // ----------------------------------------------------------------------------
6203 // ----------------------------------------------------------------------------
6205 #ifdef TEST_SNGLINST
6206 #include "wx/snglinst.h"
6207 #endif // TEST_SNGLINST
6209 int main(int argc
, char **argv
)
6211 wxApp::CheckBuildOptions(wxBuildOptions());
6213 wxInitializer initializer
;
6216 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
6221 #ifdef TEST_SNGLINST
6222 wxSingleInstanceChecker checker
;
6223 if ( checker
.Create(_T(".wxconsole.lock")) )
6225 if ( checker
.IsAnotherRunning() )
6227 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
6232 // wait some time to give time to launch another instance
6233 wxPrintf(_T("Press \"Enter\" to continue..."));
6236 else // failed to create
6238 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
6240 #endif // TEST_SNGLINST
6244 #endif // TEST_CHARSET
6247 TestCmdLineConvert();
6249 #if wxUSE_CMDLINE_PARSER
6250 static const wxCmdLineEntryDesc cmdLineDesc
[] =
6252 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
6253 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
6254 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
6255 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
6257 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
6258 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
6259 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
6260 wxCMD_LINE_VAL_NUMBER
},
6261 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
6262 wxCMD_LINE_VAL_DATE
},
6264 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
6265 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
6271 wxChar
**wargv
= new wxChar
*[argc
+ 1];
6274 for ( int n
= 0; n
< argc
; n
++ )
6276 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
6277 wargv
[n
] = wxStrdup(warg
);
6284 #endif // wxUSE_UNICODE
6286 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
6290 for ( int n
= 0; n
< argc
; n
++ )
6295 #endif // wxUSE_UNICODE
6297 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
6298 wxCMD_LINE_VAL_STRING
,
6299 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
6301 switch ( parser
.Parse() )
6304 wxLogMessage(_T("Help was given, terminating."));
6308 ShowCmdLine(parser
);
6312 wxLogMessage(_T("Syntax error detected, aborting."));
6315 #endif // wxUSE_CMDLINE_PARSER
6317 #endif // TEST_CMDLINE
6325 TestStringConstruction();
6328 TestStringTokenizer();
6329 TestStringReplace();
6335 #endif // TEST_STRINGS
6341 a1
.Add(_T("tiger"));
6343 a1
.Add(_T("lion"), 3);
6345 a1
.Add(_T("human"));
6348 wxPuts(_T("*** Initially:"));
6350 PrintArray(_T("a1"), a1
);
6352 wxArrayString
a2(a1
);
6353 PrintArray(_T("a2"), a2
);
6355 wxSortedArrayString
a3(a1
);
6356 PrintArray(_T("a3"), a3
);
6358 wxPuts(_T("*** After deleting three strings from a1"));
6361 PrintArray(_T("a1"), a1
);
6362 PrintArray(_T("a2"), a2
);
6363 PrintArray(_T("a3"), a3
);
6365 wxPuts(_T("*** After reassigning a1 to a2 and a3"));
6367 PrintArray(_T("a2"), a2
);
6368 PrintArray(_T("a3"), a3
);
6370 wxPuts(_T("*** After sorting a1"));
6372 PrintArray(_T("a1"), a1
);
6374 wxPuts(_T("*** After sorting a1 in reverse order"));
6376 PrintArray(_T("a1"), a1
);
6378 wxPuts(_T("*** After sorting a1 by the string length"));
6379 a1
.Sort(StringLenCompare
);
6380 PrintArray(_T("a1"), a1
);
6382 TestArrayOfObjects();
6383 TestArrayOfUShorts();
6387 #endif // TEST_ARRAYS
6398 #ifdef TEST_DLLLOADER
6400 #endif // TEST_DLLLOADER
6404 #endif // TEST_ENVIRON
6408 #endif // TEST_EXECUTE
6410 #ifdef TEST_FILECONF
6412 #endif // TEST_FILECONF
6420 #endif // TEST_LOCALE
6423 wxPuts(_T("*** Testing wxLog ***"));
6426 for ( size_t n
= 0; n
< 8000; n
++ )
6428 s
<< (wxChar
)(_T('A') + (n
% 26));
6431 wxLogWarning(_T("The length of the string is %lu"),
6432 (unsigned long)s
.length());
6435 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
6437 // this one shouldn't be truncated
6440 // but this one will because log functions use fixed size buffer
6441 // (note that it doesn't need '\n' at the end neither - will be added
6443 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
6455 #ifdef TEST_FILENAME
6459 fn
.Assign(_T("c:\\foo"), _T("bar.baz"));
6460 fn
.Assign(_T("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc"));
6465 TestFileNameConstruction();
6468 TestFileNameConstruction();
6469 TestFileNameMakeRelative();
6470 TestFileNameMakeAbsolute();
6471 TestFileNameSplit();
6474 TestFileNameComparison();
6475 TestFileNameOperations();
6477 #endif // TEST_FILENAME
6479 #ifdef TEST_FILETIME
6483 #endif // TEST_FILETIME
6486 wxLog::AddTraceMask(FTP_TRACE_MASK
);
6487 if ( TestFtpConnect() )
6498 if ( TEST_INTERACTIVE
)
6499 TestFtpInteractive();
6501 //else: connecting to the FTP server failed
6507 #ifdef TEST_LONGLONG
6508 // seed pseudo random generator
6509 srand((unsigned)time(NULL
));
6518 TestMultiplication();
6521 TestLongLongConversion();
6522 TestBitOperations();
6523 TestLongLongComparison();
6524 TestLongLongToString();
6525 TestLongLongPrintf();
6527 #endif // TEST_LONGLONG
6535 #endif // TEST_HASHMAP
6538 wxLog::AddTraceMask(_T("mime"));
6543 TestMimeAssociate();
6548 #ifdef TEST_INFO_FUNCTIONS
6554 if ( TEST_INTERACTIVE
)
6557 #endif // TEST_INFO_FUNCTIONS
6559 #ifdef TEST_PATHLIST
6561 #endif // TEST_PATHLIST
6569 #endif // TEST_PRINTF
6573 #endif // TEST_REGCONF
6576 // TODO: write a real test using src/regex/tests file
6581 TestRegExSubmatch();
6582 TestRegExReplacement();
6584 if ( TEST_INTERACTIVE
)
6585 TestRegExInteractive();
6587 #endif // TEST_REGEX
6589 #ifdef TEST_REGISTRY
6591 TestRegistryAssociation();
6592 #endif // TEST_REGISTRY
6597 #endif // TEST_SOCKETS
6605 #endif // TEST_STREAMS
6607 #ifdef TEST_TEXTSTREAM
6608 TestTextInputStream();
6609 #endif // TEST_TEXTSTREAM
6612 int nCPUs
= wxThread::GetCPUCount();
6613 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
6615 wxThread::SetConcurrency(nCPUs
);
6617 TestDetachedThreads();
6620 TestJoinableThreads();
6621 TestThreadSuspend();
6623 TestThreadConditions();
6627 #endif // TEST_THREADS
6631 #endif // TEST_TIMER
6633 #ifdef TEST_DATETIME
6646 TestTimeArithmetics();
6649 TestTimeSpanFormat();
6657 if ( TEST_INTERACTIVE
)
6658 TestDateTimeInteractive();
6659 #endif // TEST_DATETIME
6662 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
6664 #endif // TEST_USLEEP
6669 #endif // TEST_VCARD
6673 #endif // TEST_VOLUME
6676 TestUnicodeToFromAscii();
6677 #endif // TEST_UNICODE
6681 TestEncodingConverter();
6682 #endif // TEST_WCHAR
6685 TestZipStreamRead();
6686 TestZipFileSystem();
6690 TestZlibStreamWrite();
6691 TestZlibStreamRead();