1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWidgets
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
24 #include "wx/string.h"
29 // without this pragma, the stupid compiler precompiles #defines below so that
30 // changing them doesn't "take place" later!
35 // ----------------------------------------------------------------------------
36 // conditional compilation
37 // ----------------------------------------------------------------------------
40 A note about all these conditional compilation macros: this file is used
41 both as a test suite for various non-GUI wxWidgets classes and as a
42 scratchpad for quick tests. So there are two compilation modes: if you
43 define TEST_ALL all tests are run, otherwise you may enable the individual
44 tests individually in the "#else" branch below.
47 // what to test (in alphabetic order)? Define TEST_ALL to 0 to do a single
48 // test, define it to 1 to do all tests.
57 #define TEST_DLLLOADER
64 // #define TEST_FTP --FIXME! (RN)
67 #define TEST_INFO_FUNCTIONS
78 #define TEST_SCOPEGUARD
80 // #define TEST_SOCKETS --FIXME! (RN)
82 #define TEST_TEXTSTREAM
85 // #define TEST_VCARD -- don't enable this (VZ)
86 // #define TEST_VOLUME --FIXME! (RN)
96 // some tests are interactive, define this to run them
97 #ifdef TEST_INTERACTIVE
98 #undef TEST_INTERACTIVE
100 #define TEST_INTERACTIVE 1
102 #define TEST_INTERACTIVE 0
105 // ----------------------------------------------------------------------------
106 // test class for container objects
107 // ----------------------------------------------------------------------------
109 #if defined(TEST_LIST)
111 class Bar
// Foo is already taken in the hash test
114 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
115 Bar(const Bar
& bar
) : m_name(bar
.m_name
) { ms_bars
++; }
116 ~Bar() { ms_bars
--; }
118 static size_t GetNumber() { return ms_bars
; }
120 const wxChar
*GetName() const { return m_name
; }
125 static size_t ms_bars
;
128 size_t Bar::ms_bars
= 0;
130 #endif // defined(TEST_LIST)
132 // ============================================================================
134 // ============================================================================
136 // ----------------------------------------------------------------------------
138 // ----------------------------------------------------------------------------
140 #if defined(TEST_SOCKETS)
142 // replace TABs with \t and CRs with \n
143 static wxString
MakePrintable(const wxChar
*s
)
146 (void)str
.Replace(_T("\t"), _T("\\t"));
147 (void)str
.Replace(_T("\n"), _T("\\n"));
148 (void)str
.Replace(_T("\r"), _T("\\r"));
153 #endif // MakePrintable() is used
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
161 #include "wx/cmdline.h"
162 #include "wx/datetime.h"
164 #if wxUSE_CMDLINE_PARSER
166 static void ShowCmdLine(const wxCmdLineParser
& parser
)
168 wxString s
= _T("Input files: ");
170 size_t count
= parser
.GetParamCount();
171 for ( size_t param
= 0; param
< count
; param
++ )
173 s
<< parser
.GetParam(param
) << ' ';
177 << _T("Verbose:\t") << (parser
.Found(_T("v")) ? _T("yes") : _T("no")) << '\n'
178 << _T("Quiet:\t") << (parser
.Found(_T("q")) ? _T("yes") : _T("no")) << '\n';
183 if ( parser
.Found(_T("o"), &strVal
) )
184 s
<< _T("Output file:\t") << strVal
<< '\n';
185 if ( parser
.Found(_T("i"), &strVal
) )
186 s
<< _T("Input dir:\t") << strVal
<< '\n';
187 if ( parser
.Found(_T("s"), &lVal
) )
188 s
<< _T("Size:\t") << lVal
<< '\n';
189 if ( parser
.Found(_T("d"), &dt
) )
190 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
191 if ( parser
.Found(_T("project_name"), &strVal
) )
192 s
<< _T("Project:\t") << strVal
<< '\n';
197 #endif // wxUSE_CMDLINE_PARSER
199 static void TestCmdLineConvert()
201 static const wxChar
*cmdlines
[] =
204 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
205 _T("literal \\\" and \"\""),
208 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
210 const wxChar
*cmdline
= cmdlines
[n
];
211 wxPrintf(_T("Parsing: %s\n"), cmdline
);
212 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
214 size_t count
= args
.GetCount();
215 wxPrintf(_T("\targc = %u\n"), count
);
216 for ( size_t arg
= 0; arg
< count
; arg
++ )
218 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
223 #endif // TEST_CMDLINE
225 // ----------------------------------------------------------------------------
227 // ----------------------------------------------------------------------------
234 static const wxChar
*ROOTDIR
= _T("/");
235 static const wxChar
*TESTDIR
= _T("/usr/local/share");
236 #elif defined(__WXMSW__)
237 static const wxChar
*ROOTDIR
= _T("c:\\");
238 static const wxChar
*TESTDIR
= _T("d:\\");
240 #error "don't know where the root directory is"
243 static void TestDirEnumHelper(wxDir
& dir
,
244 int flags
= wxDIR_DEFAULT
,
245 const wxString
& filespec
= wxEmptyString
)
249 if ( !dir
.IsOpened() )
252 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
255 wxPrintf(_T("\t%s\n"), filename
.c_str());
257 cont
= dir
.GetNext(&filename
);
260 wxPuts(wxEmptyString
);
263 static void TestDirEnum()
265 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
267 wxString cwd
= wxGetCwd();
268 if ( !wxDir::Exists(cwd
) )
270 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
275 if ( !dir
.IsOpened() )
277 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
281 wxPuts(_T("Enumerating everything in current directory:"));
282 TestDirEnumHelper(dir
);
284 wxPuts(_T("Enumerating really everything in current directory:"));
285 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
287 wxPuts(_T("Enumerating object files in current directory:"));
288 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, _T("*.o*"));
290 wxPuts(_T("Enumerating directories in current directory:"));
291 TestDirEnumHelper(dir
, wxDIR_DIRS
);
293 wxPuts(_T("Enumerating files in current directory:"));
294 TestDirEnumHelper(dir
, wxDIR_FILES
);
296 wxPuts(_T("Enumerating files including hidden in current directory:"));
297 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
301 wxPuts(_T("Enumerating everything in root directory:"));
302 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
304 wxPuts(_T("Enumerating directories in root directory:"));
305 TestDirEnumHelper(dir
, wxDIR_DIRS
);
307 wxPuts(_T("Enumerating files in root directory:"));
308 TestDirEnumHelper(dir
, wxDIR_FILES
);
310 wxPuts(_T("Enumerating files including hidden in root directory:"));
311 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
313 wxPuts(_T("Enumerating files in non existing directory:"));
314 wxDir
dirNo(_T("nosuchdir"));
315 TestDirEnumHelper(dirNo
);
318 class DirPrintTraverser
: public wxDirTraverser
321 virtual wxDirTraverseResult
OnFile(const wxString
& WXUNUSED(filename
))
323 return wxDIR_CONTINUE
;
326 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
328 wxString path
, name
, ext
;
329 wxSplitPath(dirname
, &path
, &name
, &ext
);
332 name
<< _T('.') << ext
;
335 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
337 if ( wxIsPathSeparator(*p
) )
341 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
343 return wxDIR_CONTINUE
;
347 static void TestDirTraverse()
349 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
353 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
354 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
357 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
358 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
361 // enum again with custom traverser
362 wxPuts(_T("Now enumerating directories:"));
364 DirPrintTraverser traverser
;
365 dir
.Traverse(traverser
, wxEmptyString
, wxDIR_DIRS
| wxDIR_HIDDEN
);
368 static void TestDirExists()
370 wxPuts(_T("*** Testing wxDir::Exists() ***"));
372 static const wxChar
*dirnames
[] =
375 #if defined(__WXMSW__)
378 _T("\\\\share\\file"),
382 _T("c:\\autoexec.bat"),
383 #elif defined(__UNIX__)
392 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
394 wxPrintf(_T("%-40s: %s\n"),
396 wxDir::Exists(dirnames
[n
]) ? _T("exists")
397 : _T("doesn't exist"));
403 // ----------------------------------------------------------------------------
405 // ----------------------------------------------------------------------------
407 #ifdef TEST_DLLLOADER
409 #include "wx/dynlib.h"
411 static void TestDllLoad()
413 #if defined(__WXMSW__)
414 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
415 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
416 #elif defined(__UNIX__)
417 // weird: using just libc.so does *not* work!
418 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
419 static const wxChar
*FUNC_NAME
= _T("strlen");
421 #error "don't know how to test wxDllLoader on this platform"
424 wxPuts(_T("*** testing wxDllLoader ***\n"));
426 wxDynamicLibrary
lib(LIB_NAME
);
427 if ( !lib
.IsLoaded() )
429 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
433 typedef int (*wxStrlenType
)(const char *);
434 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
437 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
438 FUNC_NAME
, LIB_NAME
);
442 if ( pfnStrlen("foo") != 3 )
444 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
448 wxPuts(_T("... ok"));
454 #endif // TEST_DLLLOADER
456 // ----------------------------------------------------------------------------
458 // ----------------------------------------------------------------------------
462 #include "wx/utils.h"
464 static wxString
MyGetEnv(const wxString
& var
)
467 if ( !wxGetEnv(var
, &val
) )
470 val
= wxString(_T('\'')) + val
+ _T('\'');
475 static void TestEnvironment()
477 const wxChar
*var
= _T("wxTestVar");
479 wxPuts(_T("*** testing environment access functions ***"));
481 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
482 wxSetEnv(var
, _T("value for wxTestVar"));
483 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
484 wxSetEnv(var
, _T("another value"));
485 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
487 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
488 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
491 #endif // TEST_ENVIRON
493 // ----------------------------------------------------------------------------
495 // ----------------------------------------------------------------------------
499 #include "wx/utils.h"
501 static void TestExecute()
503 wxPuts(_T("*** testing wxExecute ***"));
506 #define COMMAND "cat -n ../../Makefile" // "echo hi"
507 #define SHELL_COMMAND "echo hi from shell"
508 #define REDIRECT_COMMAND COMMAND // "date"
509 #elif defined(__WXMSW__)
510 #define COMMAND "command.com /c echo hi"
511 #define SHELL_COMMAND "echo hi"
512 #define REDIRECT_COMMAND COMMAND
514 #error "no command to exec"
517 wxPrintf(_T("Testing wxShell: "));
519 if ( wxShell(_T(SHELL_COMMAND
)) )
522 wxPuts(_T("ERROR."));
524 wxPrintf(_T("Testing wxExecute: "));
526 if ( wxExecute(_T(COMMAND
), true /* sync */) == 0 )
529 wxPuts(_T("ERROR."));
531 #if 0 // no, it doesn't work (yet?)
532 wxPrintf(_T("Testing async wxExecute: "));
534 if ( wxExecute(COMMAND
) != 0 )
535 wxPuts(_T("Ok (command launched)."));
537 wxPuts(_T("ERROR."));
540 wxPrintf(_T("Testing wxExecute with redirection:\n"));
541 wxArrayString output
;
542 if ( wxExecute(_T(REDIRECT_COMMAND
), output
) != 0 )
544 wxPuts(_T("ERROR."));
548 size_t count
= output
.GetCount();
549 for ( size_t n
= 0; n
< count
; n
++ )
551 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
558 #endif // TEST_EXECUTE
560 // ----------------------------------------------------------------------------
562 // ----------------------------------------------------------------------------
567 #include "wx/ffile.h"
568 #include "wx/textfile.h"
570 static void TestFileRead()
572 wxPuts(_T("*** wxFile read test ***"));
574 wxFile
file(_T("testdata.fc"));
575 if ( file
.IsOpened() )
577 wxPrintf(_T("File length: %lu\n"), file
.Length());
579 wxPuts(_T("File dump:\n----------"));
581 static const off_t len
= 1024;
585 off_t nRead
= file
.Read(buf
, len
);
586 if ( nRead
== wxInvalidOffset
)
588 wxPrintf(_T("Failed to read the file."));
592 fwrite(buf
, nRead
, 1, stdout
);
598 wxPuts(_T("----------"));
602 wxPrintf(_T("ERROR: can't open test file.\n"));
605 wxPuts(wxEmptyString
);
608 static void TestTextFileRead()
610 wxPuts(_T("*** wxTextFile read test ***"));
612 wxTextFile
file(_T("testdata.fc"));
615 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
616 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
620 wxPuts(_T("\nDumping the entire file:"));
621 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
623 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
625 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
627 wxPuts(_T("\nAnd now backwards:"));
628 for ( s
= file
.GetLastLine();
629 file
.GetCurrentLine() != 0;
630 s
= file
.GetPrevLine() )
632 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
634 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
638 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
641 wxPuts(wxEmptyString
);
644 static void TestFileCopy()
646 wxPuts(_T("*** Testing wxCopyFile ***"));
648 static const wxChar
*filename1
= _T("testdata.fc");
649 static const wxChar
*filename2
= _T("test2");
650 if ( !wxCopyFile(filename1
, filename2
) )
652 wxPuts(_T("ERROR: failed to copy file"));
656 wxFFile
f1(filename1
, _T("rb")),
657 f2(filename2
, _T("rb"));
659 if ( !f1
.IsOpened() || !f2
.IsOpened() )
661 wxPuts(_T("ERROR: failed to open file(s)"));
666 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
668 wxPuts(_T("ERROR: failed to read file(s)"));
672 if ( (s1
.length() != s2
.length()) ||
673 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
675 wxPuts(_T("ERROR: copy error!"));
679 wxPuts(_T("File was copied ok."));
685 if ( !wxRemoveFile(filename2
) )
687 wxPuts(_T("ERROR: failed to remove the file"));
690 wxPuts(wxEmptyString
);
695 // ----------------------------------------------------------------------------
697 // ----------------------------------------------------------------------------
701 #include "wx/confbase.h"
702 #include "wx/fileconf.h"
704 static const struct FileConfTestData
706 const wxChar
*name
; // value name
707 const wxChar
*value
; // the value from the file
710 { _T("value1"), _T("one") },
711 { _T("value2"), _T("two") },
712 { _T("novalue"), _T("default") },
715 static void TestFileConfRead()
717 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
719 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
720 _T("testdata.fc"), wxEmptyString
,
721 wxCONFIG_USE_RELATIVE_PATH
);
723 // test simple reading
724 wxPuts(_T("\nReading config file:"));
725 wxString
defValue(_T("default")), value
;
726 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
728 const FileConfTestData
& data
= fcTestData
[n
];
729 value
= fileconf
.Read(data
.name
, defValue
);
730 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
731 if ( value
== data
.value
)
737 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
741 // test enumerating the entries
742 wxPuts(_T("\nEnumerating all root entries:"));
745 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
748 wxPrintf(_T("\t%s = %s\n"),
750 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
752 cont
= fileconf
.GetNextEntry(name
, dummy
);
755 static const wxChar
*testEntry
= _T("TestEntry");
756 wxPrintf(_T("\nTesting deletion of newly created \"Test\" entry: "));
757 fileconf
.Write(testEntry
, _T("A value"));
758 fileconf
.DeleteEntry(testEntry
);
759 wxPrintf(fileconf
.HasEntry(testEntry
) ? _T("ERROR\n") : _T("ok\n"));
762 #endif // TEST_FILECONF
764 // ----------------------------------------------------------------------------
766 // ----------------------------------------------------------------------------
770 #include "wx/filename.h"
773 static void DumpFileName(const wxChar
*desc
, const wxFileName
& fn
)
777 wxString full
= fn
.GetFullPath();
779 wxString vol
, path
, name
, ext
;
780 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
782 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
783 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
785 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
786 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
787 path
.c_str(), name
.c_str(), ext
.c_str());
789 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
790 wxPrintf(_T("with volume: \t'%s'\n"),
791 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
792 wxPrintf(_T("with separator:\t'%s'\n"),
793 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
794 wxPrintf(_T("with both: \t'%s'\n"),
795 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
797 wxPuts(_T("The directories in the path are:"));
798 wxArrayString dirs
= fn
.GetDirs();
799 size_t count
= dirs
.GetCount();
800 for ( size_t n
= 0; n
< count
; n
++ )
802 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
807 static struct FileNameInfo
809 const wxChar
*fullname
;
810 const wxChar
*volume
;
819 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), true, wxPATH_UNIX
},
820 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), true, wxPATH_UNIX
},
821 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), true, wxPATH_UNIX
},
822 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), false, wxPATH_UNIX
},
823 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), false, wxPATH_UNIX
},
824 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), true, wxPATH_UNIX
},
825 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), true, wxPATH_UNIX
},
826 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), false, wxPATH_UNIX
},
827 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), true, wxPATH_UNIX
},
829 // Windows file names
830 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), false, wxPATH_DOS
},
831 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), false, wxPATH_DOS
},
832 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), false, wxPATH_DOS
},
833 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), true, wxPATH_DOS
},
834 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), true, wxPATH_DOS
},
835 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), true, wxPATH_DOS
},
836 { _T("\\\\server\\dir\\foo.bar"), _T("server"), _T("\\dir"), _T("foo"), _T("bar"), true, wxPATH_DOS
},
838 // wxFileName support for Mac file names is broken currently
841 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), true, wxPATH_MAC
},
842 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), true, wxPATH_MAC
},
843 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), true, wxPATH_MAC
},
844 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), false, wxPATH_MAC
},
845 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), false, wxPATH_MAC
},
846 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), false, wxPATH_MAC
},
850 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), true, wxPATH_VMS
},
851 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), false, wxPATH_VMS
},
854 static void TestFileNameConstruction()
856 wxPuts(_T("*** testing wxFileName construction ***"));
858 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
860 const FileNameInfo
& fni
= filenames
[n
];
862 wxFileName
fn(fni
.fullname
, fni
.format
);
864 wxString fullname
= fn
.GetFullPath(fni
.format
);
865 if ( fullname
!= fni
.fullname
)
867 wxPrintf(_T("ERROR: fullname should be '%s'\n"), fni
.fullname
);
870 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
871 wxPrintf(_T("'%s' is %s (%s)\n\t"),
873 isAbsolute
? "absolute" : "relative",
874 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
876 if ( !fn
.Normalize(wxPATH_NORM_ALL
, wxEmptyString
, fni
.format
) )
878 wxPuts(_T("ERROR (couldn't be normalized)"));
882 wxPrintf(_T("normalized: '%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
886 wxPuts(wxEmptyString
);
889 static void TestFileNameSplit()
891 wxPuts(_T("*** testing wxFileName splitting ***"));
893 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
895 const FileNameInfo
& fni
= filenames
[n
];
896 wxString volume
, path
, name
, ext
;
897 wxFileName::SplitPath(fni
.fullname
,
898 &volume
, &path
, &name
, &ext
, fni
.format
);
900 wxPrintf(_T("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'"),
902 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
904 if ( volume
!= fni
.volume
)
905 wxPrintf(_T(" (ERROR: volume = '%s')"), fni
.volume
);
906 if ( path
!= fni
.path
)
907 wxPrintf(_T(" (ERROR: path = '%s')"), fni
.path
);
908 if ( name
!= fni
.name
)
909 wxPrintf(_T(" (ERROR: name = '%s')"), fni
.name
);
910 if ( ext
!= fni
.ext
)
911 wxPrintf(_T(" (ERROR: ext = '%s')"), fni
.ext
);
913 wxPuts(wxEmptyString
);
917 static void TestFileNameTemp()
919 wxPuts(_T("*** testing wxFileName temp file creation ***"));
921 static const wxChar
*tmpprefixes
[] =
929 _T("/tmp/foo/bar"), // this one must be an error
933 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
935 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
938 // "error" is not in upper case because it may be ok
939 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
943 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
944 tmpprefixes
[n
], path
.c_str());
946 if ( !wxRemoveFile(path
) )
948 wxLogWarning(_T("Failed to remove temp file '%s'"),
955 static void TestFileNameMakeRelative()
957 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
959 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
961 const FileNameInfo
& fni
= filenames
[n
];
963 wxFileName
fn(fni
.fullname
, fni
.format
);
965 // choose the base dir of the same format
967 switch ( fni
.format
)
970 base
= _T("/usr/bin/");
979 // TODO: I don't know how this is supposed to work there
982 case wxPATH_NATIVE
: // make gcc happy
984 wxFAIL_MSG( _T("unexpected path format") );
987 wxPrintf(_T("'%s' relative to '%s': "),
988 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
990 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
992 wxPuts(_T("unchanged"));
996 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
1001 static void TestFileNameMakeAbsolute()
1003 wxPuts(_T("*** testing wxFileName::MakeAbsolute() ***"));
1005 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1007 const FileNameInfo
& fni
= filenames
[n
];
1008 wxFileName
fn(fni
.fullname
, fni
.format
);
1010 wxPrintf(_T("'%s' absolutized: "),
1011 fn
.GetFullPath(fni
.format
).c_str());
1013 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
1016 wxPuts(wxEmptyString
);
1019 static void TestFileNameDirManip()
1021 // TODO: test AppendDir(), RemoveDir(), ...
1024 static void TestFileNameComparison()
1029 static void TestFileNameOperations()
1034 static void TestFileNameCwd()
1039 #endif // TEST_FILENAME
1041 // ----------------------------------------------------------------------------
1042 // wxFileName time functions
1043 // ----------------------------------------------------------------------------
1045 #ifdef TEST_FILETIME
1047 #include <wx/filename.h>
1048 #include <wx/datetime.h>
1050 static void TestFileGetTimes()
1052 wxFileName
fn(_T("testdata.fc"));
1054 wxDateTime dtAccess
, dtMod
, dtCreate
;
1055 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1057 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1061 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1063 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1064 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1065 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1066 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1071 static void TestFileSetTimes()
1073 wxFileName
fn(_T("testdata.fc"));
1077 wxPrintf(_T("ERROR: Touch() failed.\n"));
1082 #endif // TEST_FILETIME
1084 // ----------------------------------------------------------------------------
1086 // ----------------------------------------------------------------------------
1090 #include "wx/hashmap.h"
1092 // test compilation of basic map types
1093 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1094 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1095 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1096 myUnsignedHashMap
);
1097 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1099 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1101 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1103 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1107 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1108 // myStringHashMap );
1109 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1111 typedef myStringHashMap::iterator Itor
;
1113 static void TestHashMap()
1115 wxPuts(_T("*** Testing wxHashMap ***\n"));
1116 myStringHashMap
sh(0); // as small as possible
1119 const size_t count
= 10000;
1121 // init with some data
1122 for( i
= 0; i
< count
; ++i
)
1124 buf
.Printf(wxT("%d"), i
);
1125 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1128 // test that insertion worked
1129 if( sh
.size() != count
)
1131 wxPrintf(_T("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n"), sh
.size(), count
);
1134 for( i
= 0; i
< count
; ++i
)
1136 buf
.Printf(wxT("%d"), i
);
1137 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1139 wxPrintf(_T("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n"));
1144 // check that iterators work
1146 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1150 wxPrintf(_T("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n"));
1154 if( it
->second
!= sh
[it
->first
] )
1156 wxPrintf(_T("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n"));
1161 if( sh
.size() != i
)
1163 wxPrintf(_T("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n"), i
, count
);
1166 // test copy ctor, assignment operator
1167 myStringHashMap
h1( sh
), h2( 0 );
1170 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1172 if( h1
[it
->first
] != it
->second
)
1174 wxPrintf(_T("*** ERROR: COPY CTOR BROKEN %s ***\n"), it
->first
.c_str());
1177 if( h2
[it
->first
] != it
->second
)
1179 wxPrintf(_T("*** ERROR: OPERATOR= BROKEN %s ***\n"), it
->first
.c_str());
1184 for( i
= 0; i
< count
; ++i
)
1186 buf
.Printf(wxT("%d"), i
);
1187 size_t sz
= sh
.size();
1189 // test find() and erase(it)
1192 it
= sh
.find( buf
);
1193 if( it
!= sh
.end() )
1197 if( sh
.find( buf
) != sh
.end() )
1199 wxPrintf(_T("*** ERROR: FOUND DELETED ELEMENT %u ***\n"), i
);
1203 wxPrintf(_T("*** ERROR: CANT FIND ELEMENT %u ***\n"), i
);
1208 size_t c
= sh
.erase( buf
);
1210 wxPrintf(_T("*** ERROR: SHOULD RETURN 1 ***\n"));
1212 if( sh
.find( buf
) != sh
.end() )
1214 wxPrintf(_T("*** ERROR: FOUND DELETED ELEMENT %u ***\n"), i
);
1218 // count should decrease
1219 if( sh
.size() != sz
- 1 )
1221 wxPrintf(_T("*** ERROR: COUNT DID NOT DECREASE ***\n"));
1225 wxPrintf(_T("*** Finished testing wxHashMap ***\n"));
1228 #endif // TEST_HASHMAP
1230 // ----------------------------------------------------------------------------
1232 // ----------------------------------------------------------------------------
1236 #include "wx/hashset.h"
1238 // test compilation of basic map types
1239 WX_DECLARE_HASH_SET( int*, wxPointerHash
, wxPointerEqual
, myPtrHashSet
);
1240 WX_DECLARE_HASH_SET( long, wxIntegerHash
, wxIntegerEqual
, myLongHashSet
);
1241 WX_DECLARE_HASH_SET( unsigned long, wxIntegerHash
, wxIntegerEqual
,
1242 myUnsignedHashSet
);
1243 WX_DECLARE_HASH_SET( unsigned int, wxIntegerHash
, wxIntegerEqual
,
1245 WX_DECLARE_HASH_SET( int, wxIntegerHash
, wxIntegerEqual
,
1247 WX_DECLARE_HASH_SET( short, wxIntegerHash
, wxIntegerEqual
,
1249 WX_DECLARE_HASH_SET( unsigned short, wxIntegerHash
, wxIntegerEqual
,
1251 WX_DECLARE_HASH_SET( wxString
, wxStringHash
, wxStringEqual
,
1263 unsigned long operator()(const MyStruct
& s
) const
1264 { return m_dummy(s
.ptr
); }
1265 MyHash
& operator=(const MyHash
&) { return *this; }
1267 wxPointerHash m_dummy
;
1273 bool operator()(const MyStruct
& s1
, const MyStruct
& s2
) const
1274 { return s1
.ptr
== s2
.ptr
; }
1275 MyEqual
& operator=(const MyEqual
&) { return *this; }
1278 WX_DECLARE_HASH_SET( MyStruct
, MyHash
, MyEqual
, mySet
);
1280 typedef myTestHashSet5 wxStringHashSet
;
1282 static void TestHashSet()
1284 wxPrintf(_T("*** Testing wxHashSet ***\n"));
1286 wxStringHashSet set1
;
1288 set1
.insert( _T("abc") );
1289 set1
.insert( _T("bbc") );
1290 set1
.insert( _T("cbc") );
1291 set1
.insert( _T("abc") );
1293 if( set1
.size() != 3 )
1294 wxPrintf(_T("*** ERROR IN INSERT ***\n"));
1300 tmp
.ptr
= &dummy
; tmp
.str
= _T("ABC");
1302 tmp
.ptr
= &dummy
+ 1;
1304 tmp
.ptr
= &dummy
; tmp
.str
= _T("CDE");
1307 if( set2
.size() != 2 )
1308 wxPrintf(_T("*** ERROR IN INSERT - 2 ***\n"));
1310 mySet::iterator it
= set2
.find( tmp
);
1312 if( it
== set2
.end() )
1313 wxPrintf(_T("*** ERROR IN FIND - 1 ***\n"));
1314 if( it
->ptr
!= &dummy
)
1315 wxPrintf(_T("*** ERROR IN FIND - 2 ***\n"));
1316 if( it
->str
!= _T("ABC") )
1317 wxPrintf(_T("*** ERROR IN INSERT - 3 ***\n"));
1319 wxPrintf(_T("*** Finished testing wxHashSet ***\n"));
1322 #endif // TEST_HASHSET
1324 // ----------------------------------------------------------------------------
1326 // ----------------------------------------------------------------------------
1330 #include "wx/list.h"
1332 WX_DECLARE_LIST(Bar
, wxListBars
);
1333 #include "wx/listimpl.cpp"
1334 WX_DEFINE_LIST(wxListBars
);
1336 WX_DECLARE_LIST(int, wxListInt
);
1337 WX_DEFINE_LIST(wxListInt
);
1339 static void TestList()
1341 wxPuts(_T("*** Testing wxList operations ***\n"));
1347 for ( i
= 0; i
< 5; ++i
)
1348 list1
.Append(dummy
+ i
);
1350 if ( list1
.GetCount() != 5 )
1351 wxPuts(_T("Wrong number of items in list\n"));
1353 if ( list1
.Item(3)->GetData() != dummy
+ 3 )
1354 wxPuts(_T("Error in Item()\n"));
1356 if ( !list1
.Find(dummy
+ 4) )
1357 wxPuts(_T("Error in Find()\n"));
1359 wxListInt::compatibility_iterator node
= list1
.GetFirst();
1364 if ( node
->GetData() != dummy
+ i
)
1365 wxPuts(_T("Error in compatibility_iterator\n"));
1366 node
= node
->GetNext();
1370 if ( size_t(i
) != list1
.GetCount() )
1371 wxPuts(_T("Error in compatibility_iterator\n"));
1373 list1
.Insert(dummy
+ 0);
1374 list1
.Insert(1, dummy
+ 1);
1375 list1
.Insert(list1
.GetFirst()->GetNext()->GetNext(), dummy
+ 2);
1377 node
= list1
.GetFirst();
1382 int* t
= node
->GetData();
1383 if ( t
!= dummy
+ i
)
1384 wxPuts(_T("Error in Insert\n"));
1385 node
= node
->GetNext();
1390 wxPuts(_T("*** Testing wxList operations finished ***\n"));
1392 wxPuts(_T("*** Testing std::list operations ***\n"));
1396 wxListInt::iterator it
, en
;
1397 wxListInt::reverse_iterator rit
, ren
;
1399 for ( i
= 0; i
< 5; ++i
)
1400 list1
.push_back(i
+ &i
);
1402 for ( it
= list1
.begin(), en
= list1
.end(), i
= 0;
1403 it
!= en
; ++it
, ++i
)
1404 if ( *it
!= i
+ &i
)
1405 wxPuts(_T("Error in iterator\n"));
1407 for ( rit
= list1
.rbegin(), ren
= list1
.rend(), i
= 4;
1408 rit
!= ren
; ++rit
, --i
)
1409 if ( *rit
!= i
+ &i
)
1410 wxPuts(_T("Error in reverse_iterator\n"));
1412 if ( *list1
.rbegin() != *--list1
.end() ||
1413 *list1
.begin() != *--list1
.rend() )
1414 wxPuts(_T("Error in iterator/reverse_iterator\n"));
1415 if ( *list1
.begin() != *--++list1
.begin() ||
1416 *list1
.rbegin() != *--++list1
.rbegin() )
1417 wxPuts(_T("Error in iterator/reverse_iterator\n"));
1419 if ( list1
.front() != &i
|| list1
.back() != &i
+ 4 )
1420 wxPuts(_T("Error in front()/back()\n"));
1422 list1
.erase(list1
.begin());
1423 list1
.erase(--list1
.end());
1425 for ( it
= list1
.begin(), en
= list1
.end(), i
= 1;
1426 it
!= en
; ++it
, ++i
)
1427 if ( *it
!= i
+ &i
)
1428 wxPuts(_T("Error in erase()\n"));
1431 wxPuts(_T("*** Testing std::list operations finished ***\n"));
1434 static void TestListCtor()
1436 wxPuts(_T("*** Testing wxList construction ***\n"));
1440 list1
.Append(new Bar(_T("first")));
1441 list1
.Append(new Bar(_T("second")));
1443 wxPrintf(_T("After 1st list creation: %u objects in the list, %u objects total.\n"),
1444 list1
.GetCount(), Bar::GetNumber());
1449 wxPrintf(_T("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n"),
1450 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1453 list1
.DeleteContents(true);
1455 WX_CLEAR_LIST(wxListBars
, list1
);
1459 wxPrintf(_T("After list destruction: %u objects left.\n"), Bar::GetNumber());
1464 // ----------------------------------------------------------------------------
1466 // ----------------------------------------------------------------------------
1470 #include "wx/intl.h"
1471 #include "wx/utils.h" // for wxSetEnv
1473 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1475 // find the name of the language from its value
1476 static const wxChar
*GetLangName(int lang
)
1478 static const wxChar
*languageNames
[] =
1488 _T("ARABIC_ALGERIA"),
1489 _T("ARABIC_BAHRAIN"),
1492 _T("ARABIC_JORDAN"),
1493 _T("ARABIC_KUWAIT"),
1494 _T("ARABIC_LEBANON"),
1496 _T("ARABIC_MOROCCO"),
1499 _T("ARABIC_SAUDI_ARABIA"),
1502 _T("ARABIC_TUNISIA"),
1509 _T("AZERI_CYRILLIC"),
1524 _T("CHINESE_SIMPLIFIED"),
1525 _T("CHINESE_TRADITIONAL"),
1526 _T("CHINESE_HONGKONG"),
1527 _T("CHINESE_MACAU"),
1528 _T("CHINESE_SINGAPORE"),
1529 _T("CHINESE_TAIWAN"),
1535 _T("DUTCH_BELGIAN"),
1539 _T("ENGLISH_AUSTRALIA"),
1540 _T("ENGLISH_BELIZE"),
1541 _T("ENGLISH_BOTSWANA"),
1542 _T("ENGLISH_CANADA"),
1543 _T("ENGLISH_CARIBBEAN"),
1544 _T("ENGLISH_DENMARK"),
1546 _T("ENGLISH_JAMAICA"),
1547 _T("ENGLISH_NEW_ZEALAND"),
1548 _T("ENGLISH_PHILIPPINES"),
1549 _T("ENGLISH_SOUTH_AFRICA"),
1550 _T("ENGLISH_TRINIDAD"),
1551 _T("ENGLISH_ZIMBABWE"),
1559 _T("FRENCH_BELGIAN"),
1560 _T("FRENCH_CANADIAN"),
1561 _T("FRENCH_LUXEMBOURG"),
1562 _T("FRENCH_MONACO"),
1568 _T("GERMAN_AUSTRIAN"),
1569 _T("GERMAN_BELGIUM"),
1570 _T("GERMAN_LIECHTENSTEIN"),
1571 _T("GERMAN_LUXEMBOURG"),
1589 _T("ITALIAN_SWISS"),
1594 _T("KASHMIRI_INDIA"),
1612 _T("MALAY_BRUNEI_DARUSSALAM"),
1613 _T("MALAY_MALAYSIA"),
1623 _T("NORWEGIAN_BOKMAL"),
1624 _T("NORWEGIAN_NYNORSK"),
1631 _T("PORTUGUESE_BRAZILIAN"),
1634 _T("RHAETO_ROMANCE"),
1637 _T("RUSSIAN_UKRAINE"),
1643 _T("SERBIAN_CYRILLIC"),
1644 _T("SERBIAN_LATIN"),
1645 _T("SERBO_CROATIAN"),
1656 _T("SPANISH_ARGENTINA"),
1657 _T("SPANISH_BOLIVIA"),
1658 _T("SPANISH_CHILE"),
1659 _T("SPANISH_COLOMBIA"),
1660 _T("SPANISH_COSTA_RICA"),
1661 _T("SPANISH_DOMINICAN_REPUBLIC"),
1662 _T("SPANISH_ECUADOR"),
1663 _T("SPANISH_EL_SALVADOR"),
1664 _T("SPANISH_GUATEMALA"),
1665 _T("SPANISH_HONDURAS"),
1666 _T("SPANISH_MEXICAN"),
1667 _T("SPANISH_MODERN"),
1668 _T("SPANISH_NICARAGUA"),
1669 _T("SPANISH_PANAMA"),
1670 _T("SPANISH_PARAGUAY"),
1672 _T("SPANISH_PUERTO_RICO"),
1673 _T("SPANISH_URUGUAY"),
1675 _T("SPANISH_VENEZUELA"),
1679 _T("SWEDISH_FINLAND"),
1697 _T("URDU_PAKISTAN"),
1699 _T("UZBEK_CYRILLIC"),
1712 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1713 return languageNames
[lang
];
1715 return _T("INVALID");
1718 static void TestDefaultLang()
1720 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1722 static const wxChar
*langStrings
[] =
1724 NULL
, // system default
1731 _T("de_DE.iso88591"),
1733 _T("?"), // invalid lang spec
1734 _T("klingonese"), // I bet on some systems it does exist...
1737 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1738 wxLocale::GetSystemEncodingName().c_str(),
1739 wxLocale::GetSystemEncoding());
1741 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1743 const wxChar
*langStr
= langStrings
[n
];
1746 // FIXME: this doesn't do anything at all under Windows, we need
1747 // to create a new wxLocale!
1748 wxSetEnv(_T("LC_ALL"), langStr
);
1751 int lang
= gs_localeDefault
.GetSystemLanguage();
1752 wxPrintf(_T("Locale for '%s' is %s.\n"),
1753 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1757 #endif // TEST_LOCALE
1759 // ----------------------------------------------------------------------------
1761 // ----------------------------------------------------------------------------
1765 #include "wx/mimetype.h"
1767 static void TestMimeEnum()
1769 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1771 wxArrayString mimetypes
;
1773 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1775 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1780 for ( size_t n
= 0; n
< count
; n
++ )
1782 wxFileType
*filetype
=
1783 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1786 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1787 mimetypes
[n
].c_str());
1791 filetype
->GetDescription(&desc
);
1792 filetype
->GetExtensions(exts
);
1794 filetype
->GetIcon(NULL
);
1797 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1800 extsAll
<< _T(", ");
1804 wxPrintf(_T("\t%s: %s (%s)\n"),
1805 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1808 wxPuts(wxEmptyString
);
1811 static void TestMimeOverride()
1813 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1815 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1816 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1818 if ( wxFile::Exists(mailcap
) )
1819 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1821 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1823 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1826 if ( wxFile::Exists(mimetypes
) )
1827 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1829 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1831 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1834 wxPuts(wxEmptyString
);
1837 static void TestMimeFilename()
1839 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1841 static const wxChar
*filenames
[] =
1849 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1851 const wxString fname
= filenames
[n
];
1852 wxString ext
= fname
.AfterLast(_T('.'));
1853 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1856 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1861 if ( !ft
->GetDescription(&desc
) )
1862 desc
= _T("<no description>");
1865 if ( !ft
->GetOpenCommand(&cmd
,
1866 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
1867 cmd
= _T("<no command available>");
1869 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1871 wxPrintf(_T("To open %s (%s) do %s.\n"),
1872 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1878 wxPuts(wxEmptyString
);
1881 static void TestMimeAssociate()
1883 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1885 wxFileTypeInfo
ftInfo(
1886 _T("application/x-xyz"),
1887 _T("xyzview '%s'"), // open cmd
1888 _T(""), // print cmd
1889 _T("XYZ File"), // description
1890 _T(".xyz"), // extensions
1891 NULL
// end of extensions
1893 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1895 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1898 wxPuts(_T("ERROR: failed to create association!"));
1902 // TODO: read it back
1906 wxPuts(wxEmptyString
);
1911 // ----------------------------------------------------------------------------
1912 // misc information functions
1913 // ----------------------------------------------------------------------------
1915 #ifdef TEST_INFO_FUNCTIONS
1917 #include "wx/utils.h"
1919 static void TestDiskInfo()
1921 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1925 wxChar pathname
[128];
1926 wxPrintf(_T("\nEnter a directory name: "));
1927 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1930 // kill the last '\n'
1931 pathname
[wxStrlen(pathname
) - 1] = 0;
1933 wxLongLong total
, free
;
1934 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1936 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1940 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1941 (total
/ 1024).ToString().c_str(),
1942 (free
/ 1024).ToString().c_str(),
1948 static void TestOsInfo()
1950 wxPuts(_T("*** Testing OS info functions ***\n"));
1953 wxGetOsVersion(&major
, &minor
);
1954 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1955 wxGetOsDescription().c_str(), major
, minor
);
1957 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1959 wxPrintf(_T("Host name is %s (%s).\n"),
1960 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1962 wxPuts(wxEmptyString
);
1965 static void TestUserInfo()
1967 wxPuts(_T("*** Testing user info functions ***\n"));
1969 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1970 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1971 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1972 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1974 wxPuts(wxEmptyString
);
1977 #endif // TEST_INFO_FUNCTIONS
1979 // ----------------------------------------------------------------------------
1981 // ----------------------------------------------------------------------------
1983 #ifdef TEST_PATHLIST
1986 #define CMD_IN_PATH _T("ls")
1988 #define CMD_IN_PATH _T("command.com")
1991 static void TestPathList()
1993 wxPuts(_T("*** Testing wxPathList ***\n"));
1995 wxPathList pathlist
;
1996 pathlist
.AddEnvList(_T("PATH"));
1997 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
2000 wxPrintf(_T("ERROR: command not found in the path.\n"));
2004 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
2008 #endif // TEST_PATHLIST
2010 // ----------------------------------------------------------------------------
2011 // regular expressions
2012 // ----------------------------------------------------------------------------
2016 #include "wx/regex.h"
2018 static void TestRegExInteractive()
2020 wxPuts(_T("*** Testing RE interactively ***"));
2024 wxChar pattern
[128];
2025 wxPrintf(_T("\nEnter a pattern: "));
2026 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2029 // kill the last '\n'
2030 pattern
[wxStrlen(pattern
) - 1] = 0;
2033 if ( !re
.Compile(pattern
) )
2041 wxPrintf(_T("Enter text to match: "));
2042 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
2045 // kill the last '\n'
2046 text
[wxStrlen(text
) - 1] = 0;
2048 if ( !re
.Matches(text
) )
2050 wxPrintf(_T("No match.\n"));
2054 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
2057 for ( size_t n
= 1; ; n
++ )
2059 if ( !re
.GetMatch(&start
, &len
, n
) )
2064 wxPrintf(_T("Subexpr %u matched '%s'\n"),
2065 n
, wxString(text
+ start
, len
).c_str());
2072 #endif // TEST_REGEX
2074 // ----------------------------------------------------------------------------
2076 // ----------------------------------------------------------------------------
2086 static void TestDbOpen()
2094 // ----------------------------------------------------------------------------
2096 // ----------------------------------------------------------------------------
2099 NB: this stuff was taken from the glibc test suite and modified to build
2100 in wxWidgets: if I read the copyright below properly, this shouldn't
2106 #ifdef wxTEST_PRINTF
2107 // use our functions from wxchar.cpp
2111 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
2112 // in the tests below
2113 int wxPrintf( const wxChar
*format
, ... );
2114 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
2117 #include "wx/longlong.h"
2121 static void rfg1 (void);
2122 static void rfg2 (void);
2126 fmtchk (const wxChar
*fmt
)
2128 (void) wxPrintf(_T("%s:\t`"), fmt
);
2129 (void) wxPrintf(fmt
, 0x12);
2130 (void) wxPrintf(_T("'\n"));
2134 fmtst1chk (const wxChar
*fmt
)
2136 (void) wxPrintf(_T("%s:\t`"), fmt
);
2137 (void) wxPrintf(fmt
, 4, 0x12);
2138 (void) wxPrintf(_T("'\n"));
2142 fmtst2chk (const wxChar
*fmt
)
2144 (void) wxPrintf(_T("%s:\t`"), fmt
);
2145 (void) wxPrintf(fmt
, 4, 4, 0x12);
2146 (void) wxPrintf(_T("'\n"));
2149 /* This page is covered by the following copyright: */
2151 /* (C) Copyright C E Chew
2153 * Feel free to copy, use and distribute this software provided:
2155 * 1. you do not pretend that you wrote it
2156 * 2. you leave this copyright notice intact.
2160 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
2167 /* Formatted Output Test
2169 * This exercises the output formatting code.
2172 wxChar
*PointerNull
= NULL
;
2179 wxChar
*prefix
= buf
;
2182 wxPuts(_T("\nFormatted output test"));
2183 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
2184 wxStrcpy(prefix
, _T("%"));
2185 for (i
= 0; i
< 2; i
++) {
2186 for (j
= 0; j
< 2; j
++) {
2187 for (k
= 0; k
< 2; k
++) {
2188 for (l
= 0; l
< 2; l
++) {
2189 wxStrcpy(prefix
, _T("%"));
2190 if (i
== 0) wxStrcat(prefix
, _T("-"));
2191 if (j
== 0) wxStrcat(prefix
, _T("+"));
2192 if (k
== 0) wxStrcat(prefix
, _T("#"));
2193 if (l
== 0) wxStrcat(prefix
, _T("0"));
2194 wxPrintf(_T("%5s |"), prefix
);
2195 wxStrcpy(tp
, prefix
);
2196 wxStrcat(tp
, _T("6d |"));
2198 wxStrcpy(tp
, prefix
);
2199 wxStrcat(tp
, _T("6o |"));
2201 wxStrcpy(tp
, prefix
);
2202 wxStrcat(tp
, _T("6x |"));
2204 wxStrcpy(tp
, prefix
);
2205 wxStrcat(tp
, _T("6X |"));
2207 wxStrcpy(tp
, prefix
);
2208 wxStrcat(tp
, _T("6u |"));
2215 wxPrintf(_T("%10s\n"), PointerNull
);
2216 wxPrintf(_T("%-10s\n"), PointerNull
);
2219 static void TestPrintf()
2221 static wxChar shortstr
[] = _T("Hi, Z.");
2222 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
2223 I am ready for my first lesson today.");
2225 wxString test_format
;
2229 fmtchk(_T("%4.4x"));
2230 fmtchk(_T("%04.4x"));
2231 fmtchk(_T("%4.3x"));
2232 fmtchk(_T("%04.3x"));
2234 fmtst1chk(_T("%.*x"));
2235 fmtst1chk(_T("%0*x"));
2236 fmtst2chk(_T("%*.*x"));
2237 fmtst2chk(_T("%0*.*x"));
2239 wxString bad_format
= _T("bad format:\t\"%b\"\n");
2240 wxPrintf(bad_format
.c_str());
2241 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
2243 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
2244 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
2245 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
2246 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
2247 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
2248 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
2249 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
2250 test_format
= _T("left-adjusted ZLDN:\t\"%-010ld\"\n");
2251 wxPrintf(test_format
.c_str(), -123456);
2252 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
2253 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
2255 test_format
= _T("zero-padded string:\t\"%010s\"\n");
2256 wxPrintf(test_format
.c_str(), shortstr
);
2257 test_format
= _T("left-adjusted Z string:\t\"%-010s\"\n");
2258 wxPrintf(test_format
.c_str(), shortstr
);
2259 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
2260 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
2261 wxPrintf(_T("null string:\t\"%s\"\n"), PointerNull
);
2262 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
2264 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
2265 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
2266 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
2267 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
2268 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
2269 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
2270 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
2271 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
2272 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
2273 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
2274 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
2275 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
2277 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
2278 wxPrintf (_T(" %6.5f\n"), .1);
2279 wxPrintf (_T("x%5.4fx\n"), .5);
2281 wxPrintf (_T("%#03x\n"), 1);
2283 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
2289 while (niter
-- != 0)
2290 wxPrintf (_T("%.17e\n"), d
/ 2);
2295 // Open Watcom cause compiler error here
2296 // Error! E173: col(24) floating-point constant too small to represent
2297 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
2300 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
2301 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
2302 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
2303 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
2304 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
2305 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
2306 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
2307 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
2308 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
2309 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
2314 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
2316 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
2317 rc
, WXSIZEOF(buf
), buf
);
2320 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
2321 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
2327 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
2328 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
2329 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
2330 wxPrintf (_T("%g should be 123.456\n"), 123.456);
2331 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
2332 wxPrintf (_T("%g should be 10\n"), 10.0);
2333 wxPrintf (_T("%g should be 0.02\n"), 0.02);
2337 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
2343 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
2345 result
|= wxStrcmp (buf
,
2346 _T("onetwo three "));
2348 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
2355 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
2357 // for some reason below line fails under Borland
2358 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
2361 if (wxStrcmp (buf
, _T("40000000000")) != 0)
2364 wxPuts (_T("\tFAILED"));
2366 wxUnusedVar(result
);
2367 wxPuts (wxEmptyString
);
2369 #endif // wxLongLong_t
2371 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
2372 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
2374 wxPuts (_T("--- Should be no further output. ---"));
2383 memset (bytes
, '\xff', sizeof bytes
);
2384 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
2385 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
2386 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
2388 wxPuts (_T("%hhn overwrite more bytes"));
2393 wxPuts (_T("%hhn wrote incorrect value"));
2405 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
2406 if (wxStrcmp (buf
, _T(" ")) != 0)
2407 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
2408 wxSprintf (buf
, _T("%5.f"), 33.3);
2409 if (wxStrcmp (buf
, _T(" 33")) != 0)
2410 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
2411 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
2412 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
2413 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
2414 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
2415 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
2416 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
2417 wxSprintf (buf
, _T("%.g"), 33.3);
2418 if (wxStrcmp (buf
, _T("3e+01")) != 0)
2419 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
2420 wxSprintf (buf
, _T("%.G"), 33.3);
2421 if (wxStrcmp (buf
, _T("3E+01")) != 0)
2422 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
2430 wxString test_format
;
2433 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
2434 if (wxStrcmp (buf
, _T("3")) != 0)
2435 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2437 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
2438 if (wxStrcmp (buf
, _T("3")) != 0)
2439 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
2441 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
2442 if (wxStrcmp (buf
, _T(" 3")) != 0)
2443 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
2445 test_format
= _T("%04.*o");
2446 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2447 if (wxStrcmp (buf
, _T(" 041")) != 0)
2448 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
2450 test_format
= _T("%09.*u");
2451 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2452 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
2453 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
2455 test_format
= _T("%04.*x");
2456 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2457 if (wxStrcmp (buf
, _T(" 021")) != 0)
2458 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2460 test_format
= _T("%04.*X");
2461 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
2462 if (wxStrcmp (buf
, _T(" 021")) != 0)
2463 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
2466 #endif // TEST_PRINTF
2468 // ----------------------------------------------------------------------------
2469 // registry and related stuff
2470 // ----------------------------------------------------------------------------
2472 // this is for MSW only
2475 #undef TEST_REGISTRY
2480 #include "wx/confbase.h"
2481 #include "wx/msw/regconf.h"
2484 static void TestRegConfWrite()
2486 wxConfig
*config
= new wxConfig(_T("myapp"));
2487 config
->SetPath(_T("/group1"));
2488 config
->Write(_T("entry1"), _T("foo"));
2489 config
->SetPath(_T("/group2"));
2490 config
->Write(_T("entry1"), _T("bar"));
2494 static void TestRegConfRead()
2496 wxConfig
*config
= new wxConfig(_T("myapp"));
2500 config
->SetPath(_T("/"));
2501 wxPuts(_T("Enumerating / subgroups:"));
2502 bool bCont
= config
->GetFirstGroup(str
, dummy
);
2506 bCont
= config
->GetNextGroup(str
, dummy
);
2510 #endif // TEST_REGCONF
2512 #ifdef TEST_REGISTRY
2514 #include "wx/msw/registry.h"
2516 // I chose this one because I liked its name, but it probably only exists under
2518 static const wxChar
*TESTKEY
=
2519 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2521 static void TestRegistryRead()
2523 wxPuts(_T("*** testing registry reading ***"));
2525 wxRegKey
key(TESTKEY
);
2526 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2529 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2534 size_t nSubKeys
, nValues
;
2535 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2537 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2540 wxPrintf(_T("Enumerating values:\n"));
2544 bool cont
= key
.GetFirstValue(value
, dummy
);
2547 wxPrintf(_T("Value '%s': type "), value
.c_str());
2548 switch ( key
.GetValueType(value
) )
2550 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2551 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2552 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2553 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2554 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2555 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2556 default: wxPrintf(_T("other (unknown)")); break;
2559 wxPrintf(_T(", value = "));
2560 if ( key
.IsNumericValue(value
) )
2563 key
.QueryValue(value
, &val
);
2564 wxPrintf(_T("%ld"), val
);
2569 key
.QueryValue(value
, val
);
2570 wxPrintf(_T("'%s'"), val
.c_str());
2572 key
.QueryRawValue(value
, val
);
2573 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2578 cont
= key
.GetNextValue(value
, dummy
);
2582 static void TestRegistryAssociation()
2585 The second call to deleteself genertaes an error message, with a
2586 messagebox saying .flo is crucial to system operation, while the .ddf
2587 call also fails, but with no error message
2592 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2594 key
= _T("ddxf_auto_file") ;
2595 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2597 key
= _T("ddxf_auto_file") ;
2598 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2600 key
= _T("program,0") ;
2601 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2603 key
= _T("program \"%1\"") ;
2605 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2607 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2609 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2611 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2615 #endif // TEST_REGISTRY
2617 // ----------------------------------------------------------------------------
2619 // ----------------------------------------------------------------------------
2621 #ifdef TEST_SCOPEGUARD
2623 #include "wx/scopeguard.h"
2625 static void function0() { puts("function0()"); }
2626 static void function1(int n
) { printf("function1(%d)\n", n
); }
2627 static void function2(double x
, char c
) { printf("function2(%g, %c)\n", x
, c
); }
2631 void method0() { printf("method0()\n"); }
2632 void method1(int n
) { printf("method1(%d)\n", n
); }
2633 void method2(double x
, char c
) { printf("method2(%g, %c)\n", x
, c
); }
2636 static void TestScopeGuard()
2638 wxON_BLOCK_EXIT0(function0
);
2639 wxON_BLOCK_EXIT1(function1
, 17);
2640 wxON_BLOCK_EXIT2(function2
, 3.14, 'p');
2643 wxON_BLOCK_EXIT_OBJ0(obj
, &Object::method0
);
2644 wxON_BLOCK_EXIT_OBJ1(obj
, &Object::method1
, 7);
2645 wxON_BLOCK_EXIT_OBJ2(obj
, &Object::method2
, 2.71, 'e');
2647 wxScopeGuard dismissed
= wxMakeGuard(function0
);
2648 dismissed
.Dismiss();
2653 // ----------------------------------------------------------------------------
2655 // ----------------------------------------------------------------------------
2659 #include "wx/socket.h"
2660 #include "wx/protocol/protocol.h"
2661 #include "wx/protocol/http.h"
2663 static void TestSocketServer()
2665 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2667 static const int PORT
= 3000;
2672 wxSocketServer
*server
= new wxSocketServer(addr
);
2673 if ( !server
->Ok() )
2675 wxPuts(_T("ERROR: failed to bind"));
2683 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2685 wxSocketBase
*socket
= server
->Accept();
2688 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2692 wxPuts(_T("Server: got a client."));
2694 server
->SetTimeout(60); // 1 min
2697 while ( !close
&& socket
->IsConnected() )
2700 wxChar ch
= _T('\0');
2703 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2705 // don't log error if the client just close the connection
2706 if ( socket
->IsConnected() )
2708 wxPuts(_T("ERROR: in wxSocket::Read."));
2728 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
2729 if ( s
== _T("close") )
2731 wxPuts(_T("Closing connection"));
2735 else if ( s
== _T("quit") )
2740 wxPuts(_T("Shutting down the server"));
2742 else // not a special command
2744 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2745 socket
->Write("\r\n", 2);
2746 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
2752 wxPuts(_T("Server: lost a client unexpectedly."));
2758 // same as "delete server" but is consistent with GUI programs
2762 static void TestSocketClient()
2764 wxPuts(_T("*** Testing wxSocketClient ***\n"));
2766 static const wxChar
*hostname
= _T("www.wxwidgets.org");
2769 addr
.Hostname(hostname
);
2772 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
2774 wxSocketClient client
;
2775 if ( !client
.Connect(addr
) )
2777 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2781 wxPrintf(_T("--- Connected to %s:%u...\n"),
2782 addr
.Hostname().c_str(), addr
.Service());
2786 // could use simply "GET" here I suppose
2788 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
2789 client
.Write(cmdGet
, cmdGet
.length());
2790 wxPrintf(_T("--- Sent command '%s' to the server\n"),
2791 MakePrintable(cmdGet
).c_str());
2792 client
.Read(buf
, WXSIZEOF(buf
));
2793 wxPrintf(_T("--- Server replied:\n%s"), buf
);
2797 #endif // TEST_SOCKETS
2799 // ----------------------------------------------------------------------------
2801 // ----------------------------------------------------------------------------
2805 #include "wx/protocol/ftp.h"
2809 #define FTP_ANONYMOUS
2811 #ifdef FTP_ANONYMOUS
2812 static const wxChar
*directory
= _T("/pub");
2813 static const wxChar
*filename
= _T("welcome.msg");
2815 static const wxChar
*directory
= _T("/etc");
2816 static const wxChar
*filename
= _T("issue");
2819 static bool TestFtpConnect()
2821 wxPuts(_T("*** Testing FTP connect ***"));
2823 #ifdef FTP_ANONYMOUS
2824 static const wxChar
*hostname
= _T("ftp.wxwidgets.org");
2826 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
2827 #else // !FTP_ANONYMOUS
2828 static const wxChar
*hostname
= "localhost";
2831 wxFgets(user
, WXSIZEOF(user
), stdin
);
2832 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
2835 wxChar password
[256];
2836 wxPrintf(_T("Password for %s: "), password
);
2837 wxFgets(password
, WXSIZEOF(password
), stdin
);
2838 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
2839 ftp
.SetPassword(password
);
2841 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
2842 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2844 if ( !ftp
.Connect(hostname
) )
2846 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2852 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
2853 hostname
, ftp
.Pwd().c_str());
2859 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2860 static void TestFtpWuFtpd()
2863 static const wxChar
*hostname
= _T("ftp.eudora.com");
2864 if ( !ftp
.Connect(hostname
) )
2866 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2870 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
2871 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2874 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2878 size_t size
= in
->GetSize();
2879 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2881 wxChar
*data
= new wxChar
[size
];
2882 if ( !in
->Read(data
, size
) )
2884 wxPuts(_T("ERROR: read error"));
2888 wxPrintf(_T("Successfully retrieved the file.\n"));
2897 static void TestFtpList()
2899 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
2902 if ( !ftp
.ChDir(directory
) )
2904 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2907 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2909 // test NLIST and LIST
2910 wxArrayString files
;
2911 if ( !ftp
.GetFilesList(files
) )
2913 wxPuts(_T("ERROR: failed to get NLIST of files"));
2917 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
2918 size_t count
= files
.GetCount();
2919 for ( size_t n
= 0; n
< count
; n
++ )
2921 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2923 wxPuts(_T("End of the file list"));
2926 if ( !ftp
.GetDirList(files
) )
2928 wxPuts(_T("ERROR: failed to get LIST of files"));
2932 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
2933 size_t count
= files
.GetCount();
2934 for ( size_t n
= 0; n
< count
; n
++ )
2936 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2938 wxPuts(_T("End of the file list"));
2941 if ( !ftp
.ChDir(_T("..")) )
2943 wxPuts(_T("ERROR: failed to cd to .."));
2946 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2949 static void TestFtpDownload()
2951 wxPuts(_T("*** Testing wxFTP download ***\n"));
2954 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2957 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2961 size_t size
= in
->GetSize();
2962 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2965 wxChar
*data
= new wxChar
[size
];
2966 if ( !in
->Read(data
, size
) )
2968 wxPuts(_T("ERROR: read error"));
2972 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
2980 static void TestFtpFileSize()
2982 wxPuts(_T("*** Testing FTP SIZE command ***"));
2984 if ( !ftp
.ChDir(directory
) )
2986 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2989 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2991 if ( ftp
.FileExists(filename
) )
2993 int size
= ftp
.GetFileSize(filename
);
2995 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
2997 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
3001 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
3005 static void TestFtpMisc()
3007 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
3009 if ( ftp
.SendCommand(_T("STAT")) != '2' )
3011 wxPuts(_T("ERROR: STAT failed"));
3015 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
3018 if ( ftp
.SendCommand(_T("HELP SITE")) != '2' )
3020 wxPuts(_T("ERROR: HELP SITE failed"));
3024 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
3025 ftp
.GetLastResult().c_str());
3029 static void TestFtpInteractive()
3031 wxPuts(_T("\n*** Interactive wxFTP test ***"));
3037 wxPrintf(_T("Enter FTP command: "));
3038 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3041 // kill the last '\n'
3042 buf
[wxStrlen(buf
) - 1] = 0;
3044 // special handling of LIST and NLST as they require data connection
3045 wxString
start(buf
, 4);
3047 if ( start
== _T("LIST") || start
== _T("NLST") )
3050 if ( wxStrlen(buf
) > 4 )
3053 wxArrayString files
;
3054 if ( !ftp
.GetList(files
, wildcard
, start
== _T("LIST")) )
3056 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
3060 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
3061 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
3062 size_t count
= files
.GetCount();
3063 for ( size_t n
= 0; n
< count
; n
++ )
3065 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
3067 wxPuts(_T("--- End of the file list"));
3072 wxChar ch
= ftp
.SendCommand(buf
);
3073 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
3076 wxPrintf(_T(" (return code %c)"), ch
);
3079 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
3083 wxPuts(_T("\n*** done ***"));
3086 static void TestFtpUpload()
3088 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
3091 static const wxChar
*file1
= _T("test1");
3092 static const wxChar
*file2
= _T("test2");
3093 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
3096 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
3097 out
->Write("First hello", 11);
3101 // send a command to check the remote file
3102 if ( ftp
.SendCommand(wxString(_T("STAT ")) + file1
) != '2' )
3104 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
3108 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
3109 file1
, ftp
.GetLastResult().c_str());
3112 out
= ftp
.GetOutputStream(file2
);
3115 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
3116 out
->Write("Second hello", 12);
3123 // ----------------------------------------------------------------------------
3125 // ----------------------------------------------------------------------------
3129 #include "wx/wfstream.h"
3130 #include "wx/mstream.h"
3132 static void TestFileStream()
3134 wxPuts(_T("*** Testing wxFileInputStream ***"));
3136 static const wxString filename
= _T("testdata.fs");
3138 wxFileOutputStream
fsOut(filename
);
3139 fsOut
.Write("foo", 3);
3142 wxFileInputStream
fsIn(filename
);
3143 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
3144 while ( !fsIn
.Eof() )
3146 wxPutchar(fsIn
.GetC());
3149 if ( !wxRemoveFile(filename
) )
3151 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
.c_str());
3154 wxPuts(_T("\n*** wxFileInputStream test done ***"));
3157 static void TestMemoryStream()
3159 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
3161 wxMemoryOutputStream memOutStream
;
3162 wxPrintf(_T("Initially out stream offset: %lu\n"),
3163 (unsigned long)memOutStream
.TellO());
3165 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
3167 memOutStream
.PutC(*p
);
3170 wxPrintf(_T("Final out stream offset: %lu\n"),
3171 (unsigned long)memOutStream
.TellO());
3173 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
3176 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
3178 wxMemoryInputStream
memInpStream(buf
, len
);
3179 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3180 while ( !memInpStream
.Eof() )
3182 wxPutchar(memInpStream
.GetC());
3185 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
3188 #endif // TEST_STREAMS
3190 // ----------------------------------------------------------------------------
3192 // ----------------------------------------------------------------------------
3196 #include "wx/timer.h"
3197 #include "wx/utils.h"
3199 static void TestStopWatch()
3201 wxPuts(_T("*** Testing wxStopWatch ***\n"));
3205 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
3208 wxPrintf(_T("\t%ldms\n"), sw
.Time());
3210 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
3214 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3217 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
3220 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3223 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
3226 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
3229 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
3230 for ( size_t n
= 0; n
< 70; n
++ )
3234 for ( size_t m
= 0; m
< 100000; m
++ )
3236 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3238 wxPuts(_T("\ntime is negative - ERROR!"));
3246 wxPuts(_T(", ok."));
3249 #endif // TEST_TIMER
3251 // ----------------------------------------------------------------------------
3253 // ----------------------------------------------------------------------------
3257 #include "wx/vcard.h"
3259 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3262 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3265 wxPrintf(_T("%s%s"),
3266 wxString(_T('\t'), level
).c_str(),
3267 vcObj
->GetName().c_str());
3270 switch ( vcObj
->GetType() )
3272 case wxVCardObject::String
:
3273 case wxVCardObject::UString
:
3276 vcObj
->GetValue(&val
);
3277 value
<< _T('"') << val
<< _T('"');
3281 case wxVCardObject::Int
:
3284 vcObj
->GetValue(&i
);
3285 value
.Printf(_T("%u"), i
);
3289 case wxVCardObject::Long
:
3292 vcObj
->GetValue(&l
);
3293 value
.Printf(_T("%lu"), l
);
3297 case wxVCardObject::None
:
3300 case wxVCardObject::Object
:
3301 value
= _T("<node>");
3305 value
= _T("<unknown value type>");
3309 wxPrintf(_T(" = %s"), value
.c_str());
3312 DumpVObject(level
+ 1, *vcObj
);
3315 vcObj
= vcard
.GetNextProp(&cookie
);
3319 static void DumpVCardAddresses(const wxVCard
& vcard
)
3321 wxPuts(_T("\nShowing all addresses from vCard:\n"));
3325 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3329 int flags
= addr
->GetFlags();
3330 if ( flags
& wxVCardAddress::Domestic
)
3332 flagsStr
<< _T("domestic ");
3334 if ( flags
& wxVCardAddress::Intl
)
3336 flagsStr
<< _T("international ");
3338 if ( flags
& wxVCardAddress::Postal
)
3340 flagsStr
<< _T("postal ");
3342 if ( flags
& wxVCardAddress::Parcel
)
3344 flagsStr
<< _T("parcel ");
3346 if ( flags
& wxVCardAddress::Home
)
3348 flagsStr
<< _T("home ");
3350 if ( flags
& wxVCardAddress::Work
)
3352 flagsStr
<< _T("work ");
3355 wxPrintf(_T("Address %u:\n")
3357 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3360 addr
->GetPostOffice().c_str(),
3361 addr
->GetExtAddress().c_str(),
3362 addr
->GetStreet().c_str(),
3363 addr
->GetLocality().c_str(),
3364 addr
->GetRegion().c_str(),
3365 addr
->GetPostalCode().c_str(),
3366 addr
->GetCountry().c_str()
3370 addr
= vcard
.GetNextAddress(&cookie
);
3374 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3376 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
3380 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3384 int flags
= phone
->GetFlags();
3385 if ( flags
& wxVCardPhoneNumber::Voice
)
3387 flagsStr
<< _T("voice ");
3389 if ( flags
& wxVCardPhoneNumber::Fax
)
3391 flagsStr
<< _T("fax ");
3393 if ( flags
& wxVCardPhoneNumber::Cellular
)
3395 flagsStr
<< _T("cellular ");
3397 if ( flags
& wxVCardPhoneNumber::Modem
)
3399 flagsStr
<< _T("modem ");
3401 if ( flags
& wxVCardPhoneNumber::Home
)
3403 flagsStr
<< _T("home ");
3405 if ( flags
& wxVCardPhoneNumber::Work
)
3407 flagsStr
<< _T("work ");
3410 wxPrintf(_T("Phone number %u:\n")
3415 phone
->GetNumber().c_str()
3419 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3423 static void TestVCardRead()
3425 wxPuts(_T("*** Testing wxVCard reading ***\n"));
3427 wxVCard
vcard(_T("vcard.vcf"));
3428 if ( !vcard
.IsOk() )
3430 wxPuts(_T("ERROR: couldn't load vCard."));
3434 // read individual vCard properties
3435 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3439 vcObj
->GetValue(&value
);
3444 value
= _T("<none>");
3447 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
3450 if ( !vcard
.GetFullName(&value
) )
3452 value
= _T("<none>");
3455 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
3457 // now show how to deal with multiply occuring properties
3458 DumpVCardAddresses(vcard
);
3459 DumpVCardPhoneNumbers(vcard
);
3461 // and finally show all
3462 wxPuts(_T("\nNow dumping the entire vCard:\n")
3463 "-----------------------------\n");
3465 DumpVObject(0, vcard
);
3469 static void TestVCardWrite()
3471 wxPuts(_T("*** Testing wxVCard writing ***\n"));
3474 if ( !vcard
.IsOk() )
3476 wxPuts(_T("ERROR: couldn't create vCard."));
3481 vcard
.SetName("Zeitlin", "Vadim");
3482 vcard
.SetFullName("Vadim Zeitlin");
3483 vcard
.SetOrganization("wxWidgets", "R&D");
3485 // just dump the vCard back
3486 wxPuts(_T("Entire vCard follows:\n"));
3487 wxPuts(vcard
.Write());
3491 #endif // TEST_VCARD
3493 // ----------------------------------------------------------------------------
3495 // ----------------------------------------------------------------------------
3497 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3503 #include "wx/volume.h"
3505 static const wxChar
*volumeKinds
[] =
3511 _T("network volume"),
3515 static void TestFSVolume()
3517 wxPuts(_T("*** Testing wxFSVolume class ***"));
3519 wxArrayString volumes
= wxFSVolume::GetVolumes();
3520 size_t count
= volumes
.GetCount();
3524 wxPuts(_T("ERROR: no mounted volumes?"));
3528 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3530 for ( size_t n
= 0; n
< count
; n
++ )
3532 wxFSVolume
vol(volumes
[n
]);
3535 wxPuts(_T("ERROR: couldn't create volume"));
3539 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3541 vol
.GetDisplayName().c_str(),
3542 vol
.GetName().c_str(),
3543 volumeKinds
[vol
.GetKind()],
3544 vol
.IsWritable() ? _T("rw") : _T("ro"),
3545 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3550 #endif // TEST_VOLUME
3552 // ----------------------------------------------------------------------------
3553 // wide char and Unicode support
3554 // ----------------------------------------------------------------------------
3558 #include "wx/strconv.h"
3559 #include "wx/fontenc.h"
3560 #include "wx/encconv.h"
3561 #include "wx/buffer.h"
3563 static const unsigned char utf8koi8r
[] =
3565 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3566 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3567 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3568 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3569 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3570 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3571 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3574 static const unsigned char utf8iso8859_1
[] =
3576 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3577 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3578 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3579 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3580 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3583 static const unsigned char utf8Invalid
[] =
3585 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3586 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3587 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3588 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3592 static const struct Utf8Data
3594 const unsigned char *text
;
3596 const wxChar
*charset
;
3597 wxFontEncoding encoding
;
3600 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3601 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3602 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3605 static void TestUtf8()
3607 wxPuts(_T("*** Testing UTF8 support ***\n"));
3612 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3614 const Utf8Data
& u8d
= utf8data
[n
];
3615 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3616 WXSIZEOF(wbuf
)) == (size_t)-1 )
3618 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3622 wxCSConv
conv(u8d
.charset
);
3623 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3625 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3629 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3633 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
));
3635 s
= _T("<< conversion failed >>");
3636 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3640 wxPuts(wxEmptyString
);
3643 static void TestEncodingConverter()
3645 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3647 // using wxEncodingConverter should give the same result as above
3650 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3651 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3653 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3657 wxEncodingConverter ec
;
3658 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3659 ec
.Convert(wbuf
, buf
);
3660 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
3663 wxPuts(wxEmptyString
);
3666 #endif // TEST_WCHAR
3668 // ----------------------------------------------------------------------------
3670 // ----------------------------------------------------------------------------
3674 #include "wx/filesys.h"
3675 #include "wx/fs_zip.h"
3676 #include "wx/zipstrm.h"
3678 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3680 static void TestZipStreamRead()
3682 wxPuts(_T("*** Testing ZIP reading ***\n"));
3684 static const wxString filename
= _T("foo");
3685 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3686 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3688 wxPrintf(_T("Dumping the file '%s':\n"), filename
.c_str());
3689 while ( !istr
.Eof() )
3691 wxPutchar(istr
.GetC());
3695 wxPuts(_T("\n----- done ------"));
3698 static void DumpZipDirectory(wxFileSystem
& fs
,
3699 const wxString
& dir
,
3700 const wxString
& indent
)
3702 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3703 TESTFILE_ZIP
, dir
.c_str());
3704 wxString wildcard
= prefix
+ _T("/*");
3706 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3707 while ( !dirname
.empty() )
3709 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3711 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3716 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3718 DumpZipDirectory(fs
, dirname
,
3719 indent
+ wxString(_T(' '), 4));
3721 dirname
= fs
.FindNext();
3724 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3725 while ( !filename
.empty() )
3727 if ( !filename
.StartsWith(prefix
, &filename
) )
3729 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3734 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3736 filename
= fs
.FindNext();
3740 static void TestZipFileSystem()
3742 wxPuts(_T("*** Testing ZIP file system ***\n"));
3744 wxFileSystem::AddHandler(new wxZipFSHandler
);
3746 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3748 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3753 // ----------------------------------------------------------------------------
3755 // ----------------------------------------------------------------------------
3757 #ifdef TEST_DATETIME
3761 #include "wx/datetime.h"
3766 wxDateTime::wxDateTime_t day
;
3767 wxDateTime::Month month
;
3769 wxDateTime::wxDateTime_t hour
, min
, sec
;
3771 wxDateTime::WeekDay wday
;
3772 time_t gmticks
, ticks
;
3774 void Init(const wxDateTime::Tm
& tm
)
3783 gmticks
= ticks
= -1;
3786 wxDateTime
DT() const
3787 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3789 bool SameDay(const wxDateTime::Tm
& tm
) const
3791 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3794 wxString
Format() const
3797 s
.Printf(_T("%02d:%02d:%02d %10s %02d, %4d%s"),
3799 wxDateTime::GetMonthName(month
).c_str(),
3801 abs(wxDateTime::ConvertYearToBC(year
)),
3802 year
> 0 ? _T("AD") : _T("BC"));
3806 wxString
FormatDate() const
3809 s
.Printf(_T("%02d-%s-%4d%s"),
3811 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3812 abs(wxDateTime::ConvertYearToBC(year
)),
3813 year
> 0 ? _T("AD") : _T("BC"));
3818 static const Date testDates
[] =
3820 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3821 { 7, wxDateTime::Feb
, 2036, 00, 00, 00, 2464730.5, wxDateTime::Thu
, -1, -1 },
3822 { 8, wxDateTime::Feb
, 2036, 00, 00, 00, 2464731.5, wxDateTime::Fri
, -1, -1 },
3823 { 1, wxDateTime::Jan
, 2037, 00, 00, 00, 2465059.5, wxDateTime::Thu
, -1, -1 },
3824 { 1, wxDateTime::Jan
, 2038, 00, 00, 00, 2465424.5, wxDateTime::Fri
, -1, -1 },
3825 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3826 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3827 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3828 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3829 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3830 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3831 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3832 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3833 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3834 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3835 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3836 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3837 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3838 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3841 // this test miscellaneous static wxDateTime functions
3842 static void TestTimeStatic()
3844 wxPuts(_T("\n*** wxDateTime static methods test ***"));
3846 // some info about the current date
3847 int year
= wxDateTime::GetCurrentYear();
3848 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
3850 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3851 wxDateTime::GetNumberOfDays(year
));
3853 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3854 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
3855 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3856 wxDateTime::GetMonthName(month
).c_str(),
3857 wxDateTime::GetNumberOfDays(month
));
3860 static const size_t nYears
= 5;
3861 static const size_t years
[2][nYears
] =
3863 // first line: the years to test
3864 { 1990, 1976, 2000, 2030, 1984, },
3866 // second line: true if leap, false otherwise
3867 { false, true, true, false, true }
3870 for ( size_t n
= 0; n
< nYears
; n
++ )
3872 int year
= years
[0][n
];
3873 bool should
= years
[1][n
] != 0,
3874 is
= wxDateTime::IsLeapYear(year
);
3876 wxPrintf(_T("Year %d is %sa leap year (%s)\n"),
3879 should
== is
? "ok" : "ERROR");
3881 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3885 // test constructing wxDateTime objects
3886 static void TestTimeSet()
3888 wxPuts(_T("\n*** wxDateTime construction test ***"));
3890 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3892 const Date
& d1
= testDates
[n
];
3893 wxDateTime dt
= d1
.DT();
3896 d2
.Init(dt
.GetTm());
3898 wxString s1
= d1
.Format(),
3901 wxPrintf(_T("Date: %s == %s (%s)\n"),
3902 s1
.c_str(), s2
.c_str(),
3903 s1
== s2
? _T("ok") : _T("ERROR"));
3907 // test time zones stuff
3908 static void TestTimeZones()
3910 wxPuts(_T("\n*** wxDateTime timezone test ***"));
3912 wxDateTime now
= wxDateTime::Now();
3914 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
3915 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
3916 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
3917 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
3918 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
3919 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
3921 wxDateTime::Tm tm
= now
.GetTm();
3922 if ( wxDateTime(tm
) != now
)
3924 wxPrintf(_T("ERROR: got %s instead of %s\n"),
3925 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3929 // test some minimal support for the dates outside the standard range
3930 static void TestTimeRange()
3932 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
3934 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
3936 wxPrintf(_T("Unix epoch:\t%s\n"),
3937 wxDateTime(2440587.5).Format(fmt
).c_str());
3938 wxPrintf(_T("Feb 29, 0: \t%s\n"),
3939 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3940 wxPrintf(_T("JDN 0: \t%s\n"),
3941 wxDateTime(0.0).Format(fmt
).c_str());
3942 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
3943 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3944 wxPrintf(_T("May 29, 2099:\t%s\n"),
3945 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3948 static void TestTimeTicks()
3950 wxPuts(_T("\n*** wxDateTime ticks test ***"));
3952 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3954 const Date
& d
= testDates
[n
];
3955 if ( d
.ticks
== -1 )
3958 wxDateTime dt
= d
.DT();
3959 long ticks
= (dt
.GetValue() / 1000).ToLong();
3960 wxPrintf(_T("Ticks of %s:\t% 10ld"), d
.Format().c_str(), ticks
);
3961 if ( ticks
== d
.ticks
)
3963 wxPuts(_T(" (ok)"));
3967 wxPrintf(_T(" (ERROR: should be %ld, delta = %ld)\n"),
3968 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
3971 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3972 ticks
= (dt
.GetValue() / 1000).ToLong();
3973 wxPrintf(_T("GMtks of %s:\t% 10ld"), d
.Format().c_str(), ticks
);
3974 if ( ticks
== d
.gmticks
)
3976 wxPuts(_T(" (ok)"));
3980 wxPrintf(_T(" (ERROR: should be %ld, delta = %ld)\n"),
3981 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
3985 wxPuts(wxEmptyString
);
3988 // test conversions to JDN &c
3989 static void TestTimeJDN()
3991 wxPuts(_T("\n*** wxDateTime to JDN test ***"));
3993 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3995 const Date
& d
= testDates
[n
];
3996 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3997 double jdn
= dt
.GetJulianDayNumber();
3999 wxPrintf(_T("JDN of %s is:\t% 15.6f"), d
.Format().c_str(), jdn
);
4002 wxPuts(_T(" (ok)"));
4006 wxPrintf(_T(" (ERROR: should be %f, delta = %f)\n"),
4007 d
.jdn
, jdn
- d
.jdn
);
4012 // test week days computation
4013 static void TestTimeWDays()
4015 wxPuts(_T("\n*** wxDateTime weekday test ***"));
4017 // test GetWeekDay()
4019 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
4021 const Date
& d
= testDates
[n
];
4022 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
4024 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
4025 wxPrintf(_T("%s is: %s"),
4027 wxDateTime::GetWeekDayName(wday
).c_str());
4028 if ( wday
== d
.wday
)
4030 wxPuts(_T(" (ok)"));
4034 wxPrintf(_T(" (ERROR: should be %s)\n"),
4035 wxDateTime::GetWeekDayName(d
.wday
).c_str());
4039 wxPuts(wxEmptyString
);
4041 // test SetToWeekDay()
4042 struct WeekDateTestData
4044 Date date
; // the real date (precomputed)
4045 int nWeek
; // its week index in the month
4046 wxDateTime::WeekDay wday
; // the weekday
4047 wxDateTime::Month month
; // the month
4048 int year
; // and the year
4050 wxString
Format() const
4053 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
4055 case 1: which
= _T("first"); break;
4056 case 2: which
= _T("second"); break;
4057 case 3: which
= _T("third"); break;
4058 case 4: which
= _T("fourth"); break;
4059 case 5: which
= _T("fifth"); break;
4061 case -1: which
= _T("last"); break;
4066 which
+= _T(" from end");
4069 s
.Printf(_T("The %s %s of %s in %d"),
4071 wxDateTime::GetWeekDayName(wday
).c_str(),
4072 wxDateTime::GetMonthName(month
).c_str(),
4079 // the array data was generated by the following python program
4081 from DateTime import *
4082 from whrandom import *
4083 from string import *
4085 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4086 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4088 week = DateTimeDelta(7)
4091 year = randint(1900, 2100)
4092 month = randint(1, 12)
4093 day = randint(1, 28)
4094 dt = DateTime(year, month, day)
4095 wday = dt.day_of_week
4097 countFromEnd = choice([-1, 1])
4100 while dt.month is month:
4101 dt = dt - countFromEnd * week
4102 weekNum = weekNum + countFromEnd
4104 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
4106 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
4107 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
4110 static const WeekDateTestData weekDatesTestData
[] =
4112 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
4113 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
4114 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
4115 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
4116 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
4117 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
4118 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
4119 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
4120 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
4121 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
4122 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
4123 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
4124 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
4125 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
4126 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
4127 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
4128 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
4129 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
4130 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
4131 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4134 static const wxChar
*fmt
= _T("%d-%b-%Y");
4137 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4139 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4141 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4143 wxPrintf(_T("%s is %s"), wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4145 const Date
& d
= wd
.date
;
4146 if ( d
.SameDay(dt
.GetTm()) )
4148 wxPuts(_T(" (ok)"));
4152 dt
.Set(d
.day
, d
.month
, d
.year
);
4154 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.Format(fmt
).c_str());
4159 // test the computation of (ISO) week numbers
4160 static void TestTimeWNumber()
4162 wxPuts(_T("\n*** wxDateTime week number test ***"));
4164 struct WeekNumberTestData
4166 Date date
; // the date
4167 wxDateTime::wxDateTime_t week
; // the week number in the year
4168 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4169 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4170 wxDateTime::wxDateTime_t dnum
; // day number in the year
4173 // data generated with the following python script:
4175 from DateTime import *
4176 from whrandom import *
4177 from string import *
4179 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4180 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4182 def GetMonthWeek(dt):
4183 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4184 if weekNumMonth < 0:
4185 weekNumMonth = weekNumMonth + 53
4188 def GetLastSundayBefore(dt):
4189 if dt.iso_week[2] == 7:
4192 return dt - DateTimeDelta(dt.iso_week[2])
4195 year = randint(1900, 2100)
4196 month = randint(1, 12)
4197 day = randint(1, 28)
4198 dt = DateTime(year, month, day)
4199 dayNum = dt.day_of_year
4200 weekNum = dt.iso_week[1]
4201 weekNumMonth = GetMonthWeek(dt)
4204 dtSunday = GetLastSundayBefore(dt)
4206 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4207 weekNumMonth2 = weekNumMonth2 + 1
4208 dtSunday = dtSunday - DateTimeDelta(7)
4210 data = { 'day': rjust(`day`, 2), \
4211 'month': monthNames[month - 1], \
4213 'weekNum': rjust(`weekNum`, 2), \
4214 'weekNumMonth': weekNumMonth, \
4215 'weekNumMonth2': weekNumMonth2, \
4216 'dayNum': rjust(`dayNum`, 3) }
4218 print " { { %(day)s, "\
4219 "wxDateTime::%(month)s, "\
4222 "%(weekNumMonth)s, "\
4223 "%(weekNumMonth2)s, "\
4224 "%(dayNum)s }," % data
4227 static const WeekNumberTestData weekNumberTestDates
[] =
4229 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4230 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4231 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4232 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4233 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4234 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4235 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4236 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4237 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4238 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4239 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4240 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4241 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4242 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4243 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4244 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4245 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4246 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4247 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4248 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4251 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4253 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4254 const Date
& d
= wn
.date
;
4256 wxDateTime dt
= d
.DT();
4258 wxDateTime::wxDateTime_t
4259 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4260 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4261 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4262 dnum
= dt
.GetDayOfYear();
4264 wxPrintf(_T("%s: the day number is %d"), d
.FormatDate().c_str(), dnum
);
4265 if ( dnum
== wn
.dnum
)
4267 wxPrintf(_T(" (ok)"));
4271 wxPrintf(_T(" (ERROR: should be %d)"), wn
.dnum
);
4274 wxPrintf(_T(", week in month = %d"), wmon
);
4275 if ( wmon
!= wn
.wmon
)
4277 wxPrintf(_T(" (ERROR: should be %d)"), wn
.wmon
);
4280 wxPrintf(_T(" or %d"), wmon2
);
4281 if ( wmon2
== wn
.wmon2
)
4283 wxPrintf(_T(" (ok)"));
4287 wxPrintf(_T(" (ERROR: should be %d)"), wn
.wmon2
);
4290 wxPrintf(_T(", week in year = %d"), week
);
4291 if ( week
!= wn
.week
)
4293 wxPrintf(_T(" (ERROR: should be %d)"), wn
.week
);
4296 wxPutchar(_T('\n'));
4298 wxDateTime
dt2(1, wxDateTime::Jan
, d
.year
);
4299 dt2
.SetToTheWeek(wn
.week
, dt
.GetWeekDay());
4303 d2
.Init(dt2
.GetTm());
4304 wxPrintf(_T("ERROR: SetToTheWeek() returned %s\n"),
4305 d2
.FormatDate().c_str());
4310 // test DST calculations
4311 static void TestTimeDST()
4313 wxPuts(_T("\n*** wxDateTime DST test ***"));
4315 wxPrintf(_T("DST is%s in effect now.\n\n"),
4316 wxDateTime::Now().IsDST() ? wxEmptyString
: _T(" not"));
4318 // taken from http://www.energy.ca.gov/daylightsaving.html
4319 static const Date datesDST
[2][2004 - 1900 + 1] =
4322 { 1, wxDateTime::Apr
, 1990 },
4323 { 7, wxDateTime::Apr
, 1991 },
4324 { 5, wxDateTime::Apr
, 1992 },
4325 { 4, wxDateTime::Apr
, 1993 },
4326 { 3, wxDateTime::Apr
, 1994 },
4327 { 2, wxDateTime::Apr
, 1995 },
4328 { 7, wxDateTime::Apr
, 1996 },
4329 { 6, wxDateTime::Apr
, 1997 },
4330 { 5, wxDateTime::Apr
, 1998 },
4331 { 4, wxDateTime::Apr
, 1999 },
4332 { 2, wxDateTime::Apr
, 2000 },
4333 { 1, wxDateTime::Apr
, 2001 },
4334 { 7, wxDateTime::Apr
, 2002 },
4335 { 6, wxDateTime::Apr
, 2003 },
4336 { 4, wxDateTime::Apr
, 2004 },
4339 { 28, wxDateTime::Oct
, 1990 },
4340 { 27, wxDateTime::Oct
, 1991 },
4341 { 25, wxDateTime::Oct
, 1992 },
4342 { 31, wxDateTime::Oct
, 1993 },
4343 { 30, wxDateTime::Oct
, 1994 },
4344 { 29, wxDateTime::Oct
, 1995 },
4345 { 27, wxDateTime::Oct
, 1996 },
4346 { 26, wxDateTime::Oct
, 1997 },
4347 { 25, wxDateTime::Oct
, 1998 },
4348 { 31, wxDateTime::Oct
, 1999 },
4349 { 29, wxDateTime::Oct
, 2000 },
4350 { 28, wxDateTime::Oct
, 2001 },
4351 { 27, wxDateTime::Oct
, 2002 },
4352 { 26, wxDateTime::Oct
, 2003 },
4353 { 31, wxDateTime::Oct
, 2004 },
4358 for ( year
= 1990; year
< 2005; year
++ )
4360 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4361 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4363 wxPrintf(_T("DST period in the US for year %d: from %s to %s"),
4364 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4366 size_t n
= year
- 1990;
4367 const Date
& dBegin
= datesDST
[0][n
];
4368 const Date
& dEnd
= datesDST
[1][n
];
4370 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4372 wxPuts(_T(" (ok)"));
4376 wxPrintf(_T(" (ERROR: should be %s %d to %s %d)\n"),
4377 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4378 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4382 wxPuts(wxEmptyString
);
4384 for ( year
= 1990; year
< 2005; year
++ )
4386 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
4388 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4389 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4393 // test wxDateTime -> text conversion
4394 static void TestTimeFormat()
4396 wxPuts(_T("\n*** wxDateTime formatting test ***"));
4398 // some information may be lost during conversion, so store what kind
4399 // of info should we recover after a round trip
4402 CompareNone
, // don't try comparing
4403 CompareBoth
, // dates and times should be identical
4404 CompareDate
, // dates only
4405 CompareTime
// time only
4410 CompareKind compareKind
;
4411 const wxChar
*format
;
4412 } formatTestFormats
[] =
4414 { CompareBoth
, _T("---> %c") },
4415 { CompareDate
, _T("Date is %A, %d of %B, in year %Y") },
4416 { CompareBoth
, _T("Date is %x, time is %X") },
4417 { CompareTime
, _T("Time is %H:%M:%S or %I:%M:%S %p") },
4418 { CompareNone
, _T("The day of year: %j, the week of year: %W") },
4419 { CompareDate
, _T("ISO date without separators: %Y%m%d") },
4422 static const Date formatTestDates
[] =
4424 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4425 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4427 // this test can't work for other centuries because it uses two digit
4428 // years in formats, so don't even try it
4429 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4430 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4431 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4435 // an extra test (as it doesn't depend on date, don't do it in the loop)
4436 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
4438 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4440 wxPuts(wxEmptyString
);
4442 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4443 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4445 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4446 wxPrintf(_T("%s"), s
.c_str());
4448 // what can we recover?
4449 int kind
= formatTestFormats
[n
].compareKind
;
4453 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4456 // converion failed - should it have?
4457 if ( kind
== CompareNone
)
4458 wxPuts(_T(" (ok)"));
4460 wxPuts(_T(" (ERROR: conversion back failed)"));
4464 // should have parsed the entire string
4465 wxPuts(_T(" (ERROR: conversion back stopped too soon)"));
4469 bool equal
= false; // suppress compilaer warning
4477 equal
= dt
.IsSameDate(dt2
);
4481 equal
= dt
.IsSameTime(dt2
);
4487 wxPrintf(_T(" (ERROR: got back '%s' instead of '%s')\n"),
4488 dt2
.Format().c_str(), dt
.Format().c_str());
4492 wxPuts(_T(" (ok)"));
4499 // test text -> wxDateTime conversion
4500 static void TestTimeParse()
4502 wxPuts(_T("\n*** wxDateTime parse test ***"));
4504 struct ParseTestData
4506 const wxChar
*format
;
4511 static const ParseTestData parseTestDates
[] =
4513 { _T("Sat, 18 Dec 1999 00:46:40 +0100"), { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, true },
4514 { _T("Wed, 1 Dec 1999 05:17:20 +0300"), { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, true },
4517 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4519 const wxChar
*format
= parseTestDates
[n
].format
;
4521 wxPrintf(_T("%s => "), format
);
4524 if ( dt
.ParseRfc822Date(format
) )
4526 wxPrintf(_T("%s "), dt
.Format().c_str());
4528 if ( parseTestDates
[n
].good
)
4530 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4537 wxPrintf(_T("(ERROR: should be %s)\n"), dtReal
.Format().c_str());
4542 wxPuts(_T("(ERROR: bad format)"));
4547 wxPrintf(_T("bad format (%s)\n"),
4548 parseTestDates
[n
].good
? "ERROR" : "ok");
4553 static void TestDateTimeInteractive()
4555 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
4561 wxPrintf(_T("Enter a date: "));
4562 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
4565 // kill the last '\n'
4566 buf
[wxStrlen(buf
) - 1] = 0;
4569 const wxChar
*p
= dt
.ParseDate(buf
);
4572 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
4578 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
4581 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
4582 dt
.Format(_T("%b %d, %Y")).c_str(),
4584 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4585 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4586 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4589 wxPuts(_T("\n*** done ***"));
4592 static void TestTimeMS()
4594 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
4596 wxDateTime dt1
= wxDateTime::Now(),
4597 dt2
= wxDateTime::UNow();
4599 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
4600 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
4601 wxPrintf(_T("Dummy loop: "));
4602 for ( int i
= 0; i
< 6000; i
++ )
4604 //for ( int j = 0; j < 10; j++ )
4607 s
.Printf(_T("%g"), sqrt(i
));
4613 wxPuts(_T(", done"));
4616 dt2
= wxDateTime::UNow();
4617 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
4619 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
4621 wxPuts(_T("\n*** done ***"));
4624 static void TestTimeArithmetics()
4626 wxPuts(_T("\n*** testing arithmetic operations on wxDateTime ***"));
4628 static const struct ArithmData
4630 ArithmData(const wxDateSpan
& sp
, const wxChar
*nam
)
4631 : span(sp
), name(nam
) { }
4635 } testArithmData
[] =
4637 ArithmData(wxDateSpan::Day(), _T("day")),
4638 ArithmData(wxDateSpan::Week(), _T("week")),
4639 ArithmData(wxDateSpan::Month(), _T("month")),
4640 ArithmData(wxDateSpan::Year(), _T("year")),
4641 ArithmData(wxDateSpan(1, 2, 3, 4), _T("year, 2 months, 3 weeks, 4 days")),
4644 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4646 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4648 wxDateSpan span
= testArithmData
[n
].span
;
4652 const wxChar
*name
= testArithmData
[n
].name
;
4653 wxPrintf(_T("%s + %s = %s, %s - %s = %s\n"),
4654 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4655 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4657 wxPrintf(_T("Going back: %s"), (dt1
- span
).FormatISODate().c_str());
4658 if ( dt1
- span
== dt
)
4660 wxPuts(_T(" (ok)"));
4664 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.FormatISODate().c_str());
4667 wxPrintf(_T("Going forward: %s"), (dt2
+ span
).FormatISODate().c_str());
4668 if ( dt2
+ span
== dt
)
4670 wxPuts(_T(" (ok)"));
4674 wxPrintf(_T(" (ERROR: should be %s)\n"), dt
.FormatISODate().c_str());
4677 wxPrintf(_T("Double increment: %s"), (dt2
+ 2*span
).FormatISODate().c_str());
4678 if ( dt2
+ 2*span
== dt1
)
4680 wxPuts(_T(" (ok)"));
4684 wxPrintf(_T(" (ERROR: should be %s)\n"), dt2
.FormatISODate().c_str());
4687 wxPuts(wxEmptyString
);
4691 static void TestTimeHolidays()
4693 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
4695 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4696 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4697 dtEnd
= dtStart
.GetLastMonthDay();
4699 wxDateTimeArray hol
;
4700 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4702 const wxChar
*format
= _T("%d-%b-%Y (%a)");
4704 wxPrintf(_T("All holidays between %s and %s:\n"),
4705 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4707 size_t count
= hol
.GetCount();
4708 for ( size_t n
= 0; n
< count
; n
++ )
4710 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
4713 wxPuts(wxEmptyString
);
4716 static void TestTimeZoneBug()
4718 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
4720 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4721 for ( int i
= 0; i
< 31; i
++ )
4723 wxPrintf(_T("Date %s: week day %s.\n"),
4724 date
.Format(_T("%d-%m-%Y")).c_str(),
4725 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4727 date
+= wxDateSpan::Day();
4730 wxPuts(wxEmptyString
);
4733 static void TestTimeSpanFormat()
4735 wxPuts(_T("\n*** wxTimeSpan tests ***"));
4737 static const wxChar
*formats
[] =
4739 _T("(default) %H:%M:%S"),
4740 _T("%E weeks and %D days"),
4741 _T("%l milliseconds"),
4742 _T("(with ms) %H:%M:%S:%l"),
4743 _T("100%% of minutes is %M"), // test "%%"
4744 _T("%D days and %H hours"),
4745 _T("or also %S seconds"),
4748 wxTimeSpan
ts1(1, 2, 3, 4),
4750 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4752 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
4753 ts1
.Format(formats
[n
]).c_str(),
4754 ts2
.Format(formats
[n
]).c_str());
4757 wxPuts(wxEmptyString
);
4760 #endif // TEST_DATETIME
4762 // ----------------------------------------------------------------------------
4763 // wxTextInput/OutputStream
4764 // ----------------------------------------------------------------------------
4766 #ifdef TEST_TEXTSTREAM
4768 #include "wx/txtstrm.h"
4769 #include "wx/wfstream.h"
4771 static void TestTextInputStream()
4773 wxPuts(_T("\n*** wxTextInputStream test ***"));
4775 wxString filename
= _T("testdata.fc");
4776 wxFileInputStream
fsIn(filename
);
4779 wxPuts(_T("ERROR: couldn't open file."));
4783 wxTextInputStream
tis(fsIn
);
4788 const wxString s
= tis
.ReadLine();
4790 // line could be non empty if the last line of the file isn't
4791 // terminated with EOL
4792 if ( fsIn
.Eof() && s
.empty() )
4795 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
4800 #endif // TEST_TEXTSTREAM
4802 // ----------------------------------------------------------------------------
4804 // ----------------------------------------------------------------------------
4808 #include "wx/thread.h"
4810 static size_t gs_counter
= (size_t)-1;
4811 static wxCriticalSection gs_critsect
;
4812 static wxSemaphore gs_cond
;
4814 class MyJoinableThread
: public wxThread
4817 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4818 { m_n
= n
; Create(); }
4820 // thread execution starts here
4821 virtual ExitCode
Entry();
4827 wxThread::ExitCode
MyJoinableThread::Entry()
4829 unsigned long res
= 1;
4830 for ( size_t n
= 1; n
< m_n
; n
++ )
4834 // it's a loooong calculation :-)
4838 return (ExitCode
)res
;
4841 class MyDetachedThread
: public wxThread
4844 MyDetachedThread(size_t n
, wxChar ch
)
4848 m_cancelled
= false;
4853 // thread execution starts here
4854 virtual ExitCode
Entry();
4857 virtual void OnExit();
4860 size_t m_n
; // number of characters to write
4861 wxChar m_ch
; // character to write
4863 bool m_cancelled
; // false if we exit normally
4866 wxThread::ExitCode
MyDetachedThread::Entry()
4869 wxCriticalSectionLocker
lock(gs_critsect
);
4870 if ( gs_counter
== (size_t)-1 )
4876 for ( size_t n
= 0; n
< m_n
; n
++ )
4878 if ( TestDestroy() )
4888 wxThread::Sleep(100);
4894 void MyDetachedThread::OnExit()
4896 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
4898 wxCriticalSectionLocker
lock(gs_critsect
);
4899 if ( !--gs_counter
&& !m_cancelled
)
4903 static void TestDetachedThreads()
4905 wxPuts(_T("\n*** Testing detached threads ***"));
4907 static const size_t nThreads
= 3;
4908 MyDetachedThread
*threads
[nThreads
];
4910 for ( n
= 0; n
< nThreads
; n
++ )
4912 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4915 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4916 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4918 for ( n
= 0; n
< nThreads
; n
++ )
4923 // wait until all threads terminate
4926 wxPuts(wxEmptyString
);
4929 static void TestJoinableThreads()
4931 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
4933 // calc 10! in the background
4934 MyJoinableThread
thread(10);
4937 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
4938 (unsigned long)thread
.Wait());
4941 static void TestThreadSuspend()
4943 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
4945 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4949 // this is for this demo only, in a real life program we'd use another
4950 // condition variable which would be signaled from wxThread::Entry() to
4951 // tell us that the thread really started running - but here just wait a
4952 // bit and hope that it will be enough (the problem is, of course, that
4953 // the thread might still not run when we call Pause() which will result
4955 wxThread::Sleep(300);
4957 for ( size_t n
= 0; n
< 3; n
++ )
4961 wxPuts(_T("\nThread suspended"));
4964 // don't sleep but resume immediately the first time
4965 wxThread::Sleep(300);
4967 wxPuts(_T("Going to resume the thread"));
4972 wxPuts(_T("Waiting until it terminates now"));
4974 // wait until the thread terminates
4977 wxPuts(wxEmptyString
);
4980 static void TestThreadDelete()
4982 // As above, using Sleep() is only for testing here - we must use some
4983 // synchronisation object instead to ensure that the thread is still
4984 // running when we delete it - deleting a detached thread which already
4985 // terminated will lead to a crash!
4987 wxPuts(_T("\n*** Testing thread delete function ***"));
4989 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4993 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
4995 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4999 wxThread::Sleep(300);
5003 wxPuts(_T("\nDeleted a running thread."));
5005 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
5009 wxThread::Sleep(300);
5015 wxPuts(_T("\nDeleted a sleeping thread."));
5017 MyJoinableThread
thread3(20);
5022 wxPuts(_T("\nDeleted a joinable thread."));
5024 MyJoinableThread
thread4(2);
5027 wxThread::Sleep(300);
5031 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
5033 wxPuts(wxEmptyString
);
5036 class MyWaitingThread
: public wxThread
5039 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
5042 m_condition
= condition
;
5047 virtual ExitCode
Entry()
5049 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
5054 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
5058 m_condition
->Wait();
5061 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
5069 wxCondition
*m_condition
;
5072 static void TestThreadConditions()
5075 wxCondition
condition(mutex
);
5077 // otherwise its difficult to understand which log messages pertain to
5079 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
5080 // condition.GetId(), gs_cond.GetId());
5082 // create and launch threads
5083 MyWaitingThread
*threads
[10];
5086 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5088 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
5091 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5096 // wait until all threads run
5097 wxPuts(_T("Main thread is waiting for the other threads to start"));
5100 size_t nRunning
= 0;
5101 while ( nRunning
< WXSIZEOF(threads
) )
5107 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
5111 wxPuts(_T("Main thread: all threads started up."));
5114 wxThread::Sleep(500);
5117 // now wake one of them up
5118 wxPrintf(_T("Main thread: about to signal the condition.\n"));
5123 wxThread::Sleep(200);
5125 // wake all the (remaining) threads up, so that they can exit
5126 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
5128 condition
.Broadcast();
5130 // give them time to terminate (dirty!)
5131 wxThread::Sleep(500);
5134 #include "wx/utils.h"
5136 class MyExecThread
: public wxThread
5139 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5145 virtual ExitCode
Entry()
5147 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5154 static void TestThreadExec()
5156 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5158 MyExecThread
thread(_T("true"));
5161 wxPrintf(_T("Main program exit code: %ld.\n"),
5162 wxExecute(_T("false"), wxEXEC_SYNC
));
5164 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5168 #include "wx/datetime.h"
5170 class MySemaphoreThread
: public wxThread
5173 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5174 : wxThread(wxTHREAD_JOINABLE
),
5181 virtual ExitCode
Entry()
5183 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
5184 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5188 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
5189 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5193 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
5194 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5206 WX_DEFINE_ARRAY_PTR(wxThread
*, ArrayThreads
);
5208 static void TestSemaphore()
5210 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5212 static const int SEM_LIMIT
= 3;
5214 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5215 ArrayThreads threads
;
5217 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5219 threads
.Add(new MySemaphoreThread(i
, &sem
));
5220 threads
.Last()->Run();
5223 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5230 #endif // TEST_THREADS
5232 // ----------------------------------------------------------------------------
5234 // ----------------------------------------------------------------------------
5236 #ifdef TEST_SNGLINST
5237 #include "wx/snglinst.h"
5238 #endif // TEST_SNGLINST
5240 int main(int argc
, char **argv
)
5242 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
5244 wxInitializer initializer
;
5247 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
5252 #ifdef TEST_SNGLINST
5253 wxSingleInstanceChecker checker
;
5254 if ( checker
.Create(_T(".wxconsole.lock")) )
5256 if ( checker
.IsAnotherRunning() )
5258 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5263 // wait some time to give time to launch another instance
5264 wxPrintf(_T("Press \"Enter\" to continue..."));
5267 else // failed to create
5269 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5271 #endif // TEST_SNGLINST
5274 TestCmdLineConvert();
5276 #if wxUSE_CMDLINE_PARSER
5277 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5279 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
5280 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5281 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
5282 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
5284 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
5285 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
5286 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
5287 wxCMD_LINE_VAL_NUMBER
},
5288 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
5289 wxCMD_LINE_VAL_DATE
},
5291 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
5292 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5298 wxChar
**wargv
= new wxChar
*[argc
+ 1];
5303 for (n
= 0; n
< argc
; n
++ )
5305 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
5306 wargv
[n
] = wxStrdup(warg
);
5313 #endif // wxUSE_UNICODE
5315 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5319 for ( int n
= 0; n
< argc
; n
++ )
5324 #endif // wxUSE_UNICODE
5326 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
5327 wxCMD_LINE_VAL_STRING
,
5328 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5330 switch ( parser
.Parse() )
5333 wxLogMessage(_T("Help was given, terminating."));
5337 ShowCmdLine(parser
);
5341 wxLogMessage(_T("Syntax error detected, aborting."));
5344 #endif // wxUSE_CMDLINE_PARSER
5346 #endif // TEST_CMDLINE
5356 #ifdef TEST_DLLLOADER
5358 #endif // TEST_DLLLOADER
5362 #endif // TEST_ENVIRON
5366 #endif // TEST_EXECUTE
5368 #ifdef TEST_FILECONF
5370 #endif // TEST_FILECONF
5379 #endif // TEST_LOCALE
5382 wxPuts(_T("*** Testing wxLog ***"));
5385 for ( size_t n
= 0; n
< 8000; n
++ )
5387 s
<< (wxChar
)(_T('A') + (n
% 26));
5390 wxLogWarning(_T("The length of the string is %lu"),
5391 (unsigned long)s
.length());
5394 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
5396 // this one shouldn't be truncated
5399 // but this one will because log functions use fixed size buffer
5400 // (note that it doesn't need '\n' at the end neither - will be added
5402 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
5411 #ifdef TEST_FILENAME
5412 TestFileNameConstruction();
5413 TestFileNameMakeRelative();
5414 TestFileNameMakeAbsolute();
5415 TestFileNameSplit();
5418 TestFileNameDirManip();
5419 TestFileNameComparison();
5420 TestFileNameOperations();
5421 #endif // TEST_FILENAME
5423 #ifdef TEST_FILETIME
5428 #endif // TEST_FILETIME
5431 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5432 if ( TestFtpConnect() )
5442 #if TEST_INTERACTIVE
5443 TestFtpInteractive();
5446 //else: connecting to the FTP server failed
5455 #endif // TEST_HASHMAP
5459 #endif // TEST_HASHSET
5462 wxLog::AddTraceMask(_T("mime"));
5466 TestMimeAssociate();
5471 #ifdef TEST_INFO_FUNCTIONS
5476 #if TEST_INTERACTIVE
5480 #endif // TEST_INFO_FUNCTIONS
5482 #ifdef TEST_PATHLIST
5484 #endif // TEST_PATHLIST
5492 #endif // TEST_PRINTF
5499 #endif // TEST_REGCONF
5501 #if defined TEST_REGEX && TEST_INTERACTIVE
5502 TestRegExInteractive();
5503 #endif // defined TEST_REGEX && TEST_INTERACTIVE
5505 #ifdef TEST_REGISTRY
5507 TestRegistryAssociation();
5508 #endif // TEST_REGISTRY
5513 #endif // TEST_SOCKETS
5520 #endif // TEST_STREAMS
5522 #ifdef TEST_TEXTSTREAM
5523 TestTextInputStream();
5524 #endif // TEST_TEXTSTREAM
5527 int nCPUs
= wxThread::GetCPUCount();
5528 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
5530 wxThread::SetConcurrency(nCPUs
);
5532 TestJoinableThreads();
5535 TestJoinableThreads();
5536 TestDetachedThreads();
5537 TestThreadSuspend();
5539 TestThreadConditions();
5543 #endif // TEST_THREADS
5547 #endif // TEST_TIMER
5549 #ifdef TEST_DATETIME
5561 TestTimeArithmetics();
5564 TestTimeSpanFormat();
5570 #if TEST_INTERACTIVE
5571 TestDateTimeInteractive();
5573 #endif // TEST_DATETIME
5575 #ifdef TEST_SCOPEGUARD
5580 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
5582 #endif // TEST_USLEEP
5587 #endif // TEST_VCARD
5591 #endif // TEST_VOLUME
5595 TestEncodingConverter();
5596 #endif // TEST_WCHAR
5599 TestZipStreamRead();
5600 TestZipFileSystem();