1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
23 #error "This sample can't be compiled in GUI mode."
28 #include "wx/string.h"
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
43 A note about all these conditional compilation macros: this file is used
44 both as a test suite for various non-GUI wxWindows classes and as a
45 scratchpad for quick tests. So there are two compilation modes: if you
46 define TEST_ALL all tests are run, otherwise you may enable the individual
47 tests individually in the "#else" branch below.
50 // what to test (in alphabetic order)? uncomment the line below to do all tests
58 #define TEST_DLLLOADER
68 #define TEST_INFO_FUNCTIONS
86 // #define TEST_VCARD -- don't enable this (VZ)
93 static const bool TEST_ALL
= TRUE
;
97 static const bool TEST_ALL
= FALSE
;
100 // some tests are interactive, define this to run them
101 #ifdef TEST_INTERACTIVE
102 #undef TEST_INTERACTIVE
104 static const bool TEST_INTERACTIVE
= TRUE
;
106 static const bool TEST_INTERACTIVE
= FALSE
;
109 // ----------------------------------------------------------------------------
110 // test class for container objects
111 // ----------------------------------------------------------------------------
113 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
115 class Bar
// Foo is already taken in the hash test
118 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
119 Bar(const Bar
& bar
) : m_name(bar
.m_name
) { ms_bars
++; }
120 ~Bar() { ms_bars
--; }
122 static size_t GetNumber() { return ms_bars
; }
124 const char *GetName() const { return m_name
; }
129 static size_t ms_bars
;
132 size_t Bar::ms_bars
= 0;
134 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
136 // ============================================================================
138 // ============================================================================
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
146 // replace TABs with \t and CRs with \n
147 static wxString
MakePrintable(const wxChar
*s
)
150 (void)str
.Replace(_T("\t"), _T("\\t"));
151 (void)str
.Replace(_T("\n"), _T("\\n"));
152 (void)str
.Replace(_T("\r"), _T("\\r"));
157 #endif // MakePrintable() is used
159 // ----------------------------------------------------------------------------
160 // wxFontMapper::CharsetToEncoding
161 // ----------------------------------------------------------------------------
165 #include "wx/fontmap.h"
167 static void TestCharset()
169 static const wxChar
*charsets
[] =
171 // some vali charsets
180 // and now some bogus ones
187 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
189 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(charsets
[n
]);
190 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
192 wxFontMapper::Get()->GetEncodingName(enc
).c_str(),
193 wxFontMapper::Get()->GetEncodingDescription(enc
).c_str());
197 #endif // TEST_CHARSET
199 // ----------------------------------------------------------------------------
201 // ----------------------------------------------------------------------------
205 #include "wx/cmdline.h"
206 #include "wx/datetime.h"
208 #if wxUSE_CMDLINE_PARSER
210 static void ShowCmdLine(const wxCmdLineParser
& parser
)
212 wxString s
= "Input files: ";
214 size_t count
= parser
.GetParamCount();
215 for ( size_t param
= 0; param
< count
; param
++ )
217 s
<< parser
.GetParam(param
) << ' ';
221 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
222 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
227 if ( parser
.Found("o", &strVal
) )
228 s
<< "Output file:\t" << strVal
<< '\n';
229 if ( parser
.Found("i", &strVal
) )
230 s
<< "Input dir:\t" << strVal
<< '\n';
231 if ( parser
.Found("s", &lVal
) )
232 s
<< "Size:\t" << lVal
<< '\n';
233 if ( parser
.Found("d", &dt
) )
234 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
235 if ( parser
.Found("project_name", &strVal
) )
236 s
<< "Project:\t" << strVal
<< '\n';
241 #endif // wxUSE_CMDLINE_PARSER
243 static void TestCmdLineConvert()
245 static const char *cmdlines
[] =
248 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
249 "literal \\\" and \"\"",
252 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
254 const char *cmdline
= cmdlines
[n
];
255 printf("Parsing: %s\n", cmdline
);
256 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
258 size_t count
= args
.GetCount();
259 printf("\targc = %u\n", count
);
260 for ( size_t arg
= 0; arg
< count
; arg
++ )
262 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
267 #endif // TEST_CMDLINE
269 // ----------------------------------------------------------------------------
271 // ----------------------------------------------------------------------------
278 static const wxChar
*ROOTDIR
= _T("/");
279 static const wxChar
*TESTDIR
= _T("/usr");
280 #elif defined(__WXMSW__)
281 static const wxChar
*ROOTDIR
= _T("c:\\");
282 static const wxChar
*TESTDIR
= _T("d:\\");
284 #error "don't know where the root directory is"
287 static void TestDirEnumHelper(wxDir
& dir
,
288 int flags
= wxDIR_DEFAULT
,
289 const wxString
& filespec
= wxEmptyString
)
293 if ( !dir
.IsOpened() )
296 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
299 printf("\t%s\n", filename
.c_str());
301 cont
= dir
.GetNext(&filename
);
307 static void TestDirEnum()
309 puts("*** Testing wxDir::GetFirst/GetNext ***");
311 wxString cwd
= wxGetCwd();
312 if ( !wxDir::Exists(cwd
) )
314 printf("ERROR: current directory '%s' doesn't exist?\n", cwd
.c_str());
318 wxDir
dir("s:/tmp/foo");
319 if ( !dir
.IsOpened() )
321 printf("ERROR: failed to open current directory '%s'.\n", cwd
.c_str());
325 puts("Enumerating everything in current directory:");
326 TestDirEnumHelper(dir
);
328 puts("Enumerating really everything in current directory:");
329 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
331 puts("Enumerating object files in current directory:");
332 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
334 puts("Enumerating directories in current directory:");
335 TestDirEnumHelper(dir
, wxDIR_DIRS
);
337 puts("Enumerating files in current directory:");
338 TestDirEnumHelper(dir
, wxDIR_FILES
);
340 puts("Enumerating files including hidden in current directory:");
341 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
345 puts("Enumerating everything in root directory:");
346 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
348 puts("Enumerating directories in root directory:");
349 TestDirEnumHelper(dir
, wxDIR_DIRS
);
351 puts("Enumerating files in root directory:");
352 TestDirEnumHelper(dir
, wxDIR_FILES
);
354 puts("Enumerating files including hidden in root directory:");
355 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
357 puts("Enumerating files in non existing directory:");
358 wxDir
dirNo("nosuchdir");
359 TestDirEnumHelper(dirNo
);
362 class DirPrintTraverser
: public wxDirTraverser
365 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
367 return wxDIR_CONTINUE
;
370 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
372 wxString path
, name
, ext
;
373 wxSplitPath(dirname
, &path
, &name
, &ext
);
376 name
<< _T('.') << ext
;
379 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
381 if ( wxIsPathSeparator(*p
) )
385 printf("%s%s\n", indent
.c_str(), name
.c_str());
387 return wxDIR_CONTINUE
;
391 static void TestDirTraverse()
393 puts("*** Testing wxDir::Traverse() ***");
397 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
398 printf("There are %u files under '%s'\n", n
, TESTDIR
);
401 printf("First one is '%s'\n", files
[0u].c_str());
402 printf(" last one is '%s'\n", files
[n
- 1].c_str());
405 // enum again with custom traverser
407 DirPrintTraverser traverser
;
408 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
411 static void TestDirExists()
413 wxPuts(_T("*** Testing wxDir::Exists() ***"));
415 static const char *dirnames
[] =
418 #if defined(__WXMSW__)
421 _T("\\\\share\\file"),
425 _T("c:\\autoexec.bat"),
426 #elif defined(__UNIX__)
435 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
437 printf(_T("%-40s: %s\n"),
439 wxDir::Exists(dirnames
[n
]) ? _T("exists") : _T("doesn't exist"));
445 // ----------------------------------------------------------------------------
447 // ----------------------------------------------------------------------------
449 #ifdef TEST_DLLLOADER
451 #include "wx/dynlib.h"
453 static void TestDllLoad()
455 #if defined(__WXMSW__)
456 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
457 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
458 #elif defined(__UNIX__)
459 // weird: using just libc.so does *not* work!
460 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
461 static const wxChar
*FUNC_NAME
= _T("strlen");
463 #error "don't know how to test wxDllLoader on this platform"
466 puts("*** testing wxDllLoader ***\n");
468 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
471 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
475 typedef int (*strlenType
)(const char *);
476 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
479 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
480 FUNC_NAME
, LIB_NAME
);
484 if ( pfnStrlen("foo") != 3 )
486 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
494 wxDllLoader::UnloadLibrary(dllHandle
);
498 #endif // TEST_DLLLOADER
500 // ----------------------------------------------------------------------------
502 // ----------------------------------------------------------------------------
506 #include "wx/utils.h"
508 static wxString
MyGetEnv(const wxString
& var
)
511 if ( !wxGetEnv(var
, &val
) )
514 val
= wxString(_T('\'')) + val
+ _T('\'');
519 static void TestEnvironment()
521 const wxChar
*var
= _T("wxTestVar");
523 puts("*** testing environment access functions ***");
525 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
526 wxSetEnv(var
, _T("value for wxTestVar"));
527 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
528 wxSetEnv(var
, _T("another value"));
529 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
531 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
532 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
535 #endif // TEST_ENVIRON
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
543 #include "wx/utils.h"
545 static void TestExecute()
547 puts("*** testing wxExecute ***");
550 #define COMMAND "cat -n ../../Makefile" // "echo hi"
551 #define SHELL_COMMAND "echo hi from shell"
552 #define REDIRECT_COMMAND COMMAND // "date"
553 #elif defined(__WXMSW__)
554 #define COMMAND "command.com -c 'echo hi'"
555 #define SHELL_COMMAND "echo hi"
556 #define REDIRECT_COMMAND COMMAND
558 #error "no command to exec"
561 printf("Testing wxShell: ");
563 if ( wxShell(SHELL_COMMAND
) )
568 printf("Testing wxExecute: ");
570 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
575 #if 0 // no, it doesn't work (yet?)
576 printf("Testing async wxExecute: ");
578 if ( wxExecute(COMMAND
) != 0 )
579 puts("Ok (command launched).");
584 printf("Testing wxExecute with redirection:\n");
585 wxArrayString output
;
586 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
592 size_t count
= output
.GetCount();
593 for ( size_t n
= 0; n
< count
; n
++ )
595 printf("\t%s\n", output
[n
].c_str());
602 #endif // TEST_EXECUTE
604 // ----------------------------------------------------------------------------
606 // ----------------------------------------------------------------------------
611 #include "wx/ffile.h"
612 #include "wx/textfile.h"
614 static void TestFileRead()
616 puts("*** wxFile read test ***");
618 wxFile
file(_T("testdata.fc"));
619 if ( file
.IsOpened() )
621 printf("File length: %lu\n", file
.Length());
623 puts("File dump:\n----------");
625 static const off_t len
= 1024;
629 off_t nRead
= file
.Read(buf
, len
);
630 if ( nRead
== wxInvalidOffset
)
632 printf("Failed to read the file.");
636 fwrite(buf
, nRead
, 1, stdout
);
646 printf("ERROR: can't open test file.\n");
652 static void TestTextFileRead()
654 puts("*** wxTextFile read test ***");
656 wxTextFile
file(_T("testdata.fc"));
659 printf("Number of lines: %u\n", file
.GetLineCount());
660 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
664 puts("\nDumping the entire file:");
665 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
667 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
669 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
671 puts("\nAnd now backwards:");
672 for ( s
= file
.GetLastLine();
673 file
.GetCurrentLine() != 0;
674 s
= file
.GetPrevLine() )
676 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
678 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
682 printf("ERROR: can't open '%s'\n", file
.GetName());
688 static void TestFileCopy()
690 puts("*** Testing wxCopyFile ***");
692 static const wxChar
*filename1
= _T("testdata.fc");
693 static const wxChar
*filename2
= _T("test2");
694 if ( !wxCopyFile(filename1
, filename2
) )
696 puts("ERROR: failed to copy file");
700 wxFFile
f1(filename1
, "rb"),
703 if ( !f1
.IsOpened() || !f2
.IsOpened() )
705 puts("ERROR: failed to open file(s)");
710 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
712 puts("ERROR: failed to read file(s)");
716 if ( (s1
.length() != s2
.length()) ||
717 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
719 puts("ERROR: copy error!");
723 puts("File was copied ok.");
729 if ( !wxRemoveFile(filename2
) )
731 puts("ERROR: failed to remove the file");
739 // ----------------------------------------------------------------------------
741 // ----------------------------------------------------------------------------
745 #include "wx/confbase.h"
746 #include "wx/fileconf.h"
748 static const struct FileConfTestData
750 const wxChar
*name
; // value name
751 const wxChar
*value
; // the value from the file
754 { _T("value1"), _T("one") },
755 { _T("value2"), _T("two") },
756 { _T("novalue"), _T("default") },
759 static void TestFileConfRead()
761 puts("*** testing wxFileConfig loading/reading ***");
763 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
764 _T("testdata.fc"), wxEmptyString
,
765 wxCONFIG_USE_RELATIVE_PATH
);
767 // test simple reading
768 puts("\nReading config file:");
769 wxString
defValue(_T("default")), value
;
770 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
772 const FileConfTestData
& data
= fcTestData
[n
];
773 value
= fileconf
.Read(data
.name
, defValue
);
774 printf("\t%s = %s ", data
.name
, value
.c_str());
775 if ( value
== data
.value
)
781 printf("(ERROR: should be %s)\n", data
.value
);
785 // test enumerating the entries
786 puts("\nEnumerating all root entries:");
789 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
792 printf("\t%s = %s\n",
794 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
796 cont
= fileconf
.GetNextEntry(name
, dummy
);
800 #endif // TEST_FILECONF
802 // ----------------------------------------------------------------------------
804 // ----------------------------------------------------------------------------
808 #include "wx/filename.h"
810 static void DumpFileName(const wxFileName
& fn
)
812 wxString full
= fn
.GetFullPath();
814 wxString vol
, path
, name
, ext
;
815 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
817 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
818 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
820 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
821 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
822 path
.c_str(), name
.c_str(), ext
.c_str());
824 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
825 wxPrintf(_T("with volume: \t'%s'\n"),
826 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
827 wxPrintf(_T("with separator:\t'%s'\n"),
828 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
829 wxPrintf(_T("with both: \t'%s'\n"),
830 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
832 wxPuts(_T("The directories in the path are:"));
833 wxArrayString dirs
= fn
.GetDirs();
834 size_t count
= dirs
.GetCount();
835 for ( size_t n
= 0; n
< count
; n
++ )
837 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
841 static struct FileNameInfo
843 const wxChar
*fullname
;
844 const wxChar
*volume
;
853 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
854 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
855 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
856 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
857 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
858 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
859 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
860 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
861 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
863 // Windows file names
864 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
865 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
866 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
867 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
868 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
869 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
870 { _T("\\\\server\\dir\\foo.bar"), _T("server"), _T("\\dir"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
872 // wxFileName support for Mac file names is broken currently
875 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
876 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
877 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
878 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
879 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
880 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
884 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
885 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
888 static void TestFileNameConstruction()
890 puts("*** testing wxFileName construction ***");
892 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
894 const FileNameInfo
& fni
= filenames
[n
];
896 wxFileName
fn(fni
.fullname
, fni
.format
);
898 wxString fullname
= fn
.GetFullPath(fni
.format
);
899 if ( fullname
!= fni
.fullname
)
901 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
904 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
905 printf("'%s' is %s (%s)\n\t",
907 isAbsolute
? "absolute" : "relative",
908 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
910 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
912 puts("ERROR (couldn't be normalized)");
916 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
923 static void TestFileNameSplit()
925 puts("*** testing wxFileName splitting ***");
927 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
929 const FileNameInfo
& fni
= filenames
[n
];
930 wxString volume
, path
, name
, ext
;
931 wxFileName::SplitPath(fni
.fullname
,
932 &volume
, &path
, &name
, &ext
, fni
.format
);
934 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
936 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
938 if ( volume
!= fni
.volume
)
939 printf(" (ERROR: volume = '%s')", fni
.volume
);
940 if ( path
!= fni
.path
)
941 printf(" (ERROR: path = '%s')", fni
.path
);
942 if ( name
!= fni
.name
)
943 printf(" (ERROR: name = '%s')", fni
.name
);
944 if ( ext
!= fni
.ext
)
945 printf(" (ERROR: ext = '%s')", fni
.ext
);
951 static void TestFileNameTemp()
953 puts("*** testing wxFileName temp file creation ***");
955 static const char *tmpprefixes
[] =
963 "/tmp/foo/bar", // this one must be an error
967 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
969 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
972 // "error" is not in upper case because it may be ok
973 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
977 printf("Prefix '%s'\t-> temp file '%s'\n",
978 tmpprefixes
[n
], path
.c_str());
980 if ( !wxRemoveFile(path
) )
982 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
988 static void TestFileNameMakeRelative()
990 puts("*** testing wxFileName::MakeRelativeTo() ***");
992 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
994 const FileNameInfo
& fni
= filenames
[n
];
996 wxFileName
fn(fni
.fullname
, fni
.format
);
998 // choose the base dir of the same format
1000 switch ( fni
.format
)
1012 // TODO: I don't know how this is supposed to work there
1015 case wxPATH_NATIVE
: // make gcc happy
1017 wxFAIL_MSG( "unexpected path format" );
1020 printf("'%s' relative to '%s': ",
1021 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
1023 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
1029 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
1034 static void TestFileNameComparison()
1039 static void TestFileNameOperations()
1044 static void TestFileNameCwd()
1049 #endif // TEST_FILENAME
1051 // ----------------------------------------------------------------------------
1052 // wxFileName time functions
1053 // ----------------------------------------------------------------------------
1055 #ifdef TEST_FILETIME
1057 #include <wx/filename.h>
1058 #include <wx/datetime.h>
1060 static void TestFileGetTimes()
1062 wxFileName
fn(_T("testdata.fc"));
1064 wxDateTime dtAccess
, dtMod
, dtCreate
;
1065 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1067 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1071 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1073 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1074 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1075 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1076 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1080 static void TestFileSetTimes()
1082 wxFileName
fn(_T("testdata.fc"));
1086 wxPrintf(_T("ERROR: Touch() failed.\n"));
1090 #endif // TEST_FILETIME
1092 // ----------------------------------------------------------------------------
1094 // ----------------------------------------------------------------------------
1098 #include "wx/hash.h"
1102 Foo(int n_
) { n
= n_
; count
++; }
1107 static size_t count
;
1110 size_t Foo::count
= 0;
1112 WX_DECLARE_LIST(Foo
, wxListFoos
);
1113 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1115 #include "wx/listimpl.cpp"
1117 WX_DEFINE_LIST(wxListFoos
);
1119 static void TestHash()
1121 puts("*** Testing wxHashTable ***\n");
1125 hash
.DeleteContents(TRUE
);
1127 printf("Hash created: %u foos in hash, %u foos totally\n",
1128 hash
.GetCount(), Foo::count
);
1130 static const int hashTestData
[] =
1132 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1136 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1138 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1141 printf("Hash filled: %u foos in hash, %u foos totally\n",
1142 hash
.GetCount(), Foo::count
);
1144 puts("Hash access test:");
1145 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1147 printf("\tGetting element with key %d, value %d: ",
1148 hashTestData
[n
], n
);
1149 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1152 printf("ERROR, not found.\n");
1156 printf("%d (%s)\n", foo
->n
,
1157 (size_t)foo
->n
== n
? "ok" : "ERROR");
1161 printf("\nTrying to get an element not in hash: ");
1163 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1165 puts("ERROR: found!");
1169 puts("ok (not found)");
1173 printf("Hash destroyed: %u foos left\n", Foo::count
);
1178 // ----------------------------------------------------------------------------
1180 // ----------------------------------------------------------------------------
1184 #include "wx/hashmap.h"
1186 // test compilation of basic map types
1187 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1188 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1189 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1190 myUnsignedHashMap
);
1191 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1193 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1195 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1197 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1201 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1202 // myStringHashMap );
1203 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1205 typedef myStringHashMap::iterator Itor
;
1207 static void TestHashMap()
1209 puts("*** Testing wxHashMap ***\n");
1210 myStringHashMap
sh(0); // as small as possible
1213 const size_t count
= 10000;
1215 // init with some data
1216 for( i
= 0; i
< count
; ++i
)
1218 buf
.Printf(wxT("%d"), i
);
1219 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1222 // test that insertion worked
1223 if( sh
.size() != count
)
1225 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1228 for( i
= 0; i
< count
; ++i
)
1230 buf
.Printf(wxT("%d"), i
);
1231 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1233 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1238 // check that iterators work
1240 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1244 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1248 if( it
->second
!= sh
[it
->first
] )
1250 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1255 if( sh
.size() != i
)
1257 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1260 // test copy ctor, assignment operator
1261 myStringHashMap
h1( sh
), h2( 0 );
1264 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1266 if( h1
[it
->first
] != it
->second
)
1268 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1271 if( h2
[it
->first
] != it
->second
)
1273 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1278 for( i
= 0; i
< count
; ++i
)
1280 buf
.Printf(wxT("%d"), i
);
1281 size_t sz
= sh
.size();
1283 // test find() and erase(it)
1286 it
= sh
.find( buf
);
1287 if( it
!= sh
.end() )
1291 if( sh
.find( buf
) != sh
.end() )
1293 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1297 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1302 size_t c
= sh
.erase( buf
);
1304 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1306 if( sh
.find( buf
) != sh
.end() )
1308 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1312 // count should decrease
1313 if( sh
.size() != sz
- 1 )
1315 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1319 printf("*** Finished testing wxHashMap ***\n");
1322 #endif // TEST_HASHMAP
1324 // ----------------------------------------------------------------------------
1326 // ----------------------------------------------------------------------------
1330 #include "wx/list.h"
1332 WX_DECLARE_LIST(Bar
, wxListBars
);
1333 #include "wx/listimpl.cpp"
1334 WX_DEFINE_LIST(wxListBars
);
1336 static void TestListCtor()
1338 puts("*** Testing wxList construction ***\n");
1342 list1
.Append(new Bar(_T("first")));
1343 list1
.Append(new Bar(_T("second")));
1345 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1346 list1
.GetCount(), Bar::GetNumber());
1351 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1352 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1354 list1
.DeleteContents(TRUE
);
1357 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1362 // ----------------------------------------------------------------------------
1364 // ----------------------------------------------------------------------------
1368 #include "wx/intl.h"
1369 #include "wx/utils.h" // for wxSetEnv
1371 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1373 // find the name of the language from its value
1374 static const char *GetLangName(int lang
)
1376 static const char *languageNames
[] =
1397 "ARABIC_SAUDI_ARABIA",
1422 "CHINESE_SIMPLIFIED",
1423 "CHINESE_TRADITIONAL",
1426 "CHINESE_SINGAPORE",
1437 "ENGLISH_AUSTRALIA",
1441 "ENGLISH_CARIBBEAN",
1445 "ENGLISH_NEW_ZEALAND",
1446 "ENGLISH_PHILIPPINES",
1447 "ENGLISH_SOUTH_AFRICA",
1459 "FRENCH_LUXEMBOURG",
1468 "GERMAN_LIECHTENSTEIN",
1469 "GERMAN_LUXEMBOURG",
1510 "MALAY_BRUNEI_DARUSSALAM",
1522 "NORWEGIAN_NYNORSK",
1529 "PORTUGUESE_BRAZILIAN",
1554 "SPANISH_ARGENTINA",
1558 "SPANISH_COSTA_RICA",
1559 "SPANISH_DOMINICAN_REPUBLIC",
1561 "SPANISH_EL_SALVADOR",
1562 "SPANISH_GUATEMALA",
1566 "SPANISH_NICARAGUA",
1570 "SPANISH_PUERTO_RICO",
1573 "SPANISH_VENEZUELA",
1610 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1611 return languageNames
[lang
];
1616 static void TestDefaultLang()
1618 puts("*** Testing wxLocale::GetSystemLanguage ***");
1620 static const wxChar
*langStrings
[] =
1622 NULL
, // system default
1629 _T("de_DE.iso88591"),
1631 _T("?"), // invalid lang spec
1632 _T("klingonese"), // I bet on some systems it does exist...
1635 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1636 wxLocale::GetSystemEncodingName().c_str(),
1637 wxLocale::GetSystemEncoding());
1639 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1641 const char *langStr
= langStrings
[n
];
1644 // FIXME: this doesn't do anything at all under Windows, we need
1645 // to create a new wxLocale!
1646 wxSetEnv(_T("LC_ALL"), langStr
);
1649 int lang
= gs_localeDefault
.GetSystemLanguage();
1650 printf("Locale for '%s' is %s.\n",
1651 langStr
? langStr
: "system default", GetLangName(lang
));
1655 #endif // TEST_LOCALE
1657 // ----------------------------------------------------------------------------
1659 // ----------------------------------------------------------------------------
1663 #include "wx/mimetype.h"
1665 static void TestMimeEnum()
1667 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1669 wxArrayString mimetypes
;
1671 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1673 printf("*** All %u known filetypes: ***\n", count
);
1678 for ( size_t n
= 0; n
< count
; n
++ )
1680 wxFileType
*filetype
=
1681 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1684 printf("nothing known about the filetype '%s'!\n",
1685 mimetypes
[n
].c_str());
1689 filetype
->GetDescription(&desc
);
1690 filetype
->GetExtensions(exts
);
1692 filetype
->GetIcon(NULL
);
1695 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1698 extsAll
<< _T(", ");
1702 printf("\t%s: %s (%s)\n",
1703 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1709 static void TestMimeOverride()
1711 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1713 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1714 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1716 if ( wxFile::Exists(mailcap
) )
1717 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1719 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1721 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1724 if ( wxFile::Exists(mimetypes
) )
1725 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1727 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1729 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1735 static void TestMimeFilename()
1737 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1739 static const wxChar
*filenames
[] =
1747 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1749 const wxString fname
= filenames
[n
];
1750 wxString ext
= fname
.AfterLast(_T('.'));
1751 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1754 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1759 if ( !ft
->GetDescription(&desc
) )
1760 desc
= _T("<no description>");
1763 if ( !ft
->GetOpenCommand(&cmd
,
1764 wxFileType::MessageParameters(fname
, _T(""))) )
1765 cmd
= _T("<no command available>");
1767 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1768 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1777 static void TestMimeAssociate()
1779 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1781 wxFileTypeInfo
ftInfo(
1782 _T("application/x-xyz"),
1783 _T("xyzview '%s'"), // open cmd
1784 _T(""), // print cmd
1785 _T("XYZ File"), // description
1786 _T(".xyz"), // extensions
1787 NULL
// end of extensions
1789 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1791 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1794 wxPuts(_T("ERROR: failed to create association!"));
1798 // TODO: read it back
1807 // ----------------------------------------------------------------------------
1808 // misc information functions
1809 // ----------------------------------------------------------------------------
1811 #ifdef TEST_INFO_FUNCTIONS
1813 #include "wx/utils.h"
1815 static void TestDiskInfo()
1817 puts("*** Testing wxGetDiskSpace() ***");
1822 printf("\nEnter a directory name: ");
1823 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1826 // kill the last '\n'
1827 pathname
[strlen(pathname
) - 1] = 0;
1829 wxLongLong total
, free
;
1830 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1832 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1836 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1837 (total
/ 1024).ToString().c_str(),
1838 (free
/ 1024).ToString().c_str(),
1844 static void TestOsInfo()
1846 puts("*** Testing OS info functions ***\n");
1849 wxGetOsVersion(&major
, &minor
);
1850 printf("Running under: %s, version %d.%d\n",
1851 wxGetOsDescription().c_str(), major
, minor
);
1853 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1855 printf("Host name is %s (%s).\n",
1856 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1861 static void TestUserInfo()
1863 puts("*** Testing user info functions ***\n");
1865 printf("User id is:\t%s\n", wxGetUserId().c_str());
1866 printf("User name is:\t%s\n", wxGetUserName().c_str());
1867 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1868 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1873 #endif // TEST_INFO_FUNCTIONS
1875 // ----------------------------------------------------------------------------
1877 // ----------------------------------------------------------------------------
1879 #ifdef TEST_LONGLONG
1881 #include "wx/longlong.h"
1882 #include "wx/timer.h"
1884 // make a 64 bit number from 4 16 bit ones
1885 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1887 // get a random 64 bit number
1888 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1890 static const long testLongs
[] =
1901 #if wxUSE_LONGLONG_WX
1902 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1903 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1904 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1905 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1906 #endif // wxUSE_LONGLONG_WX
1908 static void TestSpeed()
1910 static const long max
= 100000000;
1917 for ( n
= 0; n
< max
; n
++ )
1922 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1925 #if wxUSE_LONGLONG_NATIVE
1930 for ( n
= 0; n
< max
; n
++ )
1935 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1937 #endif // wxUSE_LONGLONG_NATIVE
1943 for ( n
= 0; n
< max
; n
++ )
1948 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1952 static void TestLongLongConversion()
1954 puts("*** Testing wxLongLong conversions ***\n");
1958 for ( size_t n
= 0; n
< 100000; n
++ )
1962 #if wxUSE_LONGLONG_NATIVE
1963 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1965 wxASSERT_MSG( a
== b
, "conversions failure" );
1967 puts("Can't do it without native long long type, test skipped.");
1970 #endif // wxUSE_LONGLONG_NATIVE
1972 if ( !(nTested
% 1000) )
1984 static void TestMultiplication()
1986 puts("*** Testing wxLongLong multiplication ***\n");
1990 for ( size_t n
= 0; n
< 100000; n
++ )
1995 #if wxUSE_LONGLONG_NATIVE
1996 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1997 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1999 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
2000 #else // !wxUSE_LONGLONG_NATIVE
2001 puts("Can't do it without native long long type, test skipped.");
2004 #endif // wxUSE_LONGLONG_NATIVE
2006 if ( !(nTested
% 1000) )
2018 static void TestDivision()
2020 puts("*** Testing wxLongLong division ***\n");
2024 for ( size_t n
= 0; n
< 100000; n
++ )
2026 // get a random wxLongLong (shifting by 12 the MSB ensures that the
2027 // multiplication will not overflow)
2028 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
2030 // get a random (but non null) long (not wxLongLong for now) to divide
2042 #if wxUSE_LONGLONG_NATIVE
2043 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
2045 wxLongLongNative p
= m
/ l
, s
= m
% l
;
2046 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
2047 #else // !wxUSE_LONGLONG_NATIVE
2048 // verify the result
2049 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
2050 #endif // wxUSE_LONGLONG_NATIVE
2052 if ( !(nTested
% 1000) )
2064 static void TestAddition()
2066 puts("*** Testing wxLongLong addition ***\n");
2070 for ( size_t n
= 0; n
< 100000; n
++ )
2076 #if wxUSE_LONGLONG_NATIVE
2077 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2078 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2079 "addition failure" );
2080 #else // !wxUSE_LONGLONG_NATIVE
2081 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2082 #endif // wxUSE_LONGLONG_NATIVE
2084 if ( !(nTested
% 1000) )
2096 static void TestBitOperations()
2098 puts("*** Testing wxLongLong bit operation ***\n");
2102 for ( size_t n
= 0; n
< 100000; n
++ )
2106 #if wxUSE_LONGLONG_NATIVE
2107 for ( size_t n
= 0; n
< 33; n
++ )
2110 #else // !wxUSE_LONGLONG_NATIVE
2111 puts("Can't do it without native long long type, test skipped.");
2114 #endif // wxUSE_LONGLONG_NATIVE
2116 if ( !(nTested
% 1000) )
2128 static void TestLongLongComparison()
2130 #if wxUSE_LONGLONG_WX
2131 puts("*** Testing wxLongLong comparison ***\n");
2133 static const long ls
[2] =
2139 wxLongLongWx lls
[2];
2143 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2147 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2149 res
= lls
[m
] > testLongs
[n
];
2150 printf("0x%lx > 0x%lx is %s (%s)\n",
2151 ls
[m
], testLongs
[n
], res
? "true" : "false",
2152 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2154 res
= lls
[m
] < testLongs
[n
];
2155 printf("0x%lx < 0x%lx is %s (%s)\n",
2156 ls
[m
], testLongs
[n
], res
? "true" : "false",
2157 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2159 res
= lls
[m
] == testLongs
[n
];
2160 printf("0x%lx == 0x%lx is %s (%s)\n",
2161 ls
[m
], testLongs
[n
], res
? "true" : "false",
2162 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2165 #endif // wxUSE_LONGLONG_WX
2168 static void TestLongLongPrint()
2170 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2172 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2174 wxLongLong ll
= testLongs
[n
];
2175 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2178 wxLongLong
ll(0x12345678, 0x87654321);
2179 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2182 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2188 #endif // TEST_LONGLONG
2190 // ----------------------------------------------------------------------------
2192 // ----------------------------------------------------------------------------
2194 #ifdef TEST_PATHLIST
2196 static void TestPathList()
2198 puts("*** Testing wxPathList ***\n");
2200 wxPathList pathlist
;
2201 pathlist
.AddEnvList("PATH");
2202 wxString path
= pathlist
.FindValidPath("ls");
2205 printf("ERROR: command not found in the path.\n");
2209 printf("Command found in the path as '%s'.\n", path
.c_str());
2213 #endif // TEST_PATHLIST
2215 // ----------------------------------------------------------------------------
2216 // regular expressions
2217 // ----------------------------------------------------------------------------
2221 #include "wx/regex.h"
2223 static void TestRegExCompile()
2225 wxPuts(_T("*** Testing RE compilation ***\n"));
2227 static struct RegExCompTestData
2229 const wxChar
*pattern
;
2231 } regExCompTestData
[] =
2233 { _T("foo"), TRUE
},
2234 { _T("foo("), FALSE
},
2235 { _T("foo(bar"), FALSE
},
2236 { _T("foo(bar)"), TRUE
},
2237 { _T("foo["), FALSE
},
2238 { _T("foo[bar"), FALSE
},
2239 { _T("foo[bar]"), TRUE
},
2240 { _T("foo{"), TRUE
},
2241 { _T("foo{1"), FALSE
},
2242 { _T("foo{bar"), TRUE
},
2243 { _T("foo{1}"), TRUE
},
2244 { _T("foo{1,2}"), TRUE
},
2245 { _T("foo{bar}"), TRUE
},
2246 { _T("foo*"), TRUE
},
2247 { _T("foo**"), FALSE
},
2248 { _T("foo+"), TRUE
},
2249 { _T("foo++"), FALSE
},
2250 { _T("foo?"), TRUE
},
2251 { _T("foo??"), FALSE
},
2252 { _T("foo?+"), FALSE
},
2256 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2258 const RegExCompTestData
& data
= regExCompTestData
[n
];
2259 bool ok
= re
.Compile(data
.pattern
);
2261 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2263 ok
? _T("") : _T("not "),
2264 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2268 static void TestRegExMatch()
2270 wxPuts(_T("*** Testing RE matching ***\n"));
2272 static struct RegExMatchTestData
2274 const wxChar
*pattern
;
2277 } regExMatchTestData
[] =
2279 { _T("foo"), _T("bar"), FALSE
},
2280 { _T("foo"), _T("foobar"), TRUE
},
2281 { _T("^foo"), _T("foobar"), TRUE
},
2282 { _T("^foo"), _T("barfoo"), FALSE
},
2283 { _T("bar$"), _T("barbar"), TRUE
},
2284 { _T("bar$"), _T("barbar "), FALSE
},
2287 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2289 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2291 wxRegEx
re(data
.pattern
);
2292 bool ok
= re
.Matches(data
.text
);
2294 wxPrintf(_T("'%s' %s %s (%s)\n"),
2296 ok
? _T("matches") : _T("doesn't match"),
2298 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2302 static void TestRegExSubmatch()
2304 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2306 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2307 if ( !re
.IsValid() )
2309 wxPuts(_T("ERROR: compilation failed."));
2313 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2315 if ( !re
.Matches(text
) )
2317 wxPuts(_T("ERROR: match expected."));
2321 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2323 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2324 re
.GetMatch(text
, 3).c_str(),
2325 re
.GetMatch(text
, 2).c_str(),
2326 re
.GetMatch(text
, 4).c_str(),
2327 re
.GetMatch(text
, 1).c_str());
2331 static void TestRegExReplacement()
2333 wxPuts(_T("*** Testing RE replacement ***"));
2335 static struct RegExReplTestData
2339 const wxChar
*result
;
2341 } regExReplTestData
[] =
2343 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2344 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2345 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2346 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2347 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2348 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2349 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2352 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2353 wxRegEx
re(pattern
);
2355 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2357 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2359 const RegExReplTestData
& data
= regExReplTestData
[n
];
2361 wxString text
= data
.text
;
2362 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2364 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2365 data
.text
, data
.repl
,
2366 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2368 if ( text
== data
.result
&& nRepl
== data
.count
)
2374 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2375 data
.count
, data
.result
);
2380 static void TestRegExInteractive()
2382 wxPuts(_T("*** Testing RE interactively ***"));
2387 printf("\nEnter a pattern: ");
2388 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2391 // kill the last '\n'
2392 pattern
[strlen(pattern
) - 1] = 0;
2395 if ( !re
.Compile(pattern
) )
2403 printf("Enter text to match: ");
2404 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2407 // kill the last '\n'
2408 text
[strlen(text
) - 1] = 0;
2410 if ( !re
.Matches(text
) )
2412 printf("No match.\n");
2416 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2419 for ( size_t n
= 1; ; n
++ )
2421 if ( !re
.GetMatch(&start
, &len
, n
) )
2426 printf("Subexpr %u matched '%s'\n",
2427 n
, wxString(text
+ start
, len
).c_str());
2434 #endif // TEST_REGEX
2436 // ----------------------------------------------------------------------------
2438 // ----------------------------------------------------------------------------
2448 static void TestDbOpen()
2456 // ----------------------------------------------------------------------------
2457 // registry and related stuff
2458 // ----------------------------------------------------------------------------
2460 // this is for MSW only
2463 #undef TEST_REGISTRY
2468 #include "wx/confbase.h"
2469 #include "wx/msw/regconf.h"
2471 static void TestRegConfWrite()
2473 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2474 regconf
.Write(_T("Hello"), wxString(_T("world")));
2477 #endif // TEST_REGCONF
2479 #ifdef TEST_REGISTRY
2481 #include "wx/msw/registry.h"
2483 // I chose this one because I liked its name, but it probably only exists under
2485 static const wxChar
*TESTKEY
=
2486 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2488 static void TestRegistryRead()
2490 puts("*** testing registry reading ***");
2492 wxRegKey
key(TESTKEY
);
2493 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2496 puts("ERROR: test key can't be opened, aborting test.");
2501 size_t nSubKeys
, nValues
;
2502 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2504 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2507 printf("Enumerating values:\n");
2511 bool cont
= key
.GetFirstValue(value
, dummy
);
2514 printf("Value '%s': type ", value
.c_str());
2515 switch ( key
.GetValueType(value
) )
2517 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2518 case wxRegKey::Type_String
: printf("SZ"); break;
2519 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2520 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2521 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2522 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2523 default: printf("other (unknown)"); break;
2526 printf(", value = ");
2527 if ( key
.IsNumericValue(value
) )
2530 key
.QueryValue(value
, &val
);
2536 key
.QueryValue(value
, val
);
2537 printf("'%s'", val
.c_str());
2539 key
.QueryRawValue(value
, val
);
2540 printf(" (raw value '%s')", val
.c_str());
2545 cont
= key
.GetNextValue(value
, dummy
);
2549 static void TestRegistryAssociation()
2552 The second call to deleteself genertaes an error message, with a
2553 messagebox saying .flo is crucial to system operation, while the .ddf
2554 call also fails, but with no error message
2559 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2561 key
= "ddxf_auto_file" ;
2562 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2564 key
= "ddxf_auto_file" ;
2565 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2568 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2570 key
= "program \"%1\"" ;
2572 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2574 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2576 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2578 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2582 #endif // TEST_REGISTRY
2584 // ----------------------------------------------------------------------------
2586 // ----------------------------------------------------------------------------
2590 #include "wx/socket.h"
2591 #include "wx/protocol/protocol.h"
2592 #include "wx/protocol/http.h"
2594 static void TestSocketServer()
2596 puts("*** Testing wxSocketServer ***\n");
2598 static const int PORT
= 3000;
2603 wxSocketServer
*server
= new wxSocketServer(addr
);
2604 if ( !server
->Ok() )
2606 puts("ERROR: failed to bind");
2613 printf("Server: waiting for connection on port %d...\n", PORT
);
2615 wxSocketBase
*socket
= server
->Accept();
2618 puts("ERROR: wxSocketServer::Accept() failed.");
2622 puts("Server: got a client.");
2624 server
->SetTimeout(60); // 1 min
2626 while ( socket
->IsConnected() )
2632 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2634 // don't log error if the client just close the connection
2635 if ( socket
->IsConnected() )
2637 puts("ERROR: in wxSocket::Read.");
2657 printf("Server: got '%s'.\n", s
.c_str());
2658 if ( s
== _T("bye") )
2665 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2666 socket
->Write("\r\n", 2);
2667 printf("Server: wrote '%s'.\n", s
.c_str());
2670 puts("Server: lost a client.");
2675 // same as "delete server" but is consistent with GUI programs
2679 static void TestSocketClient()
2681 puts("*** Testing wxSocketClient ***\n");
2683 static const char *hostname
= "www.wxwindows.org";
2686 addr
.Hostname(hostname
);
2689 printf("--- Attempting to connect to %s:80...\n", hostname
);
2691 wxSocketClient client
;
2692 if ( !client
.Connect(addr
) )
2694 printf("ERROR: failed to connect to %s\n", hostname
);
2698 printf("--- Connected to %s:%u...\n",
2699 addr
.Hostname().c_str(), addr
.Service());
2703 // could use simply "GET" here I suppose
2705 wxString::Format("GET http://%s/\r\n", hostname
);
2706 client
.Write(cmdGet
, cmdGet
.length());
2707 printf("--- Sent command '%s' to the server\n",
2708 MakePrintable(cmdGet
).c_str());
2709 client
.Read(buf
, WXSIZEOF(buf
));
2710 printf("--- Server replied:\n%s", buf
);
2714 #endif // TEST_SOCKETS
2716 // ----------------------------------------------------------------------------
2718 // ----------------------------------------------------------------------------
2722 #include "wx/protocol/ftp.h"
2726 #define FTP_ANONYMOUS
2728 #ifdef FTP_ANONYMOUS
2729 static const char *directory
= "/pub";
2730 static const char *filename
= "welcome.msg";
2732 static const char *directory
= "/etc";
2733 static const char *filename
= "issue";
2736 static bool TestFtpConnect()
2738 puts("*** Testing FTP connect ***");
2740 #ifdef FTP_ANONYMOUS
2741 static const char *hostname
= "ftp.wxwindows.org";
2743 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2744 #else // !FTP_ANONYMOUS
2745 static const char *hostname
= "localhost";
2748 fgets(user
, WXSIZEOF(user
), stdin
);
2749 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2753 printf("Password for %s: ", password
);
2754 fgets(password
, WXSIZEOF(password
), stdin
);
2755 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2756 ftp
.SetPassword(password
);
2758 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2759 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2761 if ( !ftp
.Connect(hostname
) )
2763 printf("ERROR: failed to connect to %s\n", hostname
);
2769 printf("--- Connected to %s, current directory is '%s'\n",
2770 hostname
, ftp
.Pwd().c_str());
2776 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2777 static void TestFtpWuFtpd()
2780 static const char *hostname
= "ftp.eudora.com";
2781 if ( !ftp
.Connect(hostname
) )
2783 printf("ERROR: failed to connect to %s\n", hostname
);
2787 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2788 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2791 printf("ERROR: couldn't get input stream for %s\n", filename
);
2795 size_t size
= in
->StreamSize();
2796 printf("Reading file %s (%u bytes)...", filename
, size
);
2798 char *data
= new char[size
];
2799 if ( !in
->Read(data
, size
) )
2801 puts("ERROR: read error");
2805 printf("Successfully retrieved the file.\n");
2814 static void TestFtpList()
2816 puts("*** Testing wxFTP file listing ***\n");
2819 if ( !ftp
.ChDir(directory
) )
2821 printf("ERROR: failed to cd to %s\n", directory
);
2824 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2826 // test NLIST and LIST
2827 wxArrayString files
;
2828 if ( !ftp
.GetFilesList(files
) )
2830 puts("ERROR: failed to get NLIST of files");
2834 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2835 size_t count
= files
.GetCount();
2836 for ( size_t n
= 0; n
< count
; n
++ )
2838 printf("\t%s\n", files
[n
].c_str());
2840 puts("End of the file list");
2843 if ( !ftp
.GetDirList(files
) )
2845 puts("ERROR: failed to get LIST of files");
2849 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2850 size_t count
= files
.GetCount();
2851 for ( size_t n
= 0; n
< count
; n
++ )
2853 printf("\t%s\n", files
[n
].c_str());
2855 puts("End of the file list");
2858 if ( !ftp
.ChDir(_T("..")) )
2860 puts("ERROR: failed to cd to ..");
2863 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2866 static void TestFtpDownload()
2868 puts("*** Testing wxFTP download ***\n");
2871 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2874 printf("ERROR: couldn't get input stream for %s\n", filename
);
2878 size_t size
= in
->StreamSize();
2879 printf("Reading file %s (%u bytes)...", filename
, size
);
2882 char *data
= new char[size
];
2883 if ( !in
->Read(data
, size
) )
2885 puts("ERROR: read error");
2889 printf("\nContents of %s:\n%s\n", filename
, data
);
2897 static void TestFtpFileSize()
2899 puts("*** Testing FTP SIZE command ***");
2901 if ( !ftp
.ChDir(directory
) )
2903 printf("ERROR: failed to cd to %s\n", directory
);
2906 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2908 if ( ftp
.FileExists(filename
) )
2910 int size
= ftp
.GetFileSize(filename
);
2912 printf("ERROR: couldn't get size of '%s'\n", filename
);
2914 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2918 printf("ERROR: '%s' doesn't exist\n", filename
);
2922 static void TestFtpMisc()
2924 puts("*** Testing miscellaneous wxFTP functions ***");
2926 if ( ftp
.SendCommand("STAT") != '2' )
2928 puts("ERROR: STAT failed");
2932 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2935 if ( ftp
.SendCommand("HELP SITE") != '2' )
2937 puts("ERROR: HELP SITE failed");
2941 printf("The list of site-specific commands:\n\n%s\n",
2942 ftp
.GetLastResult().c_str());
2946 static void TestFtpInteractive()
2948 puts("\n*** Interactive wxFTP test ***");
2954 printf("Enter FTP command: ");
2955 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2958 // kill the last '\n'
2959 buf
[strlen(buf
) - 1] = 0;
2961 // special handling of LIST and NLST as they require data connection
2962 wxString
start(buf
, 4);
2964 if ( start
== "LIST" || start
== "NLST" )
2967 if ( strlen(buf
) > 4 )
2970 wxArrayString files
;
2971 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2973 printf("ERROR: failed to get %s of files\n", start
.c_str());
2977 printf("--- %s of '%s' under '%s':\n",
2978 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2979 size_t count
= files
.GetCount();
2980 for ( size_t n
= 0; n
< count
; n
++ )
2982 printf("\t%s\n", files
[n
].c_str());
2984 puts("--- End of the file list");
2989 char ch
= ftp
.SendCommand(buf
);
2990 printf("Command %s", ch
? "succeeded" : "failed");
2993 printf(" (return code %c)", ch
);
2996 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
3000 puts("\n*** done ***");
3003 static void TestFtpUpload()
3005 puts("*** Testing wxFTP uploading ***\n");
3008 static const char *file1
= "test1";
3009 static const char *file2
= "test2";
3010 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
3013 printf("--- Uploading to %s ---\n", file1
);
3014 out
->Write("First hello", 11);
3018 // send a command to check the remote file
3019 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
3021 printf("ERROR: STAT %s failed\n", file1
);
3025 printf("STAT %s returned:\n\n%s\n",
3026 file1
, ftp
.GetLastResult().c_str());
3029 out
= ftp
.GetOutputStream(file2
);
3032 printf("--- Uploading to %s ---\n", file1
);
3033 out
->Write("Second hello", 12);
3040 // ----------------------------------------------------------------------------
3042 // ----------------------------------------------------------------------------
3046 #include "wx/wfstream.h"
3047 #include "wx/mstream.h"
3049 static void TestFileStream()
3051 puts("*** Testing wxFileInputStream ***");
3053 static const wxChar
*filename
= _T("testdata.fs");
3055 wxFileOutputStream
fsOut(filename
);
3056 fsOut
.Write("foo", 3);
3059 wxFileInputStream
fsIn(filename
);
3060 printf("File stream size: %u\n", fsIn
.GetSize());
3061 while ( !fsIn
.Eof() )
3063 putchar(fsIn
.GetC());
3066 if ( !wxRemoveFile(filename
) )
3068 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3071 puts("\n*** wxFileInputStream test done ***");
3074 static void TestMemoryStream()
3076 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
3078 wxMemoryOutputStream memOutStream
;
3079 wxPrintf(_T("Initially out stream offset: %lu\n"),
3080 (unsigned long)memOutStream
.TellO());
3082 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
3084 memOutStream
.PutC(*p
);
3087 wxPrintf(_T("Final out stream offset: %lu\n"),
3088 (unsigned long)memOutStream
.TellO());
3090 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
3093 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
3095 wxMemoryInputStream
memInpStream(buf
, len
);
3096 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3097 while ( !memInpStream
.Eof() )
3099 putchar(memInpStream
.GetC());
3102 puts("\n*** wxMemoryInputStream test done ***");
3105 #endif // TEST_STREAMS
3107 // ----------------------------------------------------------------------------
3109 // ----------------------------------------------------------------------------
3113 #include "wx/timer.h"
3114 #include "wx/utils.h"
3116 static void TestStopWatch()
3118 puts("*** Testing wxStopWatch ***\n");
3122 printf("Initially paused, after 2 seconds time is...");
3125 printf("\t%ldms\n", sw
.Time());
3127 printf("Resuming stopwatch and sleeping 3 seconds...");
3131 printf("\telapsed time: %ldms\n", sw
.Time());
3134 printf("Pausing agan and sleeping 2 more seconds...");
3137 printf("\telapsed time: %ldms\n", sw
.Time());
3140 printf("Finally resuming and sleeping 2 more seconds...");
3143 printf("\telapsed time: %ldms\n", sw
.Time());
3146 puts("\nChecking for 'backwards clock' bug...");
3147 for ( size_t n
= 0; n
< 70; n
++ )
3151 for ( size_t m
= 0; m
< 100000; m
++ )
3153 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3155 puts("\ntime is negative - ERROR!");
3166 #endif // TEST_TIMER
3168 // ----------------------------------------------------------------------------
3170 // ----------------------------------------------------------------------------
3174 #include "wx/vcard.h"
3176 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3179 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3183 wxString(_T('\t'), level
).c_str(),
3184 vcObj
->GetName().c_str());
3187 switch ( vcObj
->GetType() )
3189 case wxVCardObject::String
:
3190 case wxVCardObject::UString
:
3193 vcObj
->GetValue(&val
);
3194 value
<< _T('"') << val
<< _T('"');
3198 case wxVCardObject::Int
:
3201 vcObj
->GetValue(&i
);
3202 value
.Printf(_T("%u"), i
);
3206 case wxVCardObject::Long
:
3209 vcObj
->GetValue(&l
);
3210 value
.Printf(_T("%lu"), l
);
3214 case wxVCardObject::None
:
3217 case wxVCardObject::Object
:
3218 value
= _T("<node>");
3222 value
= _T("<unknown value type>");
3226 printf(" = %s", value
.c_str());
3229 DumpVObject(level
+ 1, *vcObj
);
3232 vcObj
= vcard
.GetNextProp(&cookie
);
3236 static void DumpVCardAddresses(const wxVCard
& vcard
)
3238 puts("\nShowing all addresses from vCard:\n");
3242 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3246 int flags
= addr
->GetFlags();
3247 if ( flags
& wxVCardAddress::Domestic
)
3249 flagsStr
<< _T("domestic ");
3251 if ( flags
& wxVCardAddress::Intl
)
3253 flagsStr
<< _T("international ");
3255 if ( flags
& wxVCardAddress::Postal
)
3257 flagsStr
<< _T("postal ");
3259 if ( flags
& wxVCardAddress::Parcel
)
3261 flagsStr
<< _T("parcel ");
3263 if ( flags
& wxVCardAddress::Home
)
3265 flagsStr
<< _T("home ");
3267 if ( flags
& wxVCardAddress::Work
)
3269 flagsStr
<< _T("work ");
3272 printf("Address %u:\n"
3274 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3277 addr
->GetPostOffice().c_str(),
3278 addr
->GetExtAddress().c_str(),
3279 addr
->GetStreet().c_str(),
3280 addr
->GetLocality().c_str(),
3281 addr
->GetRegion().c_str(),
3282 addr
->GetPostalCode().c_str(),
3283 addr
->GetCountry().c_str()
3287 addr
= vcard
.GetNextAddress(&cookie
);
3291 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3293 puts("\nShowing all phone numbers from vCard:\n");
3297 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3301 int flags
= phone
->GetFlags();
3302 if ( flags
& wxVCardPhoneNumber::Voice
)
3304 flagsStr
<< _T("voice ");
3306 if ( flags
& wxVCardPhoneNumber::Fax
)
3308 flagsStr
<< _T("fax ");
3310 if ( flags
& wxVCardPhoneNumber::Cellular
)
3312 flagsStr
<< _T("cellular ");
3314 if ( flags
& wxVCardPhoneNumber::Modem
)
3316 flagsStr
<< _T("modem ");
3318 if ( flags
& wxVCardPhoneNumber::Home
)
3320 flagsStr
<< _T("home ");
3322 if ( flags
& wxVCardPhoneNumber::Work
)
3324 flagsStr
<< _T("work ");
3327 printf("Phone number %u:\n"
3332 phone
->GetNumber().c_str()
3336 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3340 static void TestVCardRead()
3342 puts("*** Testing wxVCard reading ***\n");
3344 wxVCard
vcard(_T("vcard.vcf"));
3345 if ( !vcard
.IsOk() )
3347 puts("ERROR: couldn't load vCard.");
3351 // read individual vCard properties
3352 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3356 vcObj
->GetValue(&value
);
3361 value
= _T("<none>");
3364 printf("Full name retrieved directly: %s\n", value
.c_str());
3367 if ( !vcard
.GetFullName(&value
) )
3369 value
= _T("<none>");
3372 printf("Full name from wxVCard API: %s\n", value
.c_str());
3374 // now show how to deal with multiply occuring properties
3375 DumpVCardAddresses(vcard
);
3376 DumpVCardPhoneNumbers(vcard
);
3378 // and finally show all
3379 puts("\nNow dumping the entire vCard:\n"
3380 "-----------------------------\n");
3382 DumpVObject(0, vcard
);
3386 static void TestVCardWrite()
3388 puts("*** Testing wxVCard writing ***\n");
3391 if ( !vcard
.IsOk() )
3393 puts("ERROR: couldn't create vCard.");
3398 vcard
.SetName("Zeitlin", "Vadim");
3399 vcard
.SetFullName("Vadim Zeitlin");
3400 vcard
.SetOrganization("wxWindows", "R&D");
3402 // just dump the vCard back
3403 puts("Entire vCard follows:\n");
3404 puts(vcard
.Write());
3408 #endif // TEST_VCARD
3410 // ----------------------------------------------------------------------------
3412 // ----------------------------------------------------------------------------
3414 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3420 #include "wx/volume.h"
3422 static const wxChar
*volumeKinds
[] =
3428 _T("network volume"),
3432 static void TestFSVolume()
3434 wxPuts(_T("*** Testing wxFSVolume class ***"));
3436 wxArrayString volumes
= wxFSVolume::GetVolumes();
3437 size_t count
= volumes
.GetCount();
3441 wxPuts(_T("ERROR: no mounted volumes?"));
3445 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3447 for ( size_t n
= 0; n
< count
; n
++ )
3449 wxFSVolume
vol(volumes
[n
]);
3452 wxPuts(_T("ERROR: couldn't create volume"));
3456 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3458 vol
.GetDisplayName().c_str(),
3459 vol
.GetName().c_str(),
3460 volumeKinds
[vol
.GetKind()],
3461 vol
.IsWritable() ? _T("rw") : _T("ro"),
3462 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3467 #endif // TEST_VOLUME
3469 // ----------------------------------------------------------------------------
3470 // wide char and Unicode support
3471 // ----------------------------------------------------------------------------
3475 static void TestUnicodeToFromAscii()
3477 wxPuts(_T("Testing wxString::To/FromAscii()\n"));
3479 static const char *msg
= "Hello, world!";
3480 wxString s
= wxString::FromAscii(msg
);
3482 wxPrintf(_T("Message in Unicode: %s\n"), s
.c_str());
3483 printf("Message in ASCII: %s\n", s
.ToAscii());
3485 wxPutchar(_T('\n'));
3488 #endif // TEST_UNICODE
3492 #include "wx/strconv.h"
3493 #include "wx/fontenc.h"
3494 #include "wx/encconv.h"
3495 #include "wx/buffer.h"
3497 static const char textInUtf8
[] =
3499 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3500 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3501 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3502 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3503 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3504 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3505 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3508 static void TestUtf8()
3510 puts("*** Testing UTF8 support ***\n");
3514 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3516 puts("ERROR: UTF-8 decoding failed.");
3520 wxCSConv
conv(_T("koi8-r"));
3521 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3523 puts("ERROR: conversion to KOI8-R failed.");
3527 printf("The resulting string (in KOI8-R): %s\n", buf
);
3531 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3533 puts("ERROR: conversion to UTF-8 failed.");
3537 printf("The string in UTF-8: %s\n", buf
);
3543 static void TestEncodingConverter()
3545 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3547 // using wxEncodingConverter should give the same result as above
3550 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3552 puts("ERROR: UTF-8 decoding failed.");
3556 wxEncodingConverter ec
;
3557 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3558 ec
.Convert(wbuf
, buf
);
3559 printf("The same string obtained using wxEC: %s\n", buf
);
3565 #endif // TEST_WCHAR
3567 // ----------------------------------------------------------------------------
3569 // ----------------------------------------------------------------------------
3573 #include "wx/filesys.h"
3574 #include "wx/fs_zip.h"
3575 #include "wx/zipstrm.h"
3577 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3579 static void TestZipStreamRead()
3581 puts("*** Testing ZIP reading ***\n");
3583 static const wxChar
*filename
= _T("foo");
3584 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3585 printf("Archive size: %u\n", istr
.GetSize());
3587 printf("Dumping the file '%s':\n", filename
);
3588 while ( !istr
.Eof() )
3590 putchar(istr
.GetC());
3594 puts("\n----- done ------");
3597 static void DumpZipDirectory(wxFileSystem
& fs
,
3598 const wxString
& dir
,
3599 const wxString
& indent
)
3601 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3602 TESTFILE_ZIP
, dir
.c_str());
3603 wxString wildcard
= prefix
+ _T("/*");
3605 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3606 while ( !dirname
.empty() )
3608 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3610 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3615 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3617 DumpZipDirectory(fs
, dirname
,
3618 indent
+ wxString(_T(' '), 4));
3620 dirname
= fs
.FindNext();
3623 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3624 while ( !filename
.empty() )
3626 if ( !filename
.StartsWith(prefix
, &filename
) )
3628 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3633 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3635 filename
= fs
.FindNext();
3639 static void TestZipFileSystem()
3641 puts("*** Testing ZIP file system ***\n");
3643 wxFileSystem::AddHandler(new wxZipFSHandler
);
3645 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3647 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3652 // ----------------------------------------------------------------------------
3654 // ----------------------------------------------------------------------------
3658 #include "wx/zstream.h"
3659 #include "wx/wfstream.h"
3661 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3662 static const char *TEST_DATA
= "hello and hello and hello and hello and hello";
3664 static void TestZlibStreamWrite()
3666 puts("*** Testing Zlib stream reading ***\n");
3668 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3669 wxZlibOutputStream
ostr(fileOutStream
);
3670 printf("Compressing the test string... ");
3671 ostr
.Write(TEST_DATA
, strlen(TEST_DATA
) + 1);
3674 puts("(ERROR: failed)");
3681 puts("\n----- done ------");
3684 static void TestZlibStreamRead()
3686 puts("*** Testing Zlib stream reading ***\n");
3688 wxFileInputStream
fileInStream(FILENAME_GZ
);
3689 wxZlibInputStream
istr(fileInStream
);
3690 printf("Archive size: %u\n", istr
.GetSize());
3692 puts("Dumping the file:");
3693 while ( !istr
.Eof() )
3695 putchar(istr
.GetC());
3699 puts("\n----- done ------");
3704 // ----------------------------------------------------------------------------
3706 // ----------------------------------------------------------------------------
3708 #ifdef TEST_DATETIME
3712 #include "wx/date.h"
3713 #include "wx/datetime.h"
3718 wxDateTime::wxDateTime_t day
;
3719 wxDateTime::Month month
;
3721 wxDateTime::wxDateTime_t hour
, min
, sec
;
3723 wxDateTime::WeekDay wday
;
3724 time_t gmticks
, ticks
;
3726 void Init(const wxDateTime::Tm
& tm
)
3735 gmticks
= ticks
= -1;
3738 wxDateTime
DT() const
3739 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3741 bool SameDay(const wxDateTime::Tm
& tm
) const
3743 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3746 wxString
Format() const
3749 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3751 wxDateTime::GetMonthName(month
).c_str(),
3753 abs(wxDateTime::ConvertYearToBC(year
)),
3754 year
> 0 ? "AD" : "BC");
3758 wxString
FormatDate() const
3761 s
.Printf("%02d-%s-%4d%s",
3763 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3764 abs(wxDateTime::ConvertYearToBC(year
)),
3765 year
> 0 ? "AD" : "BC");
3770 static const Date testDates
[] =
3772 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3773 { 7, wxDateTime::Feb
, 2036, 00, 00, 00, 2464730.5, wxDateTime::Thu
, -1, -1 },
3774 { 8, wxDateTime::Feb
, 2036, 00, 00, 00, 2464731.5, wxDateTime::Fri
, -1, -1 },
3775 { 1, wxDateTime::Jan
, 2037, 00, 00, 00, 2465059.5, wxDateTime::Thu
, -1, -1 },
3776 { 1, wxDateTime::Jan
, 2038, 00, 00, 00, 2465424.5, wxDateTime::Fri
, -1, -1 },
3777 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3778 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3779 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3780 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3781 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3782 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3783 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3784 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3785 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3786 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3787 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3788 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3789 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3790 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3793 // this test miscellaneous static wxDateTime functions
3794 static void TestTimeStatic()
3796 puts("\n*** wxDateTime static methods test ***");
3798 // some info about the current date
3799 int year
= wxDateTime::GetCurrentYear();
3800 printf("Current year %d is %sa leap one and has %d days.\n",
3802 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3803 wxDateTime::GetNumberOfDays(year
));
3805 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3806 printf("Current month is '%s' ('%s') and it has %d days\n",
3807 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3808 wxDateTime::GetMonthName(month
).c_str(),
3809 wxDateTime::GetNumberOfDays(month
));
3812 static const size_t nYears
= 5;
3813 static const size_t years
[2][nYears
] =
3815 // first line: the years to test
3816 { 1990, 1976, 2000, 2030, 1984, },
3818 // second line: TRUE if leap, FALSE otherwise
3819 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3822 for ( size_t n
= 0; n
< nYears
; n
++ )
3824 int year
= years
[0][n
];
3825 bool should
= years
[1][n
] != 0,
3826 is
= wxDateTime::IsLeapYear(year
);
3828 printf("Year %d is %sa leap year (%s)\n",
3831 should
== is
? "ok" : "ERROR");
3833 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3837 // test constructing wxDateTime objects
3838 static void TestTimeSet()
3840 puts("\n*** wxDateTime construction test ***");
3842 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3844 const Date
& d1
= testDates
[n
];
3845 wxDateTime dt
= d1
.DT();
3848 d2
.Init(dt
.GetTm());
3850 wxString s1
= d1
.Format(),
3853 printf("Date: %s == %s (%s)\n",
3854 s1
.c_str(), s2
.c_str(),
3855 s1
== s2
? "ok" : "ERROR");
3859 // test time zones stuff
3860 static void TestTimeZones()
3862 puts("\n*** wxDateTime timezone test ***");
3864 wxDateTime now
= wxDateTime::Now();
3866 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3867 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3868 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3869 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3870 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3871 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3873 wxDateTime::Tm tm
= now
.GetTm();
3874 if ( wxDateTime(tm
) != now
)
3876 printf("ERROR: got %s instead of %s\n",
3877 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3881 // test some minimal support for the dates outside the standard range
3882 static void TestTimeRange()
3884 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3886 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3888 printf("Unix epoch:\t%s\n",
3889 wxDateTime(2440587.5).Format(fmt
).c_str());
3890 printf("Feb 29, 0: \t%s\n",
3891 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3892 printf("JDN 0: \t%s\n",
3893 wxDateTime(0.0).Format(fmt
).c_str());
3894 printf("Jan 1, 1AD:\t%s\n",
3895 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3896 printf("May 29, 2099:\t%s\n",
3897 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3900 static void TestTimeTicks()
3902 puts("\n*** wxDateTime ticks test ***");
3904 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3906 const Date
& d
= testDates
[n
];
3907 if ( d
.ticks
== -1 )
3910 wxDateTime dt
= d
.DT();
3911 long ticks
= (dt
.GetValue() / 1000).ToLong();
3912 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3913 if ( ticks
== d
.ticks
)
3919 printf(" (ERROR: should be %ld, delta = %ld)\n",
3920 (long)d
.ticks
, (long)(ticks
- d
.ticks
));
3923 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3924 ticks
= (dt
.GetValue() / 1000).ToLong();
3925 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3926 if ( ticks
== d
.gmticks
)
3932 printf(" (ERROR: should be %ld, delta = %ld)\n",
3933 (long)d
.gmticks
, (long)(ticks
- d
.gmticks
));
3940 // test conversions to JDN &c
3941 static void TestTimeJDN()
3943 puts("\n*** wxDateTime to JDN test ***");
3945 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3947 const Date
& d
= testDates
[n
];
3948 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3949 double jdn
= dt
.GetJulianDayNumber();
3951 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3958 printf(" (ERROR: should be %f, delta = %f)\n",
3959 d
.jdn
, jdn
- d
.jdn
);
3964 // test week days computation
3965 static void TestTimeWDays()
3967 puts("\n*** wxDateTime weekday test ***");
3969 // test GetWeekDay()
3971 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3973 const Date
& d
= testDates
[n
];
3974 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3976 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3979 wxDateTime::GetWeekDayName(wday
).c_str());
3980 if ( wday
== d
.wday
)
3986 printf(" (ERROR: should be %s)\n",
3987 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3993 // test SetToWeekDay()
3994 struct WeekDateTestData
3996 Date date
; // the real date (precomputed)
3997 int nWeek
; // its week index in the month
3998 wxDateTime::WeekDay wday
; // the weekday
3999 wxDateTime::Month month
; // the month
4000 int year
; // and the year
4002 wxString
Format() const
4005 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
4007 case 1: which
= "first"; break;
4008 case 2: which
= "second"; break;
4009 case 3: which
= "third"; break;
4010 case 4: which
= "fourth"; break;
4011 case 5: which
= "fifth"; break;
4013 case -1: which
= "last"; break;
4018 which
+= " from end";
4021 s
.Printf("The %s %s of %s in %d",
4023 wxDateTime::GetWeekDayName(wday
).c_str(),
4024 wxDateTime::GetMonthName(month
).c_str(),
4031 // the array data was generated by the following python program
4033 from DateTime import *
4034 from whrandom import *
4035 from string import *
4037 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4038 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4040 week = DateTimeDelta(7)
4043 year = randint(1900, 2100)
4044 month = randint(1, 12)
4045 day = randint(1, 28)
4046 dt = DateTime(year, month, day)
4047 wday = dt.day_of_week
4049 countFromEnd = choice([-1, 1])
4052 while dt.month is month:
4053 dt = dt - countFromEnd * week
4054 weekNum = weekNum + countFromEnd
4056 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
4058 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
4059 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
4062 static const WeekDateTestData weekDatesTestData
[] =
4064 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
4065 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
4066 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
4067 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
4068 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
4069 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
4070 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
4071 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
4072 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
4073 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
4074 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
4075 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
4076 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
4077 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
4078 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
4079 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
4080 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
4081 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
4082 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
4083 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
4086 static const char *fmt
= "%d-%b-%Y";
4089 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
4091 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
4093 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4095 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4097 const Date
& d
= wd
.date
;
4098 if ( d
.SameDay(dt
.GetTm()) )
4104 dt
.Set(d
.day
, d
.month
, d
.year
);
4106 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4111 // test the computation of (ISO) week numbers
4112 static void TestTimeWNumber()
4114 puts("\n*** wxDateTime week number test ***");
4116 struct WeekNumberTestData
4118 Date date
; // the date
4119 wxDateTime::wxDateTime_t week
; // the week number in the year
4120 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4121 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4122 wxDateTime::wxDateTime_t dnum
; // day number in the year
4125 // data generated with the following python script:
4127 from DateTime import *
4128 from whrandom import *
4129 from string import *
4131 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4132 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4134 def GetMonthWeek(dt):
4135 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4136 if weekNumMonth < 0:
4137 weekNumMonth = weekNumMonth + 53
4140 def GetLastSundayBefore(dt):
4141 if dt.iso_week[2] == 7:
4144 return dt - DateTimeDelta(dt.iso_week[2])
4147 year = randint(1900, 2100)
4148 month = randint(1, 12)
4149 day = randint(1, 28)
4150 dt = DateTime(year, month, day)
4151 dayNum = dt.day_of_year
4152 weekNum = dt.iso_week[1]
4153 weekNumMonth = GetMonthWeek(dt)
4156 dtSunday = GetLastSundayBefore(dt)
4158 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4159 weekNumMonth2 = weekNumMonth2 + 1
4160 dtSunday = dtSunday - DateTimeDelta(7)
4162 data = { 'day': rjust(`day`, 2), \
4163 'month': monthNames[month - 1], \
4165 'weekNum': rjust(`weekNum`, 2), \
4166 'weekNumMonth': weekNumMonth, \
4167 'weekNumMonth2': weekNumMonth2, \
4168 'dayNum': rjust(`dayNum`, 3) }
4170 print " { { %(day)s, "\
4171 "wxDateTime::%(month)s, "\
4174 "%(weekNumMonth)s, "\
4175 "%(weekNumMonth2)s, "\
4176 "%(dayNum)s }," % data
4179 static const WeekNumberTestData weekNumberTestDates
[] =
4181 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4182 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4183 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4184 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4185 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4186 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4187 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4188 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4189 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4190 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4191 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4192 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4193 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4194 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4195 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4196 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4197 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4198 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4199 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4200 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4203 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4205 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4206 const Date
& d
= wn
.date
;
4208 wxDateTime dt
= d
.DT();
4210 wxDateTime::wxDateTime_t
4211 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4212 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4213 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4214 dnum
= dt
.GetDayOfYear();
4216 printf("%s: the day number is %d",
4217 d
.FormatDate().c_str(), dnum
);
4218 if ( dnum
== wn
.dnum
)
4224 printf(" (ERROR: should be %d)", wn
.dnum
);
4227 printf(", week in month is %d", wmon
);
4228 if ( wmon
== wn
.wmon
)
4234 printf(" (ERROR: should be %d)", wn
.wmon
);
4237 printf(" or %d", wmon2
);
4238 if ( wmon2
== wn
.wmon2
)
4244 printf(" (ERROR: should be %d)", wn
.wmon2
);
4247 printf(", week in year is %d", week
);
4248 if ( week
== wn
.week
)
4254 printf(" (ERROR: should be %d)\n", wn
.week
);
4259 // test DST calculations
4260 static void TestTimeDST()
4262 puts("\n*** wxDateTime DST test ***");
4264 printf("DST is%s in effect now.\n\n",
4265 wxDateTime::Now().IsDST() ? "" : " not");
4267 // taken from http://www.energy.ca.gov/daylightsaving.html
4268 static const Date datesDST
[2][2004 - 1900 + 1] =
4271 { 1, wxDateTime::Apr
, 1990 },
4272 { 7, wxDateTime::Apr
, 1991 },
4273 { 5, wxDateTime::Apr
, 1992 },
4274 { 4, wxDateTime::Apr
, 1993 },
4275 { 3, wxDateTime::Apr
, 1994 },
4276 { 2, wxDateTime::Apr
, 1995 },
4277 { 7, wxDateTime::Apr
, 1996 },
4278 { 6, wxDateTime::Apr
, 1997 },
4279 { 5, wxDateTime::Apr
, 1998 },
4280 { 4, wxDateTime::Apr
, 1999 },
4281 { 2, wxDateTime::Apr
, 2000 },
4282 { 1, wxDateTime::Apr
, 2001 },
4283 { 7, wxDateTime::Apr
, 2002 },
4284 { 6, wxDateTime::Apr
, 2003 },
4285 { 4, wxDateTime::Apr
, 2004 },
4288 { 28, wxDateTime::Oct
, 1990 },
4289 { 27, wxDateTime::Oct
, 1991 },
4290 { 25, wxDateTime::Oct
, 1992 },
4291 { 31, wxDateTime::Oct
, 1993 },
4292 { 30, wxDateTime::Oct
, 1994 },
4293 { 29, wxDateTime::Oct
, 1995 },
4294 { 27, wxDateTime::Oct
, 1996 },
4295 { 26, wxDateTime::Oct
, 1997 },
4296 { 25, wxDateTime::Oct
, 1998 },
4297 { 31, wxDateTime::Oct
, 1999 },
4298 { 29, wxDateTime::Oct
, 2000 },
4299 { 28, wxDateTime::Oct
, 2001 },
4300 { 27, wxDateTime::Oct
, 2002 },
4301 { 26, wxDateTime::Oct
, 2003 },
4302 { 31, wxDateTime::Oct
, 2004 },
4307 for ( year
= 1990; year
< 2005; year
++ )
4309 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4310 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4312 printf("DST period in the US for year %d: from %s to %s",
4313 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4315 size_t n
= year
- 1990;
4316 const Date
& dBegin
= datesDST
[0][n
];
4317 const Date
& dEnd
= datesDST
[1][n
];
4319 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4325 printf(" (ERROR: should be %s %d to %s %d)\n",
4326 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4327 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4333 for ( year
= 1990; year
< 2005; year
++ )
4335 printf("DST period in Europe for year %d: from %s to %s\n",
4337 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4338 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4342 // test wxDateTime -> text conversion
4343 static void TestTimeFormat()
4345 puts("\n*** wxDateTime formatting test ***");
4347 // some information may be lost during conversion, so store what kind
4348 // of info should we recover after a round trip
4351 CompareNone
, // don't try comparing
4352 CompareBoth
, // dates and times should be identical
4353 CompareDate
, // dates only
4354 CompareTime
// time only
4359 CompareKind compareKind
;
4361 } formatTestFormats
[] =
4363 { CompareBoth
, "---> %c" },
4364 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4365 { CompareBoth
, "Date is %x, time is %X" },
4366 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4367 { CompareNone
, "The day of year: %j, the week of year: %W" },
4368 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4371 static const Date formatTestDates
[] =
4373 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4374 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4376 // this test can't work for other centuries because it uses two digit
4377 // years in formats, so don't even try it
4378 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4379 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4380 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4384 // an extra test (as it doesn't depend on date, don't do it in the loop)
4385 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4387 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4391 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4392 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4394 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4395 printf("%s", s
.c_str());
4397 // what can we recover?
4398 int kind
= formatTestFormats
[n
].compareKind
;
4402 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4405 // converion failed - should it have?
4406 if ( kind
== CompareNone
)
4409 puts(" (ERROR: conversion back failed)");
4413 // should have parsed the entire string
4414 puts(" (ERROR: conversion back stopped too soon)");
4418 bool equal
= FALSE
; // suppress compilaer warning
4426 equal
= dt
.IsSameDate(dt2
);
4430 equal
= dt
.IsSameTime(dt2
);
4436 printf(" (ERROR: got back '%s' instead of '%s')\n",
4437 dt2
.Format().c_str(), dt
.Format().c_str());
4448 // test text -> wxDateTime conversion
4449 static void TestTimeParse()
4451 puts("\n*** wxDateTime parse test ***");
4453 struct ParseTestData
4460 static const ParseTestData parseTestDates
[] =
4462 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4463 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4466 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4468 const char *format
= parseTestDates
[n
].format
;
4470 printf("%s => ", format
);
4473 if ( dt
.ParseRfc822Date(format
) )
4475 printf("%s ", dt
.Format().c_str());
4477 if ( parseTestDates
[n
].good
)
4479 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4486 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4491 puts("(ERROR: bad format)");
4496 printf("bad format (%s)\n",
4497 parseTestDates
[n
].good
? "ERROR" : "ok");
4502 static void TestDateTimeInteractive()
4504 puts("\n*** interactive wxDateTime tests ***");
4510 printf("Enter a date: ");
4511 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4514 // kill the last '\n'
4515 buf
[strlen(buf
) - 1] = 0;
4518 const char *p
= dt
.ParseDate(buf
);
4521 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4527 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4530 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4531 dt
.Format("%b %d, %Y").c_str(),
4533 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4534 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4535 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4538 puts("\n*** done ***");
4541 static void TestTimeMS()
4543 puts("*** testing millisecond-resolution support in wxDateTime ***");
4545 wxDateTime dt1
= wxDateTime::Now(),
4546 dt2
= wxDateTime::UNow();
4548 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4549 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4550 printf("Dummy loop: ");
4551 for ( int i
= 0; i
< 6000; i
++ )
4553 //for ( int j = 0; j < 10; j++ )
4556 s
.Printf("%g", sqrt(i
));
4565 dt2
= wxDateTime::UNow();
4566 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4568 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4570 puts("\n*** done ***");
4573 static void TestTimeArithmetics()
4575 puts("\n*** testing arithmetic operations on wxDateTime ***");
4577 static const struct ArithmData
4579 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4580 : span(sp
), name(nam
) { }
4584 } testArithmData
[] =
4586 ArithmData(wxDateSpan::Day(), "day"),
4587 ArithmData(wxDateSpan::Week(), "week"),
4588 ArithmData(wxDateSpan::Month(), "month"),
4589 ArithmData(wxDateSpan::Year(), "year"),
4590 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4593 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4595 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4597 wxDateSpan span
= testArithmData
[n
].span
;
4601 const char *name
= testArithmData
[n
].name
;
4602 printf("%s + %s = %s, %s - %s = %s\n",
4603 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4604 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4606 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4607 if ( dt1
- span
== dt
)
4613 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4616 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4617 if ( dt2
+ span
== dt
)
4623 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4626 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4627 if ( dt2
+ 2*span
== dt1
)
4633 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4640 static void TestTimeHolidays()
4642 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4644 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4645 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4646 dtEnd
= dtStart
.GetLastMonthDay();
4648 wxDateTimeArray hol
;
4649 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4651 const wxChar
*format
= "%d-%b-%Y (%a)";
4653 printf("All holidays between %s and %s:\n",
4654 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4656 size_t count
= hol
.GetCount();
4657 for ( size_t n
= 0; n
< count
; n
++ )
4659 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4665 static void TestTimeZoneBug()
4667 puts("\n*** testing for DST/timezone bug ***\n");
4669 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4670 for ( int i
= 0; i
< 31; i
++ )
4672 printf("Date %s: week day %s.\n",
4673 date
.Format(_T("%d-%m-%Y")).c_str(),
4674 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4676 date
+= wxDateSpan::Day();
4682 static void TestTimeSpanFormat()
4684 puts("\n*** wxTimeSpan tests ***");
4686 static const char *formats
[] =
4688 _T("(default) %H:%M:%S"),
4689 _T("%E weeks and %D days"),
4690 _T("%l milliseconds"),
4691 _T("(with ms) %H:%M:%S:%l"),
4692 _T("100%% of minutes is %M"), // test "%%"
4693 _T("%D days and %H hours"),
4694 _T("or also %S seconds"),
4697 wxTimeSpan
ts1(1, 2, 3, 4),
4699 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4701 printf("ts1 = %s\tts2 = %s\n",
4702 ts1
.Format(formats
[n
]).c_str(),
4703 ts2
.Format(formats
[n
]).c_str());
4711 // test compatibility with the old wxDate/wxTime classes
4712 static void TestTimeCompatibility()
4714 puts("\n*** wxDateTime compatibility test ***");
4716 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4717 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4719 double jdnNow
= wxDateTime::Now().GetJDN();
4720 long jdnMidnight
= (long)(jdnNow
- 0.5);
4721 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4723 jdnMidnight
= wxDate().Set().GetJulianDate();
4724 printf("wxDateTime for today: %s\n",
4725 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4727 int flags
= wxEUROPEAN
;//wxFULL;
4730 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4731 for ( int n
= 0; n
< 7; n
++ )
4733 printf("Previous %s is %s\n",
4734 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4735 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4741 #endif // TEST_DATETIME
4743 // ----------------------------------------------------------------------------
4745 // ----------------------------------------------------------------------------
4749 #include "wx/thread.h"
4751 static size_t gs_counter
= (size_t)-1;
4752 static wxCriticalSection gs_critsect
;
4753 static wxSemaphore gs_cond
;
4755 class MyJoinableThread
: public wxThread
4758 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4759 { m_n
= n
; Create(); }
4761 // thread execution starts here
4762 virtual ExitCode
Entry();
4768 wxThread::ExitCode
MyJoinableThread::Entry()
4770 unsigned long res
= 1;
4771 for ( size_t n
= 1; n
< m_n
; n
++ )
4775 // it's a loooong calculation :-)
4779 return (ExitCode
)res
;
4782 class MyDetachedThread
: public wxThread
4785 MyDetachedThread(size_t n
, char ch
)
4789 m_cancelled
= FALSE
;
4794 // thread execution starts here
4795 virtual ExitCode
Entry();
4798 virtual void OnExit();
4801 size_t m_n
; // number of characters to write
4802 char m_ch
; // character to write
4804 bool m_cancelled
; // FALSE if we exit normally
4807 wxThread::ExitCode
MyDetachedThread::Entry()
4810 wxCriticalSectionLocker
lock(gs_critsect
);
4811 if ( gs_counter
== (size_t)-1 )
4817 for ( size_t n
= 0; n
< m_n
; n
++ )
4819 if ( TestDestroy() )
4829 wxThread::Sleep(100);
4835 void MyDetachedThread::OnExit()
4837 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4839 wxCriticalSectionLocker
lock(gs_critsect
);
4840 if ( !--gs_counter
&& !m_cancelled
)
4844 static void TestDetachedThreads()
4846 puts("\n*** Testing detached threads ***");
4848 static const size_t nThreads
= 3;
4849 MyDetachedThread
*threads
[nThreads
];
4851 for ( n
= 0; n
< nThreads
; n
++ )
4853 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4856 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4857 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4859 for ( n
= 0; n
< nThreads
; n
++ )
4864 // wait until all threads terminate
4870 static void TestJoinableThreads()
4872 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4874 // calc 10! in the background
4875 MyJoinableThread
thread(10);
4878 printf("\nThread terminated with exit code %lu.\n",
4879 (unsigned long)thread
.Wait());
4882 static void TestThreadSuspend()
4884 puts("\n*** Testing thread suspend/resume functions ***");
4886 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4890 // this is for this demo only, in a real life program we'd use another
4891 // condition variable which would be signaled from wxThread::Entry() to
4892 // tell us that the thread really started running - but here just wait a
4893 // bit and hope that it will be enough (the problem is, of course, that
4894 // the thread might still not run when we call Pause() which will result
4896 wxThread::Sleep(300);
4898 for ( size_t n
= 0; n
< 3; n
++ )
4902 puts("\nThread suspended");
4905 // don't sleep but resume immediately the first time
4906 wxThread::Sleep(300);
4908 puts("Going to resume the thread");
4913 puts("Waiting until it terminates now");
4915 // wait until the thread terminates
4921 static void TestThreadDelete()
4923 // As above, using Sleep() is only for testing here - we must use some
4924 // synchronisation object instead to ensure that the thread is still
4925 // running when we delete it - deleting a detached thread which already
4926 // terminated will lead to a crash!
4928 puts("\n*** Testing thread delete function ***");
4930 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4934 puts("\nDeleted a thread which didn't start to run yet.");
4936 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4940 wxThread::Sleep(300);
4944 puts("\nDeleted a running thread.");
4946 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4950 wxThread::Sleep(300);
4956 puts("\nDeleted a sleeping thread.");
4958 MyJoinableThread
thread3(20);
4963 puts("\nDeleted a joinable thread.");
4965 MyJoinableThread
thread4(2);
4968 wxThread::Sleep(300);
4972 puts("\nDeleted a joinable thread which already terminated.");
4977 class MyWaitingThread
: public wxThread
4980 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4983 m_condition
= condition
;
4988 virtual ExitCode
Entry()
4990 printf("Thread %lu has started running.\n", GetId());
4995 printf("Thread %lu starts to wait...\n", GetId());
4999 m_condition
->Wait();
5002 printf("Thread %lu finished to wait, exiting.\n", GetId());
5010 wxCondition
*m_condition
;
5013 static void TestThreadConditions()
5016 wxCondition
condition(mutex
);
5018 // otherwise its difficult to understand which log messages pertain to
5020 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
5021 // condition.GetId(), gs_cond.GetId());
5023 // create and launch threads
5024 MyWaitingThread
*threads
[10];
5027 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5029 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
5032 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
5037 // wait until all threads run
5038 puts("Main thread is waiting for the other threads to start");
5041 size_t nRunning
= 0;
5042 while ( nRunning
< WXSIZEOF(threads
) )
5048 printf("Main thread: %u already running\n", nRunning
);
5052 puts("Main thread: all threads started up.");
5055 wxThread::Sleep(500);
5058 // now wake one of them up
5059 printf("Main thread: about to signal the condition.\n");
5064 wxThread::Sleep(200);
5066 // wake all the (remaining) threads up, so that they can exit
5067 printf("Main thread: about to broadcast the condition.\n");
5069 condition
.Broadcast();
5071 // give them time to terminate (dirty!)
5072 wxThread::Sleep(500);
5075 #include "wx/utils.h"
5077 class MyExecThread
: public wxThread
5080 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
5086 virtual ExitCode
Entry()
5088 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5095 static void TestThreadExec()
5097 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5099 MyExecThread
thread(_T("true"));
5102 wxPrintf(_T("Main program exit code: %ld.\n"),
5103 wxExecute(_T("false"), wxEXEC_SYNC
));
5105 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5109 #include "wx/datetime.h"
5111 class MySemaphoreThread
: public wxThread
5114 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5115 : wxThread(wxTHREAD_JOINABLE
),
5122 virtual ExitCode
Entry()
5124 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
5125 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5129 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
5130 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5134 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
5135 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
5147 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5149 static void TestSemaphore()
5151 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5153 static const int SEM_LIMIT
= 3;
5155 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5156 ArrayThreads threads
;
5158 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5160 threads
.Add(new MySemaphoreThread(i
, &sem
));
5161 threads
.Last()->Run();
5164 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5171 #endif // TEST_THREADS
5173 // ----------------------------------------------------------------------------
5175 // ----------------------------------------------------------------------------
5179 #include "wx/dynarray.h"
5181 typedef unsigned short ushort
;
5183 #define DefineCompare(name, T) \
5185 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5187 return first - second; \
5190 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5192 return *first - *second; \
5195 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5197 return *second - *first; \
5200 DefineCompare(UShort, ushort);
5201 DefineCompare(Int
, int);
5203 // test compilation of all macros
5204 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5205 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5206 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5207 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5209 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5210 #include "wx/arrimpl.cpp"
5211 WX_DEFINE_OBJARRAY(ArrayBars
);
5213 static void PrintArray(const char* name
, const wxArrayString
& array
)
5215 printf("Dump of the array '%s'\n", name
);
5217 size_t nCount
= array
.GetCount();
5218 for ( size_t n
= 0; n
< nCount
; n
++ )
5220 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5224 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5225 const wxString
& second
)
5227 return first
.length() - second
.length();
5230 #define TestArrayOf(name) \
5232 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5234 printf("Dump of the array '%s'\n", name); \
5236 size_t nCount = array.GetCount(); \
5237 for ( size_t n = 0; n < nCount; n++ ) \
5239 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5243 static void PrintArray(const char* name, const wxArray##name & array) \
5245 printf("Dump of the array '%s'\n", name); \
5247 size_t nCount = array.GetCount(); \
5248 for ( size_t n = 0; n < nCount; n++ ) \
5250 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5254 static void TestArrayOf ## name ## s() \
5256 printf("*** Testing wxArray%s ***\n", #name); \
5264 puts("Initially:"); \
5265 PrintArray("a", a); \
5267 puts("After sort:"); \
5268 a.Sort(name ## Compare); \
5269 PrintArray("a", a); \
5271 puts("After reverse sort:"); \
5272 a.Sort(name ## RevCompare); \
5273 PrintArray("a", a); \
5275 wxSortedArray##name b; \
5281 puts("Sorted array initially:"); \
5282 PrintArray("b", b); \
5285 TestArrayOf(UShort
);
5288 static void TestArrayOfObjects()
5290 puts("*** Testing wxObjArray ***\n");
5294 Bar
bar("second bar (two copies!)");
5296 printf("Initially: %u objects in the array, %u objects total.\n",
5297 bars
.GetCount(), Bar::GetNumber());
5299 bars
.Add(new Bar("first bar"));
5302 printf("Now: %u objects in the array, %u objects total.\n",
5303 bars
.GetCount(), Bar::GetNumber());
5305 bars
.RemoveAt(1, bars
.GetCount() - 1);
5307 printf("After removing all but first element: %u objects in the "
5308 "array, %u objects total.\n",
5309 bars
.GetCount(), Bar::GetNumber());
5313 printf("After Empty(): %u objects in the array, %u objects total.\n",
5314 bars
.GetCount(), Bar::GetNumber());
5317 printf("Finally: no more objects in the array, %u objects total.\n",
5321 #endif // TEST_ARRAYS
5323 // ----------------------------------------------------------------------------
5325 // ----------------------------------------------------------------------------
5329 #include "wx/timer.h"
5330 #include "wx/tokenzr.h"
5332 static void TestStringConstruction()
5334 puts("*** Testing wxString constructores ***");
5336 #define TEST_CTOR(args, res) \
5339 printf("wxString%s = %s ", #args, s.c_str()); \
5346 printf("(ERROR: should be %s)\n", res); \
5350 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5351 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5352 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5353 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5355 static const wxChar
*s
= _T("?really!");
5356 const wxChar
*start
= wxStrchr(s
, _T('r'));
5357 const wxChar
*end
= wxStrchr(s
, _T('!'));
5358 TEST_CTOR((start
, end
), _T("really"));
5363 static void TestString()
5373 for (int i
= 0; i
< 1000000; ++i
)
5377 c
= "! How'ya doin'?";
5380 c
= "Hello world! What's up?";
5385 printf ("TestString elapsed time: %ld\n", sw
.Time());
5388 static void TestPChar()
5396 for (int i
= 0; i
< 1000000; ++i
)
5398 strcpy (a
, "Hello");
5399 strcpy (b
, " world");
5400 strcpy (c
, "! How'ya doin'?");
5403 strcpy (c
, "Hello world! What's up?");
5404 if (strcmp (c
, a
) == 0)
5408 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5411 static void TestStringSub()
5413 wxString
s("Hello, world!");
5415 puts("*** Testing wxString substring extraction ***");
5417 printf("String = '%s'\n", s
.c_str());
5418 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5419 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5420 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5421 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5422 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5423 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5425 static const wxChar
*prefixes
[] =
5429 _T("Hello, world!"),
5430 _T("Hello, world!!!"),
5436 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5438 wxString prefix
= prefixes
[n
], rest
;
5439 bool rc
= s
.StartsWith(prefix
, &rest
);
5440 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5443 printf(" (the rest is '%s')\n", rest
.c_str());
5454 static void TestStringFormat()
5456 puts("*** Testing wxString formatting ***");
5459 s
.Printf("%03d", 18);
5461 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5462 printf("Number 18: %s\n", s
.c_str());
5467 // returns "not found" for npos, value for all others
5468 static wxString
PosToString(size_t res
)
5470 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5471 : wxString::Format(_T("%u"), res
);
5475 static void TestStringFind()
5477 puts("*** Testing wxString find() functions ***");
5479 static const wxChar
*strToFind
= _T("ell");
5480 static const struct StringFindTest
5484 result
; // of searching "ell" in str
5487 { _T("Well, hello world"), 0, 1 },
5488 { _T("Well, hello world"), 6, 7 },
5489 { _T("Well, hello world"), 9, wxString::npos
},
5492 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5494 const StringFindTest
& ft
= findTestData
[n
];
5495 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5497 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5498 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5500 size_t resTrue
= ft
.result
;
5501 if ( res
== resTrue
)
5507 printf(_T("(ERROR: should be %s)\n"),
5508 PosToString(resTrue
).c_str());
5515 static void TestStringTokenizer()
5517 puts("*** Testing wxStringTokenizer ***");
5519 static const wxChar
*modeNames
[] =
5523 _T("return all empty"),
5528 static const struct StringTokenizerTest
5530 const wxChar
*str
; // string to tokenize
5531 const wxChar
*delims
; // delimiters to use
5532 size_t count
; // count of token
5533 wxStringTokenizerMode mode
; // how should we tokenize it
5534 } tokenizerTestData
[] =
5536 { _T(""), _T(" "), 0 },
5537 { _T("Hello, world"), _T(" "), 2 },
5538 { _T("Hello, world "), _T(" "), 2 },
5539 { _T("Hello, world"), _T(","), 2 },
5540 { _T("Hello, world!"), _T(",!"), 2 },
5541 { _T("Hello,, world!"), _T(",!"), 3 },
5542 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5543 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5544 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5545 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5546 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5547 { _T("01/02/99"), _T("/-"), 3 },
5548 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5551 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5553 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5554 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5556 size_t count
= tkz
.CountTokens();
5557 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5558 MakePrintable(tt
.str
).c_str(),
5560 MakePrintable(tt
.delims
).c_str(),
5561 modeNames
[tkz
.GetMode()]);
5562 if ( count
== tt
.count
)
5568 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5573 // if we emulate strtok(), check that we do it correctly
5574 wxChar
*buf
, *s
= NULL
, *last
;
5576 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5578 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5579 wxStrcpy(buf
, tt
.str
);
5581 s
= wxStrtok(buf
, tt
.delims
, &last
);
5588 // now show the tokens themselves
5590 while ( tkz
.HasMoreTokens() )
5592 wxString token
= tkz
.GetNextToken();
5594 printf(_T("\ttoken %u: '%s'"),
5596 MakePrintable(token
).c_str());
5606 printf(" (ERROR: should be %s)\n", s
);
5609 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5613 // nothing to compare with
5618 if ( count2
!= count
)
5620 puts(_T("\tERROR: token count mismatch"));
5629 static void TestStringReplace()
5631 puts("*** Testing wxString::replace ***");
5633 static const struct StringReplaceTestData
5635 const wxChar
*original
; // original test string
5636 size_t start
, len
; // the part to replace
5637 const wxChar
*replacement
; // the replacement string
5638 const wxChar
*result
; // and the expected result
5639 } stringReplaceTestData
[] =
5641 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5642 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5643 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5644 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5645 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5648 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5650 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5652 wxString original
= data
.original
;
5653 original
.replace(data
.start
, data
.len
, data
.replacement
);
5655 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5656 data
.original
, data
.start
, data
.len
, data
.replacement
,
5659 if ( original
== data
.result
)
5665 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5672 static void TestStringMatch()
5674 wxPuts(_T("*** Testing wxString::Matches() ***"));
5676 static const struct StringMatchTestData
5679 const wxChar
*wildcard
;
5681 } stringMatchTestData
[] =
5683 { _T("foobar"), _T("foo*"), 1 },
5684 { _T("foobar"), _T("*oo*"), 1 },
5685 { _T("foobar"), _T("*bar"), 1 },
5686 { _T("foobar"), _T("??????"), 1 },
5687 { _T("foobar"), _T("f??b*"), 1 },
5688 { _T("foobar"), _T("f?b*"), 0 },
5689 { _T("foobar"), _T("*goo*"), 0 },
5690 { _T("foobar"), _T("*foo"), 0 },
5691 { _T("foobarfoo"), _T("*foo"), 1 },
5692 { _T(""), _T("*"), 1 },
5693 { _T(""), _T("?"), 0 },
5696 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5698 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5699 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5700 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5702 matches
? _T("matches") : _T("doesn't match"),
5704 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5710 #endif // TEST_STRINGS
5712 // ----------------------------------------------------------------------------
5714 // ----------------------------------------------------------------------------
5716 #ifdef TEST_SNGLINST
5717 #include "wx/snglinst.h"
5718 #endif // TEST_SNGLINST
5720 int main(int argc
, char **argv
)
5722 wxApp::CheckBuildOptions(wxBuildOptions());
5724 wxInitializer initializer
;
5727 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5732 #ifdef TEST_SNGLINST
5733 wxSingleInstanceChecker checker
;
5734 if ( checker
.Create(_T(".wxconsole.lock")) )
5736 if ( checker
.IsAnotherRunning() )
5738 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5743 // wait some time to give time to launch another instance
5744 wxPrintf(_T("Press \"Enter\" to continue..."));
5747 else // failed to create
5749 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5751 #endif // TEST_SNGLINST
5755 #endif // TEST_CHARSET
5758 TestCmdLineConvert();
5760 #if wxUSE_CMDLINE_PARSER
5761 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5763 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5764 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5765 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5766 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5768 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5769 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5770 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5771 wxCMD_LINE_VAL_NUMBER
},
5772 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5773 wxCMD_LINE_VAL_DATE
},
5775 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5776 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5781 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5783 parser
.AddOption("project_name", "", "full path to project file",
5784 wxCMD_LINE_VAL_STRING
,
5785 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5787 switch ( parser
.Parse() )
5790 wxLogMessage("Help was given, terminating.");
5794 ShowCmdLine(parser
);
5798 wxLogMessage("Syntax error detected, aborting.");
5801 #endif // wxUSE_CMDLINE_PARSER
5803 #endif // TEST_CMDLINE
5811 TestStringConstruction();
5814 TestStringTokenizer();
5815 TestStringReplace();
5821 #endif // TEST_STRINGS
5834 puts("*** Initially:");
5836 PrintArray("a1", a1
);
5838 wxArrayString
a2(a1
);
5839 PrintArray("a2", a2
);
5841 wxSortedArrayString
a3(a1
);
5842 PrintArray("a3", a3
);
5844 puts("*** After deleting three strings from a1");
5847 PrintArray("a1", a1
);
5848 PrintArray("a2", a2
);
5849 PrintArray("a3", a3
);
5851 puts("*** After reassigning a1 to a2 and a3");
5853 PrintArray("a2", a2
);
5854 PrintArray("a3", a3
);
5856 puts("*** After sorting a1");
5858 PrintArray("a1", a1
);
5860 puts("*** After sorting a1 in reverse order");
5862 PrintArray("a1", a1
);
5864 puts("*** After sorting a1 by the string length");
5865 a1
.Sort(StringLenCompare
);
5866 PrintArray("a1", a1
);
5868 TestArrayOfObjects();
5869 TestArrayOfUShorts();
5873 #endif // TEST_ARRAYS
5884 #ifdef TEST_DLLLOADER
5886 #endif // TEST_DLLLOADER
5890 #endif // TEST_ENVIRON
5894 #endif // TEST_EXECUTE
5896 #ifdef TEST_FILECONF
5898 #endif // TEST_FILECONF
5906 #endif // TEST_LOCALE
5910 for ( size_t n
= 0; n
< 8000; n
++ )
5912 s
<< (char)('A' + (n
% 26));
5916 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5918 // this one shouldn't be truncated
5921 // but this one will because log functions use fixed size buffer
5922 // (note that it doesn't need '\n' at the end neither - will be added
5924 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5936 #ifdef TEST_FILENAME
5940 fn
.Assign("c:\\foo", "bar.baz");
5941 fn
.Assign("/u/os9-port/Viewer/tvision/WEI2HZ-3B3-14_05-04-00MSC1.asc");
5946 TestFileNameConstruction();
5949 TestFileNameConstruction();
5950 TestFileNameMakeRelative();
5951 TestFileNameSplit();
5954 TestFileNameComparison();
5955 TestFileNameOperations();
5957 #endif // TEST_FILENAME
5959 #ifdef TEST_FILETIME
5963 #endif // TEST_FILETIME
5966 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5967 if ( TestFtpConnect() )
5978 if ( TEST_INTERACTIVE
)
5979 TestFtpInteractive();
5981 //else: connecting to the FTP server failed
5987 #ifdef TEST_LONGLONG
5988 // seed pseudo random generator
5989 srand((unsigned)time(NULL
));
5998 TestMultiplication();
6001 TestLongLongConversion();
6002 TestBitOperations();
6003 TestLongLongComparison();
6004 TestLongLongPrint();
6006 #endif // TEST_LONGLONG
6014 #endif // TEST_HASHMAP
6017 wxLog::AddTraceMask(_T("mime"));
6022 TestMimeAssociate();
6027 #ifdef TEST_INFO_FUNCTIONS
6033 if ( TEST_INTERACTIVE
)
6036 #endif // TEST_INFO_FUNCTIONS
6038 #ifdef TEST_PATHLIST
6040 #endif // TEST_PATHLIST
6048 #endif // TEST_REGCONF
6051 // TODO: write a real test using src/regex/tests file
6056 TestRegExSubmatch();
6057 TestRegExReplacement();
6059 if ( TEST_INTERACTIVE
)
6060 TestRegExInteractive();
6062 #endif // TEST_REGEX
6064 #ifdef TEST_REGISTRY
6066 TestRegistryAssociation();
6067 #endif // TEST_REGISTRY
6072 #endif // TEST_SOCKETS
6080 #endif // TEST_STREAMS
6083 int nCPUs
= wxThread::GetCPUCount();
6084 printf("This system has %d CPUs\n", nCPUs
);
6086 wxThread::SetConcurrency(nCPUs
);
6090 TestDetachedThreads();
6091 TestJoinableThreads();
6092 TestThreadSuspend();
6094 TestThreadConditions();
6099 #endif // TEST_THREADS
6103 #endif // TEST_TIMER
6105 #ifdef TEST_DATETIME
6118 TestTimeArithmetics();
6121 TestTimeSpanFormat();
6127 if ( TEST_INTERACTIVE
)
6128 TestDateTimeInteractive();
6129 #endif // TEST_DATETIME
6132 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6134 #endif // TEST_USLEEP
6139 #endif // TEST_VCARD
6143 #endif // TEST_VOLUME
6146 TestUnicodeToFromAscii();
6147 #endif // TEST_UNICODE
6151 TestEncodingConverter();
6152 #endif // TEST_WCHAR
6155 TestZipStreamRead();
6156 TestZipFileSystem();
6160 TestZlibStreamWrite();
6161 TestZlibStreamRead();