1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
23 #error "This sample can't be compiled in GUI mode."
28 #include "wx/string.h"
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
43 A note about all these conditional compilation macros: this file is used
44 both as a test suite for various non-GUI wxWindows classes and as a
45 scratchpad for quick tests. So there are two compilation modes: if you
46 define TEST_ALL all tests are run, otherwise you may enable the individual
47 tests individually in the "#else" branch below.
50 // what to test (in alphabetic order)? uncomment the line below to do all tests
58 #define TEST_DLLLOADER
68 #define TEST_INFO_FUNCTIONS
85 // #define TEST_VCARD -- don't enable this (VZ)
92 static const bool TEST_ALL
= TRUE
;
96 static const bool TEST_ALL
= FALSE
;
99 // some tests are interactive, define this to run them
100 #ifdef TEST_INTERACTIVE
101 #undef TEST_INTERACTIVE
103 static const bool TEST_INTERACTIVE
= TRUE
;
105 static const bool TEST_INTERACTIVE
= FALSE
;
108 // ----------------------------------------------------------------------------
109 // test class for container objects
110 // ----------------------------------------------------------------------------
112 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
114 class Bar
// Foo is already taken in the hash test
117 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
118 ~Bar() { ms_bars
--; }
120 static size_t GetNumber() { return ms_bars
; }
122 const char *GetName() const { return m_name
; }
127 static size_t ms_bars
;
130 size_t Bar::ms_bars
= 0;
132 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
134 // ============================================================================
136 // ============================================================================
138 // ----------------------------------------------------------------------------
140 // ----------------------------------------------------------------------------
142 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
144 // replace TABs with \t and CRs with \n
145 static wxString
MakePrintable(const wxChar
*s
)
148 (void)str
.Replace(_T("\t"), _T("\\t"));
149 (void)str
.Replace(_T("\n"), _T("\\n"));
150 (void)str
.Replace(_T("\r"), _T("\\r"));
155 #endif // MakePrintable() is used
157 // ----------------------------------------------------------------------------
158 // wxFontMapper::CharsetToEncoding
159 // ----------------------------------------------------------------------------
163 #include "wx/fontmap.h"
165 static void TestCharset()
167 static const wxChar
*charsets
[] =
169 // some vali charsets
178 // and now some bogus ones
185 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
187 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(charsets
[n
]);
188 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
190 wxFontMapper::Get()->GetEncodingName(enc
).c_str(),
191 wxFontMapper::Get()->GetEncodingDescription(enc
).c_str());
195 #endif // TEST_CHARSET
197 // ----------------------------------------------------------------------------
199 // ----------------------------------------------------------------------------
203 #include "wx/cmdline.h"
204 #include "wx/datetime.h"
206 #if wxUSE_CMDLINE_PARSER
208 static void ShowCmdLine(const wxCmdLineParser
& parser
)
210 wxString s
= "Input files: ";
212 size_t count
= parser
.GetParamCount();
213 for ( size_t param
= 0; param
< count
; param
++ )
215 s
<< parser
.GetParam(param
) << ' ';
219 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
220 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
225 if ( parser
.Found("o", &strVal
) )
226 s
<< "Output file:\t" << strVal
<< '\n';
227 if ( parser
.Found("i", &strVal
) )
228 s
<< "Input dir:\t" << strVal
<< '\n';
229 if ( parser
.Found("s", &lVal
) )
230 s
<< "Size:\t" << lVal
<< '\n';
231 if ( parser
.Found("d", &dt
) )
232 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
233 if ( parser
.Found("project_name", &strVal
) )
234 s
<< "Project:\t" << strVal
<< '\n';
239 #endif // wxUSE_CMDLINE_PARSER
241 static void TestCmdLineConvert()
243 static const char *cmdlines
[] =
246 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
247 "literal \\\" and \"\"",
250 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
252 const char *cmdline
= cmdlines
[n
];
253 printf("Parsing: %s\n", cmdline
);
254 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
256 size_t count
= args
.GetCount();
257 printf("\targc = %u\n", count
);
258 for ( size_t arg
= 0; arg
< count
; arg
++ )
260 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
265 #endif // TEST_CMDLINE
267 // ----------------------------------------------------------------------------
269 // ----------------------------------------------------------------------------
276 static const wxChar
*ROOTDIR
= _T("/");
277 static const wxChar
*TESTDIR
= _T("/usr");
278 #elif defined(__WXMSW__)
279 static const wxChar
*ROOTDIR
= _T("c:\\");
280 static const wxChar
*TESTDIR
= _T("d:\\");
282 #error "don't know where the root directory is"
285 static void TestDirEnumHelper(wxDir
& dir
,
286 int flags
= wxDIR_DEFAULT
,
287 const wxString
& filespec
= wxEmptyString
)
291 if ( !dir
.IsOpened() )
294 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
297 printf("\t%s\n", filename
.c_str());
299 cont
= dir
.GetNext(&filename
);
305 static void TestDirEnum()
307 puts("*** Testing wxDir::GetFirst/GetNext ***");
309 wxDir
dir(wxGetCwd());
311 puts("Enumerating everything in current directory:");
312 TestDirEnumHelper(dir
);
314 puts("Enumerating really everything in current directory:");
315 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
317 puts("Enumerating object files in current directory:");
318 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
320 puts("Enumerating directories in current directory:");
321 TestDirEnumHelper(dir
, wxDIR_DIRS
);
323 puts("Enumerating files in current directory:");
324 TestDirEnumHelper(dir
, wxDIR_FILES
);
326 puts("Enumerating files including hidden in current directory:");
327 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
331 puts("Enumerating everything in root directory:");
332 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
334 puts("Enumerating directories in root directory:");
335 TestDirEnumHelper(dir
, wxDIR_DIRS
);
337 puts("Enumerating files in root directory:");
338 TestDirEnumHelper(dir
, wxDIR_FILES
);
340 puts("Enumerating files including hidden in root directory:");
341 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
343 puts("Enumerating files in non existing directory:");
344 wxDir
dirNo("nosuchdir");
345 TestDirEnumHelper(dirNo
);
348 class DirPrintTraverser
: public wxDirTraverser
351 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
353 return wxDIR_CONTINUE
;
356 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
358 wxString path
, name
, ext
;
359 wxSplitPath(dirname
, &path
, &name
, &ext
);
362 name
<< _T('.') << ext
;
365 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
367 if ( wxIsPathSeparator(*p
) )
371 printf("%s%s\n", indent
.c_str(), name
.c_str());
373 return wxDIR_CONTINUE
;
377 static void TestDirTraverse()
379 puts("*** Testing wxDir::Traverse() ***");
383 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
384 printf("There are %u files under '%s'\n", n
, TESTDIR
);
387 printf("First one is '%s'\n", files
[0u].c_str());
388 printf(" last one is '%s'\n", files
[n
- 1].c_str());
391 // enum again with custom traverser
393 DirPrintTraverser traverser
;
394 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
399 // ----------------------------------------------------------------------------
401 // ----------------------------------------------------------------------------
403 #ifdef TEST_DLLLOADER
405 #include "wx/dynlib.h"
407 static void TestDllLoad()
409 #if defined(__WXMSW__)
410 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
411 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
412 #elif defined(__UNIX__)
413 // weird: using just libc.so does *not* work!
414 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
415 static const wxChar
*FUNC_NAME
= _T("strlen");
417 #error "don't know how to test wxDllLoader on this platform"
420 puts("*** testing wxDllLoader ***\n");
422 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
425 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
429 typedef int (*strlenType
)(const char *);
430 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
433 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
434 FUNC_NAME
, LIB_NAME
);
438 if ( pfnStrlen("foo") != 3 )
440 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
448 wxDllLoader::UnloadLibrary(dllHandle
);
452 #endif // TEST_DLLLOADER
454 // ----------------------------------------------------------------------------
456 // ----------------------------------------------------------------------------
460 #include "wx/utils.h"
462 static wxString
MyGetEnv(const wxString
& var
)
465 if ( !wxGetEnv(var
, &val
) )
468 val
= wxString(_T('\'')) + val
+ _T('\'');
473 static void TestEnvironment()
475 const wxChar
*var
= _T("wxTestVar");
477 puts("*** testing environment access functions ***");
479 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
480 wxSetEnv(var
, _T("value for wxTestVar"));
481 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
482 wxSetEnv(var
, _T("another value"));
483 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
485 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
486 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
489 #endif // TEST_ENVIRON
491 // ----------------------------------------------------------------------------
493 // ----------------------------------------------------------------------------
497 #include "wx/utils.h"
499 static void TestExecute()
501 puts("*** testing wxExecute ***");
504 #define COMMAND "cat -n ../../Makefile" // "echo hi"
505 #define SHELL_COMMAND "echo hi from shell"
506 #define REDIRECT_COMMAND COMMAND // "date"
507 #elif defined(__WXMSW__)
508 #define COMMAND "command.com -c 'echo hi'"
509 #define SHELL_COMMAND "echo hi"
510 #define REDIRECT_COMMAND COMMAND
512 #error "no command to exec"
515 printf("Testing wxShell: ");
517 if ( wxShell(SHELL_COMMAND
) )
522 printf("Testing wxExecute: ");
524 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
529 #if 0 // no, it doesn't work (yet?)
530 printf("Testing async wxExecute: ");
532 if ( wxExecute(COMMAND
) != 0 )
533 puts("Ok (command launched).");
538 printf("Testing wxExecute with redirection:\n");
539 wxArrayString output
;
540 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
546 size_t count
= output
.GetCount();
547 for ( size_t n
= 0; n
< count
; n
++ )
549 printf("\t%s\n", output
[n
].c_str());
556 #endif // TEST_EXECUTE
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
565 #include "wx/ffile.h"
566 #include "wx/textfile.h"
568 static void TestFileRead()
570 puts("*** wxFile read test ***");
572 wxFile
file(_T("testdata.fc"));
573 if ( file
.IsOpened() )
575 printf("File length: %lu\n", file
.Length());
577 puts("File dump:\n----------");
579 static const off_t len
= 1024;
583 off_t nRead
= file
.Read(buf
, len
);
584 if ( nRead
== wxInvalidOffset
)
586 printf("Failed to read the file.");
590 fwrite(buf
, nRead
, 1, stdout
);
600 printf("ERROR: can't open test file.\n");
606 static void TestTextFileRead()
608 puts("*** wxTextFile read test ***");
610 wxTextFile
file(_T("testdata.fc"));
613 printf("Number of lines: %u\n", file
.GetLineCount());
614 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
618 puts("\nDumping the entire file:");
619 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
621 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
623 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
625 puts("\nAnd now backwards:");
626 for ( s
= file
.GetLastLine();
627 file
.GetCurrentLine() != 0;
628 s
= file
.GetPrevLine() )
630 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
632 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
636 printf("ERROR: can't open '%s'\n", file
.GetName());
642 static void TestFileCopy()
644 puts("*** Testing wxCopyFile ***");
646 static const wxChar
*filename1
= _T("testdata.fc");
647 static const wxChar
*filename2
= _T("test2");
648 if ( !wxCopyFile(filename1
, filename2
) )
650 puts("ERROR: failed to copy file");
654 wxFFile
f1(filename1
, "rb"),
657 if ( !f1
.IsOpened() || !f2
.IsOpened() )
659 puts("ERROR: failed to open file(s)");
664 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
666 puts("ERROR: failed to read file(s)");
670 if ( (s1
.length() != s2
.length()) ||
671 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
673 puts("ERROR: copy error!");
677 puts("File was copied ok.");
683 if ( !wxRemoveFile(filename2
) )
685 puts("ERROR: failed to remove the file");
693 // ----------------------------------------------------------------------------
695 // ----------------------------------------------------------------------------
699 #include "wx/confbase.h"
700 #include "wx/fileconf.h"
702 static const struct FileConfTestData
704 const wxChar
*name
; // value name
705 const wxChar
*value
; // the value from the file
708 { _T("value1"), _T("one") },
709 { _T("value2"), _T("two") },
710 { _T("novalue"), _T("default") },
713 static void TestFileConfRead()
715 puts("*** testing wxFileConfig loading/reading ***");
717 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
718 _T("testdata.fc"), wxEmptyString
,
719 wxCONFIG_USE_RELATIVE_PATH
);
721 // test simple reading
722 puts("\nReading config file:");
723 wxString
defValue(_T("default")), value
;
724 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
726 const FileConfTestData
& data
= fcTestData
[n
];
727 value
= fileconf
.Read(data
.name
, defValue
);
728 printf("\t%s = %s ", data
.name
, value
.c_str());
729 if ( value
== data
.value
)
735 printf("(ERROR: should be %s)\n", data
.value
);
739 // test enumerating the entries
740 puts("\nEnumerating all root entries:");
743 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
746 printf("\t%s = %s\n",
748 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
750 cont
= fileconf
.GetNextEntry(name
, dummy
);
754 #endif // TEST_FILECONF
756 // ----------------------------------------------------------------------------
758 // ----------------------------------------------------------------------------
762 #include "wx/filename.h"
764 static void DumpFileName(const wxFileName
& fn
)
766 wxString full
= fn
.GetFullPath();
768 wxString vol
, path
, name
, ext
;
769 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
771 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
772 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
774 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
775 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
776 path
.c_str(), name
.c_str(), ext
.c_str());
778 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
779 wxPrintf(_T("with volume: \t'%s'\n"),
780 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
781 wxPrintf(_T("with separator:\t'%s'\n"),
782 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
783 wxPrintf(_T("with both: \t'%s'\n"),
784 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
787 static struct FileNameInfo
789 const wxChar
*fullname
;
790 const wxChar
*volume
;
799 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
800 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
801 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
802 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
803 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
804 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
805 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
806 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
807 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
809 // Windows file names
810 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
811 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
812 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
813 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
814 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
815 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
817 // wxFileName support for Mac file names is broken currently
820 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
821 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
822 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
823 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
824 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
825 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
829 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
830 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
833 static void TestFileNameConstruction()
835 puts("*** testing wxFileName construction ***");
837 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
839 const FileNameInfo
& fni
= filenames
[n
];
841 wxFileName
fn(fni
.fullname
, fni
.format
);
843 wxString fullname
= fn
.GetFullPath(fni
.format
);
844 if ( fullname
!= fni
.fullname
)
846 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
849 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
850 printf("'%s' is %s (%s)\n\t",
852 isAbsolute
? "absolute" : "relative",
853 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
855 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
857 puts("ERROR (couldn't be normalized)");
861 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
868 static void TestFileNameSplit()
870 puts("*** testing wxFileName splitting ***");
872 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
874 const FileNameInfo
& fni
= filenames
[n
];
875 wxString volume
, path
, name
, ext
;
876 wxFileName::SplitPath(fni
.fullname
,
877 &volume
, &path
, &name
, &ext
, fni
.format
);
879 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
881 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
883 if ( volume
!= fni
.volume
)
884 printf(" (ERROR: volume = '%s')", fni
.volume
);
885 if ( path
!= fni
.path
)
886 printf(" (ERROR: path = '%s')", fni
.path
);
887 if ( name
!= fni
.name
)
888 printf(" (ERROR: name = '%s')", fni
.name
);
889 if ( ext
!= fni
.ext
)
890 printf(" (ERROR: ext = '%s')", fni
.ext
);
896 static void TestFileNameTemp()
898 puts("*** testing wxFileName temp file creation ***");
900 static const char *tmpprefixes
[] =
908 "/tmp/foo/bar", // this one must be an error
912 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
914 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
917 // "error" is not in upper case because it may be ok
918 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
922 printf("Prefix '%s'\t-> temp file '%s'\n",
923 tmpprefixes
[n
], path
.c_str());
925 if ( !wxRemoveFile(path
) )
927 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
933 static void TestFileNameMakeRelative()
935 puts("*** testing wxFileName::MakeRelativeTo() ***");
937 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
939 const FileNameInfo
& fni
= filenames
[n
];
941 wxFileName
fn(fni
.fullname
, fni
.format
);
943 // choose the base dir of the same format
945 switch ( fni
.format
)
957 // TODO: I don't know how this is supposed to work there
960 case wxPATH_NATIVE
: // make gcc happy
962 wxFAIL_MSG( "unexpected path format" );
965 printf("'%s' relative to '%s': ",
966 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
968 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
974 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
979 static void TestFileNameComparison()
984 static void TestFileNameOperations()
989 static void TestFileNameCwd()
994 #endif // TEST_FILENAME
996 // ----------------------------------------------------------------------------
997 // wxFileName time functions
998 // ----------------------------------------------------------------------------
1000 #ifdef TEST_FILETIME
1002 #include <wx/filename.h>
1003 #include <wx/datetime.h>
1005 static void TestFileGetTimes()
1007 wxFileName
fn(_T("testdata.fc"));
1009 wxDateTime dtAccess
, dtMod
, dtCreate
;
1010 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1012 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1016 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1018 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1019 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1020 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1021 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1025 static void TestFileSetTimes()
1027 wxFileName
fn(_T("testdata.fc"));
1031 wxPrintf(_T("ERROR: Touch() failed.\n"));
1035 #endif // TEST_FILETIME
1037 // ----------------------------------------------------------------------------
1039 // ----------------------------------------------------------------------------
1043 #include "wx/hash.h"
1047 Foo(int n_
) { n
= n_
; count
++; }
1052 static size_t count
;
1055 size_t Foo::count
= 0;
1057 WX_DECLARE_LIST(Foo
, wxListFoos
);
1058 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1060 #include "wx/listimpl.cpp"
1062 WX_DEFINE_LIST(wxListFoos
);
1064 static void TestHash()
1066 puts("*** Testing wxHashTable ***\n");
1070 hash
.DeleteContents(TRUE
);
1072 printf("Hash created: %u foos in hash, %u foos totally\n",
1073 hash
.GetCount(), Foo::count
);
1075 static const int hashTestData
[] =
1077 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1081 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1083 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1086 printf("Hash filled: %u foos in hash, %u foos totally\n",
1087 hash
.GetCount(), Foo::count
);
1089 puts("Hash access test:");
1090 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1092 printf("\tGetting element with key %d, value %d: ",
1093 hashTestData
[n
], n
);
1094 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1097 printf("ERROR, not found.\n");
1101 printf("%d (%s)\n", foo
->n
,
1102 (size_t)foo
->n
== n
? "ok" : "ERROR");
1106 printf("\nTrying to get an element not in hash: ");
1108 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1110 puts("ERROR: found!");
1114 puts("ok (not found)");
1118 printf("Hash destroyed: %u foos left\n", Foo::count
);
1123 // ----------------------------------------------------------------------------
1125 // ----------------------------------------------------------------------------
1129 #include "wx/hashmap.h"
1131 // test compilation of basic map types
1132 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1133 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1134 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1135 myUnsignedHashMap
);
1136 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1138 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1140 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1142 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1146 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1147 // myStringHashMap );
1148 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1150 typedef myStringHashMap::iterator Itor
;
1152 static void TestHashMap()
1154 puts("*** Testing wxHashMap ***\n");
1155 myStringHashMap
sh(0); // as small as possible
1158 const size_t count
= 10000;
1160 // init with some data
1161 for( i
= 0; i
< count
; ++i
)
1163 buf
.Printf(wxT("%d"), i
);
1164 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1167 // test that insertion worked
1168 if( sh
.size() != count
)
1170 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1173 for( i
= 0; i
< count
; ++i
)
1175 buf
.Printf(wxT("%d"), i
);
1176 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1178 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1183 // check that iterators work
1185 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1189 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1193 if( it
->second
!= sh
[it
->first
] )
1195 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1200 if( sh
.size() != i
)
1202 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1205 // test copy ctor, assignment operator
1206 myStringHashMap
h1( sh
), h2( 0 );
1209 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1211 if( h1
[it
->first
] != it
->second
)
1213 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1216 if( h2
[it
->first
] != it
->second
)
1218 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1223 for( i
= 0; i
< count
; ++i
)
1225 buf
.Printf(wxT("%d"), i
);
1226 size_t sz
= sh
.size();
1228 // test find() and erase(it)
1231 it
= sh
.find( buf
);
1232 if( it
!= sh
.end() )
1236 if( sh
.find( buf
) != sh
.end() )
1238 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1242 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1247 size_t c
= sh
.erase( buf
);
1249 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1251 if( sh
.find( buf
) != sh
.end() )
1253 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1257 // count should decrease
1258 if( sh
.size() != sz
- 1 )
1260 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1264 printf("*** Finished testing wxHashMap ***\n");
1267 #endif // TEST_HASHMAP
1269 // ----------------------------------------------------------------------------
1271 // ----------------------------------------------------------------------------
1275 #include "wx/list.h"
1277 WX_DECLARE_LIST(Bar
, wxListBars
);
1278 #include "wx/listimpl.cpp"
1279 WX_DEFINE_LIST(wxListBars
);
1281 static void TestListCtor()
1283 puts("*** Testing wxList construction ***\n");
1287 list1
.Append(new Bar(_T("first")));
1288 list1
.Append(new Bar(_T("second")));
1290 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1291 list1
.GetCount(), Bar::GetNumber());
1296 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1297 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1299 list1
.DeleteContents(TRUE
);
1302 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1307 // ----------------------------------------------------------------------------
1309 // ----------------------------------------------------------------------------
1313 #include "wx/intl.h"
1314 #include "wx/utils.h" // for wxSetEnv
1316 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1318 // find the name of the language from its value
1319 static const char *GetLangName(int lang
)
1321 static const char *languageNames
[] =
1342 "ARABIC_SAUDI_ARABIA",
1367 "CHINESE_SIMPLIFIED",
1368 "CHINESE_TRADITIONAL",
1371 "CHINESE_SINGAPORE",
1382 "ENGLISH_AUSTRALIA",
1386 "ENGLISH_CARIBBEAN",
1390 "ENGLISH_NEW_ZEALAND",
1391 "ENGLISH_PHILIPPINES",
1392 "ENGLISH_SOUTH_AFRICA",
1404 "FRENCH_LUXEMBOURG",
1413 "GERMAN_LIECHTENSTEIN",
1414 "GERMAN_LUXEMBOURG",
1455 "MALAY_BRUNEI_DARUSSALAM",
1467 "NORWEGIAN_NYNORSK",
1474 "PORTUGUESE_BRAZILIAN",
1499 "SPANISH_ARGENTINA",
1503 "SPANISH_COSTA_RICA",
1504 "SPANISH_DOMINICAN_REPUBLIC",
1506 "SPANISH_EL_SALVADOR",
1507 "SPANISH_GUATEMALA",
1511 "SPANISH_NICARAGUA",
1515 "SPANISH_PUERTO_RICO",
1518 "SPANISH_VENEZUELA",
1555 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1556 return languageNames
[lang
];
1561 static void TestDefaultLang()
1563 puts("*** Testing wxLocale::GetSystemLanguage ***");
1565 static const wxChar
*langStrings
[] =
1567 NULL
, // system default
1574 _T("de_DE.iso88591"),
1576 _T("?"), // invalid lang spec
1577 _T("klingonese"), // I bet on some systems it does exist...
1580 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1581 wxLocale::GetSystemEncodingName().c_str(),
1582 wxLocale::GetSystemEncoding());
1584 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1586 const char *langStr
= langStrings
[n
];
1589 // FIXME: this doesn't do anything at all under Windows, we need
1590 // to create a new wxLocale!
1591 wxSetEnv(_T("LC_ALL"), langStr
);
1594 int lang
= gs_localeDefault
.GetSystemLanguage();
1595 printf("Locale for '%s' is %s.\n",
1596 langStr
? langStr
: "system default", GetLangName(lang
));
1600 #endif // TEST_LOCALE
1602 // ----------------------------------------------------------------------------
1604 // ----------------------------------------------------------------------------
1608 #include "wx/mimetype.h"
1610 static void TestMimeEnum()
1612 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1614 wxArrayString mimetypes
;
1616 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1618 printf("*** All %u known filetypes: ***\n", count
);
1623 for ( size_t n
= 0; n
< count
; n
++ )
1625 wxFileType
*filetype
=
1626 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1629 printf("nothing known about the filetype '%s'!\n",
1630 mimetypes
[n
].c_str());
1634 filetype
->GetDescription(&desc
);
1635 filetype
->GetExtensions(exts
);
1637 filetype
->GetIcon(NULL
);
1640 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1643 extsAll
<< _T(", ");
1647 printf("\t%s: %s (%s)\n",
1648 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1654 static void TestMimeOverride()
1656 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1658 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1659 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1661 if ( wxFile::Exists(mailcap
) )
1662 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1664 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1666 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1669 if ( wxFile::Exists(mimetypes
) )
1670 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1672 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1674 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1680 static void TestMimeFilename()
1682 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1684 static const wxChar
*filenames
[] =
1691 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1693 const wxString fname
= filenames
[n
];
1694 wxString ext
= fname
.AfterLast(_T('.'));
1695 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1698 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1703 if ( !ft
->GetDescription(&desc
) )
1704 desc
= _T("<no description>");
1707 if ( !ft
->GetOpenCommand(&cmd
,
1708 wxFileType::MessageParameters(fname
, _T(""))) )
1709 cmd
= _T("<no command available>");
1711 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1712 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1721 static void TestMimeAssociate()
1723 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1725 wxFileTypeInfo
ftInfo(
1726 _T("application/x-xyz"),
1727 _T("xyzview '%s'"), // open cmd
1728 _T(""), // print cmd
1729 _T("XYZ File"), // description
1730 _T(".xyz"), // extensions
1731 NULL
// end of extensions
1733 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1735 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1738 wxPuts(_T("ERROR: failed to create association!"));
1742 // TODO: read it back
1751 // ----------------------------------------------------------------------------
1752 // misc information functions
1753 // ----------------------------------------------------------------------------
1755 #ifdef TEST_INFO_FUNCTIONS
1757 #include "wx/utils.h"
1759 static void TestDiskInfo()
1761 puts("*** Testing wxGetDiskSpace() ***");
1766 printf("\nEnter a directory name: ");
1767 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1770 // kill the last '\n'
1771 pathname
[strlen(pathname
) - 1] = 0;
1773 wxLongLong total
, free
;
1774 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1776 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1780 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1781 (total
/ 1024).ToString().c_str(),
1782 (free
/ 1024).ToString().c_str(),
1788 static void TestOsInfo()
1790 puts("*** Testing OS info functions ***\n");
1793 wxGetOsVersion(&major
, &minor
);
1794 printf("Running under: %s, version %d.%d\n",
1795 wxGetOsDescription().c_str(), major
, minor
);
1797 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1799 printf("Host name is %s (%s).\n",
1800 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1805 static void TestUserInfo()
1807 puts("*** Testing user info functions ***\n");
1809 printf("User id is:\t%s\n", wxGetUserId().c_str());
1810 printf("User name is:\t%s\n", wxGetUserName().c_str());
1811 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1812 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1817 #endif // TEST_INFO_FUNCTIONS
1819 // ----------------------------------------------------------------------------
1821 // ----------------------------------------------------------------------------
1823 #ifdef TEST_LONGLONG
1825 #include "wx/longlong.h"
1826 #include "wx/timer.h"
1828 // make a 64 bit number from 4 16 bit ones
1829 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1831 // get a random 64 bit number
1832 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1834 static const long testLongs
[] =
1845 #if wxUSE_LONGLONG_WX
1846 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1847 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1848 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1849 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1850 #endif // wxUSE_LONGLONG_WX
1852 static void TestSpeed()
1854 static const long max
= 100000000;
1861 for ( n
= 0; n
< max
; n
++ )
1866 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1869 #if wxUSE_LONGLONG_NATIVE
1874 for ( n
= 0; n
< max
; n
++ )
1879 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1881 #endif // wxUSE_LONGLONG_NATIVE
1887 for ( n
= 0; n
< max
; n
++ )
1892 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1896 static void TestLongLongConversion()
1898 puts("*** Testing wxLongLong conversions ***\n");
1902 for ( size_t n
= 0; n
< 100000; n
++ )
1906 #if wxUSE_LONGLONG_NATIVE
1907 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1909 wxASSERT_MSG( a
== b
, "conversions failure" );
1911 puts("Can't do it without native long long type, test skipped.");
1914 #endif // wxUSE_LONGLONG_NATIVE
1916 if ( !(nTested
% 1000) )
1928 static void TestMultiplication()
1930 puts("*** Testing wxLongLong multiplication ***\n");
1934 for ( size_t n
= 0; n
< 100000; n
++ )
1939 #if wxUSE_LONGLONG_NATIVE
1940 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1941 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1943 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1944 #else // !wxUSE_LONGLONG_NATIVE
1945 puts("Can't do it without native long long type, test skipped.");
1948 #endif // wxUSE_LONGLONG_NATIVE
1950 if ( !(nTested
% 1000) )
1962 static void TestDivision()
1964 puts("*** Testing wxLongLong division ***\n");
1968 for ( size_t n
= 0; n
< 100000; n
++ )
1970 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1971 // multiplication will not overflow)
1972 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1974 // get a random (but non null) long (not wxLongLong for now) to divide
1986 #if wxUSE_LONGLONG_NATIVE
1987 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1989 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1990 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1991 #else // !wxUSE_LONGLONG_NATIVE
1992 // verify the result
1993 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1994 #endif // wxUSE_LONGLONG_NATIVE
1996 if ( !(nTested
% 1000) )
2008 static void TestAddition()
2010 puts("*** Testing wxLongLong addition ***\n");
2014 for ( size_t n
= 0; n
< 100000; n
++ )
2020 #if wxUSE_LONGLONG_NATIVE
2021 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2022 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2023 "addition failure" );
2024 #else // !wxUSE_LONGLONG_NATIVE
2025 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2026 #endif // wxUSE_LONGLONG_NATIVE
2028 if ( !(nTested
% 1000) )
2040 static void TestBitOperations()
2042 puts("*** Testing wxLongLong bit operation ***\n");
2046 for ( size_t n
= 0; n
< 100000; n
++ )
2050 #if wxUSE_LONGLONG_NATIVE
2051 for ( size_t n
= 0; n
< 33; n
++ )
2054 #else // !wxUSE_LONGLONG_NATIVE
2055 puts("Can't do it without native long long type, test skipped.");
2058 #endif // wxUSE_LONGLONG_NATIVE
2060 if ( !(nTested
% 1000) )
2072 static void TestLongLongComparison()
2074 #if wxUSE_LONGLONG_WX
2075 puts("*** Testing wxLongLong comparison ***\n");
2077 static const long ls
[2] =
2083 wxLongLongWx lls
[2];
2087 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2091 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2093 res
= lls
[m
] > testLongs
[n
];
2094 printf("0x%lx > 0x%lx is %s (%s)\n",
2095 ls
[m
], testLongs
[n
], res
? "true" : "false",
2096 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2098 res
= lls
[m
] < testLongs
[n
];
2099 printf("0x%lx < 0x%lx is %s (%s)\n",
2100 ls
[m
], testLongs
[n
], res
? "true" : "false",
2101 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2103 res
= lls
[m
] == testLongs
[n
];
2104 printf("0x%lx == 0x%lx is %s (%s)\n",
2105 ls
[m
], testLongs
[n
], res
? "true" : "false",
2106 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2109 #endif // wxUSE_LONGLONG_WX
2112 static void TestLongLongPrint()
2114 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2116 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2118 wxLongLong ll
= testLongs
[n
];
2119 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2122 wxLongLong
ll(0x12345678, 0x87654321);
2123 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2126 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2132 #endif // TEST_LONGLONG
2134 // ----------------------------------------------------------------------------
2136 // ----------------------------------------------------------------------------
2138 #ifdef TEST_PATHLIST
2140 static void TestPathList()
2142 puts("*** Testing wxPathList ***\n");
2144 wxPathList pathlist
;
2145 pathlist
.AddEnvList("PATH");
2146 wxString path
= pathlist
.FindValidPath("ls");
2149 printf("ERROR: command not found in the path.\n");
2153 printf("Command found in the path as '%s'.\n", path
.c_str());
2157 #endif // TEST_PATHLIST
2159 // ----------------------------------------------------------------------------
2160 // regular expressions
2161 // ----------------------------------------------------------------------------
2165 #include "wx/regex.h"
2167 static void TestRegExCompile()
2169 wxPuts(_T("*** Testing RE compilation ***\n"));
2171 static struct RegExCompTestData
2173 const wxChar
*pattern
;
2175 } regExCompTestData
[] =
2177 { _T("foo"), TRUE
},
2178 { _T("foo("), FALSE
},
2179 { _T("foo(bar"), FALSE
},
2180 { _T("foo(bar)"), TRUE
},
2181 { _T("foo["), FALSE
},
2182 { _T("foo[bar"), FALSE
},
2183 { _T("foo[bar]"), TRUE
},
2184 { _T("foo{"), TRUE
},
2185 { _T("foo{1"), FALSE
},
2186 { _T("foo{bar"), TRUE
},
2187 { _T("foo{1}"), TRUE
},
2188 { _T("foo{1,2}"), TRUE
},
2189 { _T("foo{bar}"), TRUE
},
2190 { _T("foo*"), TRUE
},
2191 { _T("foo**"), FALSE
},
2192 { _T("foo+"), TRUE
},
2193 { _T("foo++"), FALSE
},
2194 { _T("foo?"), TRUE
},
2195 { _T("foo??"), FALSE
},
2196 { _T("foo?+"), FALSE
},
2200 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2202 const RegExCompTestData
& data
= regExCompTestData
[n
];
2203 bool ok
= re
.Compile(data
.pattern
);
2205 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2207 ok
? _T("") : _T("not "),
2208 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2212 static void TestRegExMatch()
2214 wxPuts(_T("*** Testing RE matching ***\n"));
2216 static struct RegExMatchTestData
2218 const wxChar
*pattern
;
2221 } regExMatchTestData
[] =
2223 { _T("foo"), _T("bar"), FALSE
},
2224 { _T("foo"), _T("foobar"), TRUE
},
2225 { _T("^foo"), _T("foobar"), TRUE
},
2226 { _T("^foo"), _T("barfoo"), FALSE
},
2227 { _T("bar$"), _T("barbar"), TRUE
},
2228 { _T("bar$"), _T("barbar "), FALSE
},
2231 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2233 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2235 wxRegEx
re(data
.pattern
);
2236 bool ok
= re
.Matches(data
.text
);
2238 wxPrintf(_T("'%s' %s %s (%s)\n"),
2240 ok
? _T("matches") : _T("doesn't match"),
2242 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2246 static void TestRegExSubmatch()
2248 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2250 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2251 if ( !re
.IsValid() )
2253 wxPuts(_T("ERROR: compilation failed."));
2257 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2259 if ( !re
.Matches(text
) )
2261 wxPuts(_T("ERROR: match expected."));
2265 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2267 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2268 re
.GetMatch(text
, 3).c_str(),
2269 re
.GetMatch(text
, 2).c_str(),
2270 re
.GetMatch(text
, 4).c_str(),
2271 re
.GetMatch(text
, 1).c_str());
2275 static void TestRegExReplacement()
2277 wxPuts(_T("*** Testing RE replacement ***"));
2279 static struct RegExReplTestData
2283 const wxChar
*result
;
2285 } regExReplTestData
[] =
2287 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2288 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2289 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2290 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2291 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2292 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2293 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2296 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2297 wxRegEx
re(pattern
);
2299 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2301 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2303 const RegExReplTestData
& data
= regExReplTestData
[n
];
2305 wxString text
= data
.text
;
2306 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2308 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2309 data
.text
, data
.repl
,
2310 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2312 if ( text
== data
.result
&& nRepl
== data
.count
)
2318 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2319 data
.count
, data
.result
);
2324 static void TestRegExInteractive()
2326 wxPuts(_T("*** Testing RE interactively ***"));
2331 printf("\nEnter a pattern: ");
2332 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2335 // kill the last '\n'
2336 pattern
[strlen(pattern
) - 1] = 0;
2339 if ( !re
.Compile(pattern
) )
2347 printf("Enter text to match: ");
2348 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2351 // kill the last '\n'
2352 text
[strlen(text
) - 1] = 0;
2354 if ( !re
.Matches(text
) )
2356 printf("No match.\n");
2360 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2363 for ( size_t n
= 1; ; n
++ )
2365 if ( !re
.GetMatch(&start
, &len
, n
) )
2370 printf("Subexpr %u matched '%s'\n",
2371 n
, wxString(text
+ start
, len
).c_str());
2378 #endif // TEST_REGEX
2380 // ----------------------------------------------------------------------------
2382 // ----------------------------------------------------------------------------
2388 static void TestDbOpen()
2396 // ----------------------------------------------------------------------------
2397 // registry and related stuff
2398 // ----------------------------------------------------------------------------
2400 // this is for MSW only
2403 #undef TEST_REGISTRY
2408 #include "wx/confbase.h"
2409 #include "wx/msw/regconf.h"
2411 static void TestRegConfWrite()
2413 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2414 regconf
.Write(_T("Hello"), wxString(_T("world")));
2417 #endif // TEST_REGCONF
2419 #ifdef TEST_REGISTRY
2421 #include "wx/msw/registry.h"
2423 // I chose this one because I liked its name, but it probably only exists under
2425 static const wxChar
*TESTKEY
=
2426 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2428 static void TestRegistryRead()
2430 puts("*** testing registry reading ***");
2432 wxRegKey
key(TESTKEY
);
2433 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2436 puts("ERROR: test key can't be opened, aborting test.");
2441 size_t nSubKeys
, nValues
;
2442 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2444 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2447 printf("Enumerating values:\n");
2451 bool cont
= key
.GetFirstValue(value
, dummy
);
2454 printf("Value '%s': type ", value
.c_str());
2455 switch ( key
.GetValueType(value
) )
2457 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2458 case wxRegKey::Type_String
: printf("SZ"); break;
2459 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2460 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2461 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2462 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2463 default: printf("other (unknown)"); break;
2466 printf(", value = ");
2467 if ( key
.IsNumericValue(value
) )
2470 key
.QueryValue(value
, &val
);
2476 key
.QueryValue(value
, val
);
2477 printf("'%s'", val
.c_str());
2479 key
.QueryRawValue(value
, val
);
2480 printf(" (raw value '%s')", val
.c_str());
2485 cont
= key
.GetNextValue(value
, dummy
);
2489 static void TestRegistryAssociation()
2492 The second call to deleteself genertaes an error message, with a
2493 messagebox saying .flo is crucial to system operation, while the .ddf
2494 call also fails, but with no error message
2499 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2501 key
= "ddxf_auto_file" ;
2502 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2504 key
= "ddxf_auto_file" ;
2505 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2508 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2510 key
= "program \"%1\"" ;
2512 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2514 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2516 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2518 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2522 #endif // TEST_REGISTRY
2524 // ----------------------------------------------------------------------------
2526 // ----------------------------------------------------------------------------
2530 #include "wx/socket.h"
2531 #include "wx/protocol/protocol.h"
2532 #include "wx/protocol/http.h"
2534 static void TestSocketServer()
2536 puts("*** Testing wxSocketServer ***\n");
2538 static const int PORT
= 3000;
2543 wxSocketServer
*server
= new wxSocketServer(addr
);
2544 if ( !server
->Ok() )
2546 puts("ERROR: failed to bind");
2553 printf("Server: waiting for connection on port %d...\n", PORT
);
2555 wxSocketBase
*socket
= server
->Accept();
2558 puts("ERROR: wxSocketServer::Accept() failed.");
2562 puts("Server: got a client.");
2564 server
->SetTimeout(60); // 1 min
2566 while ( socket
->IsConnected() )
2572 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2574 // don't log error if the client just close the connection
2575 if ( socket
->IsConnected() )
2577 puts("ERROR: in wxSocket::Read.");
2597 printf("Server: got '%s'.\n", s
.c_str());
2598 if ( s
== _T("bye") )
2605 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2606 socket
->Write("\r\n", 2);
2607 printf("Server: wrote '%s'.\n", s
.c_str());
2610 puts("Server: lost a client.");
2615 // same as "delete server" but is consistent with GUI programs
2619 static void TestSocketClient()
2621 puts("*** Testing wxSocketClient ***\n");
2623 static const char *hostname
= "www.wxwindows.org";
2626 addr
.Hostname(hostname
);
2629 printf("--- Attempting to connect to %s:80...\n", hostname
);
2631 wxSocketClient client
;
2632 if ( !client
.Connect(addr
) )
2634 printf("ERROR: failed to connect to %s\n", hostname
);
2638 printf("--- Connected to %s:%u...\n",
2639 addr
.Hostname().c_str(), addr
.Service());
2643 // could use simply "GET" here I suppose
2645 wxString::Format("GET http://%s/\r\n", hostname
);
2646 client
.Write(cmdGet
, cmdGet
.length());
2647 printf("--- Sent command '%s' to the server\n",
2648 MakePrintable(cmdGet
).c_str());
2649 client
.Read(buf
, WXSIZEOF(buf
));
2650 printf("--- Server replied:\n%s", buf
);
2654 #endif // TEST_SOCKETS
2656 // ----------------------------------------------------------------------------
2658 // ----------------------------------------------------------------------------
2662 #include "wx/protocol/ftp.h"
2666 #define FTP_ANONYMOUS
2668 #ifdef FTP_ANONYMOUS
2669 static const char *directory
= "/pub";
2670 static const char *filename
= "welcome.msg";
2672 static const char *directory
= "/etc";
2673 static const char *filename
= "issue";
2676 static bool TestFtpConnect()
2678 puts("*** Testing FTP connect ***");
2680 #ifdef FTP_ANONYMOUS
2681 static const char *hostname
= "ftp.wxwindows.org";
2683 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2684 #else // !FTP_ANONYMOUS
2685 static const char *hostname
= "localhost";
2688 fgets(user
, WXSIZEOF(user
), stdin
);
2689 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2693 printf("Password for %s: ", password
);
2694 fgets(password
, WXSIZEOF(password
), stdin
);
2695 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2696 ftp
.SetPassword(password
);
2698 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2699 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2701 if ( !ftp
.Connect(hostname
) )
2703 printf("ERROR: failed to connect to %s\n", hostname
);
2709 printf("--- Connected to %s, current directory is '%s'\n",
2710 hostname
, ftp
.Pwd().c_str());
2716 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2717 static void TestFtpWuFtpd()
2720 static const char *hostname
= "ftp.eudora.com";
2721 if ( !ftp
.Connect(hostname
) )
2723 printf("ERROR: failed to connect to %s\n", hostname
);
2727 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2728 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2731 printf("ERROR: couldn't get input stream for %s\n", filename
);
2735 size_t size
= in
->StreamSize();
2736 printf("Reading file %s (%u bytes)...", filename
, size
);
2738 char *data
= new char[size
];
2739 if ( !in
->Read(data
, size
) )
2741 puts("ERROR: read error");
2745 printf("Successfully retrieved the file.\n");
2754 static void TestFtpList()
2756 puts("*** Testing wxFTP file listing ***\n");
2759 if ( !ftp
.ChDir(directory
) )
2761 printf("ERROR: failed to cd to %s\n", directory
);
2764 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2766 // test NLIST and LIST
2767 wxArrayString files
;
2768 if ( !ftp
.GetFilesList(files
) )
2770 puts("ERROR: failed to get NLIST of files");
2774 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2775 size_t count
= files
.GetCount();
2776 for ( size_t n
= 0; n
< count
; n
++ )
2778 printf("\t%s\n", files
[n
].c_str());
2780 puts("End of the file list");
2783 if ( !ftp
.GetDirList(files
) )
2785 puts("ERROR: failed to get LIST of files");
2789 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2790 size_t count
= files
.GetCount();
2791 for ( size_t n
= 0; n
< count
; n
++ )
2793 printf("\t%s\n", files
[n
].c_str());
2795 puts("End of the file list");
2798 if ( !ftp
.ChDir(_T("..")) )
2800 puts("ERROR: failed to cd to ..");
2803 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2806 static void TestFtpDownload()
2808 puts("*** Testing wxFTP download ***\n");
2811 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2814 printf("ERROR: couldn't get input stream for %s\n", filename
);
2818 size_t size
= in
->StreamSize();
2819 printf("Reading file %s (%u bytes)...", filename
, size
);
2822 char *data
= new char[size
];
2823 if ( !in
->Read(data
, size
) )
2825 puts("ERROR: read error");
2829 printf("\nContents of %s:\n%s\n", filename
, data
);
2837 static void TestFtpFileSize()
2839 puts("*** Testing FTP SIZE command ***");
2841 if ( !ftp
.ChDir(directory
) )
2843 printf("ERROR: failed to cd to %s\n", directory
);
2846 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2848 if ( ftp
.FileExists(filename
) )
2850 int size
= ftp
.GetFileSize(filename
);
2852 printf("ERROR: couldn't get size of '%s'\n", filename
);
2854 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2858 printf("ERROR: '%s' doesn't exist\n", filename
);
2862 static void TestFtpMisc()
2864 puts("*** Testing miscellaneous wxFTP functions ***");
2866 if ( ftp
.SendCommand("STAT") != '2' )
2868 puts("ERROR: STAT failed");
2872 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2875 if ( ftp
.SendCommand("HELP SITE") != '2' )
2877 puts("ERROR: HELP SITE failed");
2881 printf("The list of site-specific commands:\n\n%s\n",
2882 ftp
.GetLastResult().c_str());
2886 static void TestFtpInteractive()
2888 puts("\n*** Interactive wxFTP test ***");
2894 printf("Enter FTP command: ");
2895 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2898 // kill the last '\n'
2899 buf
[strlen(buf
) - 1] = 0;
2901 // special handling of LIST and NLST as they require data connection
2902 wxString
start(buf
, 4);
2904 if ( start
== "LIST" || start
== "NLST" )
2907 if ( strlen(buf
) > 4 )
2910 wxArrayString files
;
2911 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2913 printf("ERROR: failed to get %s of files\n", start
.c_str());
2917 printf("--- %s of '%s' under '%s':\n",
2918 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2919 size_t count
= files
.GetCount();
2920 for ( size_t n
= 0; n
< count
; n
++ )
2922 printf("\t%s\n", files
[n
].c_str());
2924 puts("--- End of the file list");
2929 char ch
= ftp
.SendCommand(buf
);
2930 printf("Command %s", ch
? "succeeded" : "failed");
2933 printf(" (return code %c)", ch
);
2936 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2940 puts("\n*** done ***");
2943 static void TestFtpUpload()
2945 puts("*** Testing wxFTP uploading ***\n");
2948 static const char *file1
= "test1";
2949 static const char *file2
= "test2";
2950 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2953 printf("--- Uploading to %s ---\n", file1
);
2954 out
->Write("First hello", 11);
2958 // send a command to check the remote file
2959 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2961 printf("ERROR: STAT %s failed\n", file1
);
2965 printf("STAT %s returned:\n\n%s\n",
2966 file1
, ftp
.GetLastResult().c_str());
2969 out
= ftp
.GetOutputStream(file2
);
2972 printf("--- Uploading to %s ---\n", file1
);
2973 out
->Write("Second hello", 12);
2980 // ----------------------------------------------------------------------------
2982 // ----------------------------------------------------------------------------
2986 #include "wx/wfstream.h"
2987 #include "wx/mstream.h"
2989 static void TestFileStream()
2991 puts("*** Testing wxFileInputStream ***");
2993 static const wxChar
*filename
= _T("testdata.fs");
2995 wxFileOutputStream
fsOut(filename
);
2996 fsOut
.Write("foo", 3);
2999 wxFileInputStream
fsIn(filename
);
3000 printf("File stream size: %u\n", fsIn
.GetSize());
3001 while ( !fsIn
.Eof() )
3003 putchar(fsIn
.GetC());
3006 if ( !wxRemoveFile(filename
) )
3008 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3011 puts("\n*** wxFileInputStream test done ***");
3014 static void TestMemoryStream()
3016 puts("*** Testing wxMemoryInputStream ***");
3019 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3021 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3022 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3023 while ( !memInpStream
.Eof() )
3025 putchar(memInpStream
.GetC());
3028 puts("\n*** wxMemoryInputStream test done ***");
3031 #endif // TEST_STREAMS
3033 // ----------------------------------------------------------------------------
3035 // ----------------------------------------------------------------------------
3039 #include "wx/timer.h"
3040 #include "wx/utils.h"
3042 static void TestStopWatch()
3044 puts("*** Testing wxStopWatch ***\n");
3048 printf("Initially paused, after 2 seconds time is...");
3051 printf("\t%ldms\n", sw
.Time());
3053 printf("Resuming stopwatch and sleeping 3 seconds...");
3057 printf("\telapsed time: %ldms\n", sw
.Time());
3060 printf("Pausing agan and sleeping 2 more seconds...");
3063 printf("\telapsed time: %ldms\n", sw
.Time());
3066 printf("Finally resuming and sleeping 2 more seconds...");
3069 printf("\telapsed time: %ldms\n", sw
.Time());
3072 puts("\nChecking for 'backwards clock' bug...");
3073 for ( size_t n
= 0; n
< 70; n
++ )
3077 for ( size_t m
= 0; m
< 100000; m
++ )
3079 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3081 puts("\ntime is negative - ERROR!");
3092 #endif // TEST_TIMER
3094 // ----------------------------------------------------------------------------
3096 // ----------------------------------------------------------------------------
3100 #include "wx/vcard.h"
3102 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3105 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3109 wxString(_T('\t'), level
).c_str(),
3110 vcObj
->GetName().c_str());
3113 switch ( vcObj
->GetType() )
3115 case wxVCardObject::String
:
3116 case wxVCardObject::UString
:
3119 vcObj
->GetValue(&val
);
3120 value
<< _T('"') << val
<< _T('"');
3124 case wxVCardObject::Int
:
3127 vcObj
->GetValue(&i
);
3128 value
.Printf(_T("%u"), i
);
3132 case wxVCardObject::Long
:
3135 vcObj
->GetValue(&l
);
3136 value
.Printf(_T("%lu"), l
);
3140 case wxVCardObject::None
:
3143 case wxVCardObject::Object
:
3144 value
= _T("<node>");
3148 value
= _T("<unknown value type>");
3152 printf(" = %s", value
.c_str());
3155 DumpVObject(level
+ 1, *vcObj
);
3158 vcObj
= vcard
.GetNextProp(&cookie
);
3162 static void DumpVCardAddresses(const wxVCard
& vcard
)
3164 puts("\nShowing all addresses from vCard:\n");
3168 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3172 int flags
= addr
->GetFlags();
3173 if ( flags
& wxVCardAddress::Domestic
)
3175 flagsStr
<< _T("domestic ");
3177 if ( flags
& wxVCardAddress::Intl
)
3179 flagsStr
<< _T("international ");
3181 if ( flags
& wxVCardAddress::Postal
)
3183 flagsStr
<< _T("postal ");
3185 if ( flags
& wxVCardAddress::Parcel
)
3187 flagsStr
<< _T("parcel ");
3189 if ( flags
& wxVCardAddress::Home
)
3191 flagsStr
<< _T("home ");
3193 if ( flags
& wxVCardAddress::Work
)
3195 flagsStr
<< _T("work ");
3198 printf("Address %u:\n"
3200 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3203 addr
->GetPostOffice().c_str(),
3204 addr
->GetExtAddress().c_str(),
3205 addr
->GetStreet().c_str(),
3206 addr
->GetLocality().c_str(),
3207 addr
->GetRegion().c_str(),
3208 addr
->GetPostalCode().c_str(),
3209 addr
->GetCountry().c_str()
3213 addr
= vcard
.GetNextAddress(&cookie
);
3217 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3219 puts("\nShowing all phone numbers from vCard:\n");
3223 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3227 int flags
= phone
->GetFlags();
3228 if ( flags
& wxVCardPhoneNumber::Voice
)
3230 flagsStr
<< _T("voice ");
3232 if ( flags
& wxVCardPhoneNumber::Fax
)
3234 flagsStr
<< _T("fax ");
3236 if ( flags
& wxVCardPhoneNumber::Cellular
)
3238 flagsStr
<< _T("cellular ");
3240 if ( flags
& wxVCardPhoneNumber::Modem
)
3242 flagsStr
<< _T("modem ");
3244 if ( flags
& wxVCardPhoneNumber::Home
)
3246 flagsStr
<< _T("home ");
3248 if ( flags
& wxVCardPhoneNumber::Work
)
3250 flagsStr
<< _T("work ");
3253 printf("Phone number %u:\n"
3258 phone
->GetNumber().c_str()
3262 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3266 static void TestVCardRead()
3268 puts("*** Testing wxVCard reading ***\n");
3270 wxVCard
vcard(_T("vcard.vcf"));
3271 if ( !vcard
.IsOk() )
3273 puts("ERROR: couldn't load vCard.");
3277 // read individual vCard properties
3278 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3282 vcObj
->GetValue(&value
);
3287 value
= _T("<none>");
3290 printf("Full name retrieved directly: %s\n", value
.c_str());
3293 if ( !vcard
.GetFullName(&value
) )
3295 value
= _T("<none>");
3298 printf("Full name from wxVCard API: %s\n", value
.c_str());
3300 // now show how to deal with multiply occuring properties
3301 DumpVCardAddresses(vcard
);
3302 DumpVCardPhoneNumbers(vcard
);
3304 // and finally show all
3305 puts("\nNow dumping the entire vCard:\n"
3306 "-----------------------------\n");
3308 DumpVObject(0, vcard
);
3312 static void TestVCardWrite()
3314 puts("*** Testing wxVCard writing ***\n");
3317 if ( !vcard
.IsOk() )
3319 puts("ERROR: couldn't create vCard.");
3324 vcard
.SetName("Zeitlin", "Vadim");
3325 vcard
.SetFullName("Vadim Zeitlin");
3326 vcard
.SetOrganization("wxWindows", "R&D");
3328 // just dump the vCard back
3329 puts("Entire vCard follows:\n");
3330 puts(vcard
.Write());
3334 #endif // TEST_VCARD
3336 // ----------------------------------------------------------------------------
3338 // ----------------------------------------------------------------------------
3346 #include "wx/volume.h"
3348 static const wxChar
*volumeKinds
[] =
3354 _T("network volume"),
3358 static void TestFSVolume()
3360 wxPuts(_T("*** Testing wxFSVolume class ***"));
3362 wxArrayString volumes
= wxFSVolume::GetVolumes();
3363 size_t count
= volumes
.GetCount();
3367 wxPuts(_T("ERROR: no mounted volumes?"));
3371 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3373 for ( size_t n
= 0; n
< count
; n
++ )
3375 wxFSVolume
vol(volumes
[n
]);
3378 wxPuts(_T("ERROR: couldn't create volume"));
3382 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3384 vol
.GetDisplayName().c_str(),
3385 vol
.GetName().c_str(),
3386 volumeKinds
[vol
.GetKind()],
3387 vol
.IsWritable() ? _T("rw") : _T("ro"),
3388 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3393 #endif // TEST_VOLUME
3395 // ----------------------------------------------------------------------------
3396 // wide char (Unicode) support
3397 // ----------------------------------------------------------------------------
3401 #include "wx/strconv.h"
3402 #include "wx/fontenc.h"
3403 #include "wx/encconv.h"
3404 #include "wx/buffer.h"
3406 static const char textInUtf8
[] =
3408 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3409 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3410 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3411 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3412 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3413 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3414 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3417 static void TestUtf8()
3419 puts("*** Testing UTF8 support ***\n");
3423 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3425 puts("ERROR: UTF-8 decoding failed.");
3429 wxCSConv
conv(_T("koi8-r"));
3430 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3432 puts("ERROR: conversion to KOI8-R failed.");
3436 printf("The resulting string (in KOI8-R): %s\n", buf
);
3440 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3442 puts("ERROR: conversion to UTF-8 failed.");
3446 printf("The string in UTF-8: %s\n", buf
);
3452 static void TestEncodingConverter()
3454 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3456 // using wxEncodingConverter should give the same result as above
3459 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3461 puts("ERROR: UTF-8 decoding failed.");
3465 wxEncodingConverter ec
;
3466 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3467 ec
.Convert(wbuf
, buf
);
3468 printf("The same string obtained using wxEC: %s\n", buf
);
3474 #endif // TEST_WCHAR
3476 // ----------------------------------------------------------------------------
3478 // ----------------------------------------------------------------------------
3482 #include "wx/filesys.h"
3483 #include "wx/fs_zip.h"
3484 #include "wx/zipstrm.h"
3486 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3488 static void TestZipStreamRead()
3490 puts("*** Testing ZIP reading ***\n");
3492 static const wxChar
*filename
= _T("foo");
3493 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3494 printf("Archive size: %u\n", istr
.GetSize());
3496 printf("Dumping the file '%s':\n", filename
);
3497 while ( !istr
.Eof() )
3499 putchar(istr
.GetC());
3503 puts("\n----- done ------");
3506 static void DumpZipDirectory(wxFileSystem
& fs
,
3507 const wxString
& dir
,
3508 const wxString
& indent
)
3510 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3511 TESTFILE_ZIP
, dir
.c_str());
3512 wxString wildcard
= prefix
+ _T("/*");
3514 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3515 while ( !dirname
.empty() )
3517 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3519 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3524 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3526 DumpZipDirectory(fs
, dirname
,
3527 indent
+ wxString(_T(' '), 4));
3529 dirname
= fs
.FindNext();
3532 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3533 while ( !filename
.empty() )
3535 if ( !filename
.StartsWith(prefix
, &filename
) )
3537 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3542 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3544 filename
= fs
.FindNext();
3548 static void TestZipFileSystem()
3550 puts("*** Testing ZIP file system ***\n");
3552 wxFileSystem::AddHandler(new wxZipFSHandler
);
3554 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3556 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3561 // ----------------------------------------------------------------------------
3563 // ----------------------------------------------------------------------------
3567 #include "wx/zstream.h"
3568 #include "wx/wfstream.h"
3570 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3571 static const char *TEST_DATA
= "hello and hello again";
3573 static void TestZlibStreamWrite()
3575 puts("*** Testing Zlib stream reading ***\n");
3577 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3578 wxZlibOutputStream
ostr(fileOutStream
, 0);
3579 printf("Compressing the test string... ");
3580 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3583 puts("(ERROR: failed)");
3590 puts("\n----- done ------");
3593 static void TestZlibStreamRead()
3595 puts("*** Testing Zlib stream reading ***\n");
3597 wxFileInputStream
fileInStream(FILENAME_GZ
);
3598 wxZlibInputStream
istr(fileInStream
);
3599 printf("Archive size: %u\n", istr
.GetSize());
3601 puts("Dumping the file:");
3602 while ( !istr
.Eof() )
3604 putchar(istr
.GetC());
3608 puts("\n----- done ------");
3613 // ----------------------------------------------------------------------------
3615 // ----------------------------------------------------------------------------
3617 #ifdef TEST_DATETIME
3621 #include "wx/date.h"
3622 #include "wx/datetime.h"
3627 wxDateTime::wxDateTime_t day
;
3628 wxDateTime::Month month
;
3630 wxDateTime::wxDateTime_t hour
, min
, sec
;
3632 wxDateTime::WeekDay wday
;
3633 time_t gmticks
, ticks
;
3635 void Init(const wxDateTime::Tm
& tm
)
3644 gmticks
= ticks
= -1;
3647 wxDateTime
DT() const
3648 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3650 bool SameDay(const wxDateTime::Tm
& tm
) const
3652 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3655 wxString
Format() const
3658 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3660 wxDateTime::GetMonthName(month
).c_str(),
3662 abs(wxDateTime::ConvertYearToBC(year
)),
3663 year
> 0 ? "AD" : "BC");
3667 wxString
FormatDate() const
3670 s
.Printf("%02d-%s-%4d%s",
3672 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3673 abs(wxDateTime::ConvertYearToBC(year
)),
3674 year
> 0 ? "AD" : "BC");
3679 static const Date testDates
[] =
3681 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3682 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3683 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3684 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3685 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3686 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3687 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3688 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3689 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3690 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3691 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3692 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3693 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3694 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3695 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3698 // this test miscellaneous static wxDateTime functions
3699 static void TestTimeStatic()
3701 puts("\n*** wxDateTime static methods test ***");
3703 // some info about the current date
3704 int year
= wxDateTime::GetCurrentYear();
3705 printf("Current year %d is %sa leap one and has %d days.\n",
3707 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3708 wxDateTime::GetNumberOfDays(year
));
3710 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3711 printf("Current month is '%s' ('%s') and it has %d days\n",
3712 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3713 wxDateTime::GetMonthName(month
).c_str(),
3714 wxDateTime::GetNumberOfDays(month
));
3717 static const size_t nYears
= 5;
3718 static const size_t years
[2][nYears
] =
3720 // first line: the years to test
3721 { 1990, 1976, 2000, 2030, 1984, },
3723 // second line: TRUE if leap, FALSE otherwise
3724 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3727 for ( size_t n
= 0; n
< nYears
; n
++ )
3729 int year
= years
[0][n
];
3730 bool should
= years
[1][n
] != 0,
3731 is
= wxDateTime::IsLeapYear(year
);
3733 printf("Year %d is %sa leap year (%s)\n",
3736 should
== is
? "ok" : "ERROR");
3738 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3742 // test constructing wxDateTime objects
3743 static void TestTimeSet()
3745 puts("\n*** wxDateTime construction test ***");
3747 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3749 const Date
& d1
= testDates
[n
];
3750 wxDateTime dt
= d1
.DT();
3753 d2
.Init(dt
.GetTm());
3755 wxString s1
= d1
.Format(),
3758 printf("Date: %s == %s (%s)\n",
3759 s1
.c_str(), s2
.c_str(),
3760 s1
== s2
? "ok" : "ERROR");
3764 // test time zones stuff
3765 static void TestTimeZones()
3767 puts("\n*** wxDateTime timezone test ***");
3769 wxDateTime now
= wxDateTime::Now();
3771 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3772 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3773 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3774 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3775 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3776 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3778 wxDateTime::Tm tm
= now
.GetTm();
3779 if ( wxDateTime(tm
) != now
)
3781 printf("ERROR: got %s instead of %s\n",
3782 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3786 // test some minimal support for the dates outside the standard range
3787 static void TestTimeRange()
3789 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3791 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3793 printf("Unix epoch:\t%s\n",
3794 wxDateTime(2440587.5).Format(fmt
).c_str());
3795 printf("Feb 29, 0: \t%s\n",
3796 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3797 printf("JDN 0: \t%s\n",
3798 wxDateTime(0.0).Format(fmt
).c_str());
3799 printf("Jan 1, 1AD:\t%s\n",
3800 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3801 printf("May 29, 2099:\t%s\n",
3802 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3805 static void TestTimeTicks()
3807 puts("\n*** wxDateTime ticks test ***");
3809 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3811 const Date
& d
= testDates
[n
];
3812 if ( d
.ticks
== -1 )
3815 wxDateTime dt
= d
.DT();
3816 long ticks
= (dt
.GetValue() / 1000).ToLong();
3817 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3818 if ( ticks
== d
.ticks
)
3824 printf(" (ERROR: should be %ld, delta = %ld)\n",
3825 d
.ticks
, ticks
- d
.ticks
);
3828 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3829 ticks
= (dt
.GetValue() / 1000).ToLong();
3830 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3831 if ( ticks
== d
.gmticks
)
3837 printf(" (ERROR: should be %ld, delta = %ld)\n",
3838 d
.gmticks
, ticks
- d
.gmticks
);
3845 // test conversions to JDN &c
3846 static void TestTimeJDN()
3848 puts("\n*** wxDateTime to JDN test ***");
3850 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3852 const Date
& d
= testDates
[n
];
3853 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3854 double jdn
= dt
.GetJulianDayNumber();
3856 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3863 printf(" (ERROR: should be %f, delta = %f)\n",
3864 d
.jdn
, jdn
- d
.jdn
);
3869 // test week days computation
3870 static void TestTimeWDays()
3872 puts("\n*** wxDateTime weekday test ***");
3874 // test GetWeekDay()
3876 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3878 const Date
& d
= testDates
[n
];
3879 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3881 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3884 wxDateTime::GetWeekDayName(wday
).c_str());
3885 if ( wday
== d
.wday
)
3891 printf(" (ERROR: should be %s)\n",
3892 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3898 // test SetToWeekDay()
3899 struct WeekDateTestData
3901 Date date
; // the real date (precomputed)
3902 int nWeek
; // its week index in the month
3903 wxDateTime::WeekDay wday
; // the weekday
3904 wxDateTime::Month month
; // the month
3905 int year
; // and the year
3907 wxString
Format() const
3910 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3912 case 1: which
= "first"; break;
3913 case 2: which
= "second"; break;
3914 case 3: which
= "third"; break;
3915 case 4: which
= "fourth"; break;
3916 case 5: which
= "fifth"; break;
3918 case -1: which
= "last"; break;
3923 which
+= " from end";
3926 s
.Printf("The %s %s of %s in %d",
3928 wxDateTime::GetWeekDayName(wday
).c_str(),
3929 wxDateTime::GetMonthName(month
).c_str(),
3936 // the array data was generated by the following python program
3938 from DateTime import *
3939 from whrandom import *
3940 from string import *
3942 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3943 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3945 week = DateTimeDelta(7)
3948 year = randint(1900, 2100)
3949 month = randint(1, 12)
3950 day = randint(1, 28)
3951 dt = DateTime(year, month, day)
3952 wday = dt.day_of_week
3954 countFromEnd = choice([-1, 1])
3957 while dt.month is month:
3958 dt = dt - countFromEnd * week
3959 weekNum = weekNum + countFromEnd
3961 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3963 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3964 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3967 static const WeekDateTestData weekDatesTestData
[] =
3969 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3970 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3971 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3972 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3973 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3974 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3975 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3976 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3977 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3978 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3979 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3980 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3981 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3982 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3983 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3984 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3985 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3986 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3987 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3988 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3991 static const char *fmt
= "%d-%b-%Y";
3994 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3996 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3998 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4000 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4002 const Date
& d
= wd
.date
;
4003 if ( d
.SameDay(dt
.GetTm()) )
4009 dt
.Set(d
.day
, d
.month
, d
.year
);
4011 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4016 // test the computation of (ISO) week numbers
4017 static void TestTimeWNumber()
4019 puts("\n*** wxDateTime week number test ***");
4021 struct WeekNumberTestData
4023 Date date
; // the date
4024 wxDateTime::wxDateTime_t week
; // the week number in the year
4025 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4026 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4027 wxDateTime::wxDateTime_t dnum
; // day number in the year
4030 // data generated with the following python script:
4032 from DateTime import *
4033 from whrandom import *
4034 from string import *
4036 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4037 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4039 def GetMonthWeek(dt):
4040 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4041 if weekNumMonth < 0:
4042 weekNumMonth = weekNumMonth + 53
4045 def GetLastSundayBefore(dt):
4046 if dt.iso_week[2] == 7:
4049 return dt - DateTimeDelta(dt.iso_week[2])
4052 year = randint(1900, 2100)
4053 month = randint(1, 12)
4054 day = randint(1, 28)
4055 dt = DateTime(year, month, day)
4056 dayNum = dt.day_of_year
4057 weekNum = dt.iso_week[1]
4058 weekNumMonth = GetMonthWeek(dt)
4061 dtSunday = GetLastSundayBefore(dt)
4063 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4064 weekNumMonth2 = weekNumMonth2 + 1
4065 dtSunday = dtSunday - DateTimeDelta(7)
4067 data = { 'day': rjust(`day`, 2), \
4068 'month': monthNames[month - 1], \
4070 'weekNum': rjust(`weekNum`, 2), \
4071 'weekNumMonth': weekNumMonth, \
4072 'weekNumMonth2': weekNumMonth2, \
4073 'dayNum': rjust(`dayNum`, 3) }
4075 print " { { %(day)s, "\
4076 "wxDateTime::%(month)s, "\
4079 "%(weekNumMonth)s, "\
4080 "%(weekNumMonth2)s, "\
4081 "%(dayNum)s }," % data
4084 static const WeekNumberTestData weekNumberTestDates
[] =
4086 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4087 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4088 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4089 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4090 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4091 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4092 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4093 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4094 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4095 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4096 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4097 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4098 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4099 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4100 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4101 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4102 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4103 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4104 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4105 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4108 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4110 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4111 const Date
& d
= wn
.date
;
4113 wxDateTime dt
= d
.DT();
4115 wxDateTime::wxDateTime_t
4116 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4117 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4118 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4119 dnum
= dt
.GetDayOfYear();
4121 printf("%s: the day number is %d",
4122 d
.FormatDate().c_str(), dnum
);
4123 if ( dnum
== wn
.dnum
)
4129 printf(" (ERROR: should be %d)", wn
.dnum
);
4132 printf(", week in month is %d", wmon
);
4133 if ( wmon
== wn
.wmon
)
4139 printf(" (ERROR: should be %d)", wn
.wmon
);
4142 printf(" or %d", wmon2
);
4143 if ( wmon2
== wn
.wmon2
)
4149 printf(" (ERROR: should be %d)", wn
.wmon2
);
4152 printf(", week in year is %d", week
);
4153 if ( week
== wn
.week
)
4159 printf(" (ERROR: should be %d)\n", wn
.week
);
4164 // test DST calculations
4165 static void TestTimeDST()
4167 puts("\n*** wxDateTime DST test ***");
4169 printf("DST is%s in effect now.\n\n",
4170 wxDateTime::Now().IsDST() ? "" : " not");
4172 // taken from http://www.energy.ca.gov/daylightsaving.html
4173 static const Date datesDST
[2][2004 - 1900 + 1] =
4176 { 1, wxDateTime::Apr
, 1990 },
4177 { 7, wxDateTime::Apr
, 1991 },
4178 { 5, wxDateTime::Apr
, 1992 },
4179 { 4, wxDateTime::Apr
, 1993 },
4180 { 3, wxDateTime::Apr
, 1994 },
4181 { 2, wxDateTime::Apr
, 1995 },
4182 { 7, wxDateTime::Apr
, 1996 },
4183 { 6, wxDateTime::Apr
, 1997 },
4184 { 5, wxDateTime::Apr
, 1998 },
4185 { 4, wxDateTime::Apr
, 1999 },
4186 { 2, wxDateTime::Apr
, 2000 },
4187 { 1, wxDateTime::Apr
, 2001 },
4188 { 7, wxDateTime::Apr
, 2002 },
4189 { 6, wxDateTime::Apr
, 2003 },
4190 { 4, wxDateTime::Apr
, 2004 },
4193 { 28, wxDateTime::Oct
, 1990 },
4194 { 27, wxDateTime::Oct
, 1991 },
4195 { 25, wxDateTime::Oct
, 1992 },
4196 { 31, wxDateTime::Oct
, 1993 },
4197 { 30, wxDateTime::Oct
, 1994 },
4198 { 29, wxDateTime::Oct
, 1995 },
4199 { 27, wxDateTime::Oct
, 1996 },
4200 { 26, wxDateTime::Oct
, 1997 },
4201 { 25, wxDateTime::Oct
, 1998 },
4202 { 31, wxDateTime::Oct
, 1999 },
4203 { 29, wxDateTime::Oct
, 2000 },
4204 { 28, wxDateTime::Oct
, 2001 },
4205 { 27, wxDateTime::Oct
, 2002 },
4206 { 26, wxDateTime::Oct
, 2003 },
4207 { 31, wxDateTime::Oct
, 2004 },
4212 for ( year
= 1990; year
< 2005; year
++ )
4214 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4215 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4217 printf("DST period in the US for year %d: from %s to %s",
4218 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4220 size_t n
= year
- 1990;
4221 const Date
& dBegin
= datesDST
[0][n
];
4222 const Date
& dEnd
= datesDST
[1][n
];
4224 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4230 printf(" (ERROR: should be %s %d to %s %d)\n",
4231 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4232 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4238 for ( year
= 1990; year
< 2005; year
++ )
4240 printf("DST period in Europe for year %d: from %s to %s\n",
4242 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4243 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4247 // test wxDateTime -> text conversion
4248 static void TestTimeFormat()
4250 puts("\n*** wxDateTime formatting test ***");
4252 // some information may be lost during conversion, so store what kind
4253 // of info should we recover after a round trip
4256 CompareNone
, // don't try comparing
4257 CompareBoth
, // dates and times should be identical
4258 CompareDate
, // dates only
4259 CompareTime
// time only
4264 CompareKind compareKind
;
4266 } formatTestFormats
[] =
4268 { CompareBoth
, "---> %c" },
4269 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4270 { CompareBoth
, "Date is %x, time is %X" },
4271 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4272 { CompareNone
, "The day of year: %j, the week of year: %W" },
4273 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4276 static const Date formatTestDates
[] =
4278 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4279 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4281 // this test can't work for other centuries because it uses two digit
4282 // years in formats, so don't even try it
4283 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4284 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4285 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4289 // an extra test (as it doesn't depend on date, don't do it in the loop)
4290 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4292 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4296 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4297 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4299 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4300 printf("%s", s
.c_str());
4302 // what can we recover?
4303 int kind
= formatTestFormats
[n
].compareKind
;
4307 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4310 // converion failed - should it have?
4311 if ( kind
== CompareNone
)
4314 puts(" (ERROR: conversion back failed)");
4318 // should have parsed the entire string
4319 puts(" (ERROR: conversion back stopped too soon)");
4323 bool equal
= FALSE
; // suppress compilaer warning
4331 equal
= dt
.IsSameDate(dt2
);
4335 equal
= dt
.IsSameTime(dt2
);
4341 printf(" (ERROR: got back '%s' instead of '%s')\n",
4342 dt2
.Format().c_str(), dt
.Format().c_str());
4353 // test text -> wxDateTime conversion
4354 static void TestTimeParse()
4356 puts("\n*** wxDateTime parse test ***");
4358 struct ParseTestData
4365 static const ParseTestData parseTestDates
[] =
4367 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4368 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4371 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4373 const char *format
= parseTestDates
[n
].format
;
4375 printf("%s => ", format
);
4378 if ( dt
.ParseRfc822Date(format
) )
4380 printf("%s ", dt
.Format().c_str());
4382 if ( parseTestDates
[n
].good
)
4384 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4391 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4396 puts("(ERROR: bad format)");
4401 printf("bad format (%s)\n",
4402 parseTestDates
[n
].good
? "ERROR" : "ok");
4407 static void TestDateTimeInteractive()
4409 puts("\n*** interactive wxDateTime tests ***");
4415 printf("Enter a date: ");
4416 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4419 // kill the last '\n'
4420 buf
[strlen(buf
) - 1] = 0;
4423 const char *p
= dt
.ParseDate(buf
);
4426 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4432 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4435 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4436 dt
.Format("%b %d, %Y").c_str(),
4438 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4439 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4440 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4443 puts("\n*** done ***");
4446 static void TestTimeMS()
4448 puts("*** testing millisecond-resolution support in wxDateTime ***");
4450 wxDateTime dt1
= wxDateTime::Now(),
4451 dt2
= wxDateTime::UNow();
4453 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4454 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4455 printf("Dummy loop: ");
4456 for ( int i
= 0; i
< 6000; i
++ )
4458 //for ( int j = 0; j < 10; j++ )
4461 s
.Printf("%g", sqrt(i
));
4470 dt2
= wxDateTime::UNow();
4471 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4473 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4475 puts("\n*** done ***");
4478 static void TestTimeArithmetics()
4480 puts("\n*** testing arithmetic operations on wxDateTime ***");
4482 static const struct ArithmData
4484 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4485 : span(sp
), name(nam
) { }
4489 } testArithmData
[] =
4491 ArithmData(wxDateSpan::Day(), "day"),
4492 ArithmData(wxDateSpan::Week(), "week"),
4493 ArithmData(wxDateSpan::Month(), "month"),
4494 ArithmData(wxDateSpan::Year(), "year"),
4495 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4498 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4500 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4502 wxDateSpan span
= testArithmData
[n
].span
;
4506 const char *name
= testArithmData
[n
].name
;
4507 printf("%s + %s = %s, %s - %s = %s\n",
4508 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4509 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4511 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4512 if ( dt1
- span
== dt
)
4518 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4521 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4522 if ( dt2
+ span
== dt
)
4528 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4531 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4532 if ( dt2
+ 2*span
== dt1
)
4538 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4545 static void TestTimeHolidays()
4547 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4549 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4550 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4551 dtEnd
= dtStart
.GetLastMonthDay();
4553 wxDateTimeArray hol
;
4554 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4556 const wxChar
*format
= "%d-%b-%Y (%a)";
4558 printf("All holidays between %s and %s:\n",
4559 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4561 size_t count
= hol
.GetCount();
4562 for ( size_t n
= 0; n
< count
; n
++ )
4564 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4570 static void TestTimeZoneBug()
4572 puts("\n*** testing for DST/timezone bug ***\n");
4574 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4575 for ( int i
= 0; i
< 31; i
++ )
4577 printf("Date %s: week day %s.\n",
4578 date
.Format(_T("%d-%m-%Y")).c_str(),
4579 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4581 date
+= wxDateSpan::Day();
4587 static void TestTimeSpanFormat()
4589 puts("\n*** wxTimeSpan tests ***");
4591 static const char *formats
[] =
4593 _T("(default) %H:%M:%S"),
4594 _T("%E weeks and %D days"),
4595 _T("%l milliseconds"),
4596 _T("(with ms) %H:%M:%S:%l"),
4597 _T("100%% of minutes is %M"), // test "%%"
4598 _T("%D days and %H hours"),
4599 _T("or also %S seconds"),
4602 wxTimeSpan
ts1(1, 2, 3, 4),
4604 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4606 printf("ts1 = %s\tts2 = %s\n",
4607 ts1
.Format(formats
[n
]).c_str(),
4608 ts2
.Format(formats
[n
]).c_str());
4616 // test compatibility with the old wxDate/wxTime classes
4617 static void TestTimeCompatibility()
4619 puts("\n*** wxDateTime compatibility test ***");
4621 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4622 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4624 double jdnNow
= wxDateTime::Now().GetJDN();
4625 long jdnMidnight
= (long)(jdnNow
- 0.5);
4626 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4628 jdnMidnight
= wxDate().Set().GetJulianDate();
4629 printf("wxDateTime for today: %s\n",
4630 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4632 int flags
= wxEUROPEAN
;//wxFULL;
4635 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4636 for ( int n
= 0; n
< 7; n
++ )
4638 printf("Previous %s is %s\n",
4639 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4640 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4646 #endif // TEST_DATETIME
4648 // ----------------------------------------------------------------------------
4650 // ----------------------------------------------------------------------------
4654 #include "wx/thread.h"
4656 static size_t gs_counter
= (size_t)-1;
4657 static wxCriticalSection gs_critsect
;
4658 static wxSemaphore gs_cond
;
4660 class MyJoinableThread
: public wxThread
4663 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4664 { m_n
= n
; Create(); }
4666 // thread execution starts here
4667 virtual ExitCode
Entry();
4673 wxThread::ExitCode
MyJoinableThread::Entry()
4675 unsigned long res
= 1;
4676 for ( size_t n
= 1; n
< m_n
; n
++ )
4680 // it's a loooong calculation :-)
4684 return (ExitCode
)res
;
4687 class MyDetachedThread
: public wxThread
4690 MyDetachedThread(size_t n
, char ch
)
4694 m_cancelled
= FALSE
;
4699 // thread execution starts here
4700 virtual ExitCode
Entry();
4703 virtual void OnExit();
4706 size_t m_n
; // number of characters to write
4707 char m_ch
; // character to write
4709 bool m_cancelled
; // FALSE if we exit normally
4712 wxThread::ExitCode
MyDetachedThread::Entry()
4715 wxCriticalSectionLocker
lock(gs_critsect
);
4716 if ( gs_counter
== (size_t)-1 )
4722 for ( size_t n
= 0; n
< m_n
; n
++ )
4724 if ( TestDestroy() )
4734 wxThread::Sleep(100);
4740 void MyDetachedThread::OnExit()
4742 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4744 wxCriticalSectionLocker
lock(gs_critsect
);
4745 if ( !--gs_counter
&& !m_cancelled
)
4749 static void TestDetachedThreads()
4751 puts("\n*** Testing detached threads ***");
4753 static const size_t nThreads
= 3;
4754 MyDetachedThread
*threads
[nThreads
];
4756 for ( n
= 0; n
< nThreads
; n
++ )
4758 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4761 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4762 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4764 for ( n
= 0; n
< nThreads
; n
++ )
4769 // wait until all threads terminate
4775 static void TestJoinableThreads()
4777 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4779 // calc 10! in the background
4780 MyJoinableThread
thread(10);
4783 printf("\nThread terminated with exit code %lu.\n",
4784 (unsigned long)thread
.Wait());
4787 static void TestThreadSuspend()
4789 puts("\n*** Testing thread suspend/resume functions ***");
4791 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4795 // this is for this demo only, in a real life program we'd use another
4796 // condition variable which would be signaled from wxThread::Entry() to
4797 // tell us that the thread really started running - but here just wait a
4798 // bit and hope that it will be enough (the problem is, of course, that
4799 // the thread might still not run when we call Pause() which will result
4801 wxThread::Sleep(300);
4803 for ( size_t n
= 0; n
< 3; n
++ )
4807 puts("\nThread suspended");
4810 // don't sleep but resume immediately the first time
4811 wxThread::Sleep(300);
4813 puts("Going to resume the thread");
4818 puts("Waiting until it terminates now");
4820 // wait until the thread terminates
4826 static void TestThreadDelete()
4828 // As above, using Sleep() is only for testing here - we must use some
4829 // synchronisation object instead to ensure that the thread is still
4830 // running when we delete it - deleting a detached thread which already
4831 // terminated will lead to a crash!
4833 puts("\n*** Testing thread delete function ***");
4835 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4839 puts("\nDeleted a thread which didn't start to run yet.");
4841 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4845 wxThread::Sleep(300);
4849 puts("\nDeleted a running thread.");
4851 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4855 wxThread::Sleep(300);
4861 puts("\nDeleted a sleeping thread.");
4863 MyJoinableThread
thread3(20);
4868 puts("\nDeleted a joinable thread.");
4870 MyJoinableThread
thread4(2);
4873 wxThread::Sleep(300);
4877 puts("\nDeleted a joinable thread which already terminated.");
4882 class MyWaitingThread
: public wxThread
4885 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4888 m_condition
= condition
;
4893 virtual ExitCode
Entry()
4895 printf("Thread %lu has started running.\n", GetId());
4900 printf("Thread %lu starts to wait...\n", GetId());
4904 m_condition
->Wait();
4907 printf("Thread %lu finished to wait, exiting.\n", GetId());
4915 wxCondition
*m_condition
;
4918 static void TestThreadConditions()
4921 wxCondition
condition(mutex
);
4923 // otherwise its difficult to understand which log messages pertain to
4925 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4926 // condition.GetId(), gs_cond.GetId());
4928 // create and launch threads
4929 MyWaitingThread
*threads
[10];
4932 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4934 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4937 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4942 // wait until all threads run
4943 puts("Main thread is waiting for the other threads to start");
4946 size_t nRunning
= 0;
4947 while ( nRunning
< WXSIZEOF(threads
) )
4953 printf("Main thread: %u already running\n", nRunning
);
4957 puts("Main thread: all threads started up.");
4960 wxThread::Sleep(500);
4963 // now wake one of them up
4964 printf("Main thread: about to signal the condition.\n");
4969 wxThread::Sleep(200);
4971 // wake all the (remaining) threads up, so that they can exit
4972 printf("Main thread: about to broadcast the condition.\n");
4974 condition
.Broadcast();
4976 // give them time to terminate (dirty!)
4977 wxThread::Sleep(500);
4980 #include "wx/utils.h"
4982 class MyExecThread
: public wxThread
4985 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
4991 virtual ExitCode
Entry()
4993 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5000 static void TestThreadExec()
5002 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5004 MyExecThread
thread(_T("true"));
5007 wxPrintf(_T("Main program exit code: %ld.\n"),
5008 wxExecute(_T("false"), wxEXEC_SYNC
));
5010 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5014 #include "wx/datetime.h"
5016 class MySemaphoreThread
: public wxThread
5019 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5020 : wxThread(wxTHREAD_JOINABLE
),
5027 virtual ExitCode
Entry()
5029 wxPrintf(_T("%s: Thread %d starting to wait for semaphore...\n"),
5030 wxDateTime::Now().FormatTime().c_str(), m_i
);
5034 wxPrintf(_T("%s: Thread %d acquired the semaphore.\n"),
5035 wxDateTime::Now().FormatTime().c_str(), m_i
);
5039 wxPrintf(_T("%s: Thread %d releasing the semaphore.\n"),
5040 wxDateTime::Now().FormatTime().c_str(), m_i
);
5052 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5054 static void TestSemaphore()
5056 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5058 static const int SEM_LIMIT
= 3;
5060 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5061 ArrayThreads threads
;
5063 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5065 threads
.Add(new MySemaphoreThread(i
, &sem
));
5066 threads
.Last()->Run();
5069 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5076 #endif // TEST_THREADS
5078 // ----------------------------------------------------------------------------
5080 // ----------------------------------------------------------------------------
5084 #include "wx/dynarray.h"
5086 #define DefineCompare(name, T) \
5088 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5090 return first - second; \
5093 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5095 return *first - *second; \
5098 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5100 return *second - *first; \
5103 DefineCompare(Short, short);
5104 DefineCompare(Int
, int);
5106 // test compilation of all macros
5107 WX_DEFINE_ARRAY(short, wxArrayShort
);
5108 WX_DEFINE_SORTED_ARRAY(short, wxSortedArrayShortNoCmp
);
5109 WX_DEFINE_SORTED_ARRAY_CMP(short, ShortCompareValues
, wxSortedArrayShort
);
5110 WX_DEFINE_SORTED_ARRAY_CMP(int, IntCompareValues
, wxSortedArrayInt
);
5112 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5113 #include "wx/arrimpl.cpp"
5114 WX_DEFINE_OBJARRAY(ArrayBars
);
5116 static void PrintArray(const char* name
, const wxArrayString
& array
)
5118 printf("Dump of the array '%s'\n", name
);
5120 size_t nCount
= array
.GetCount();
5121 for ( size_t n
= 0; n
< nCount
; n
++ )
5123 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5127 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5128 const wxString
& second
)
5130 return first
.length() - second
.length();
5133 #define TestArrayOf(name) \
5135 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5137 printf("Dump of the array '%s'\n", name); \
5139 size_t nCount = array.GetCount(); \
5140 for ( size_t n = 0; n < nCount; n++ ) \
5142 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5146 static void PrintArray(const char* name, const wxArray##name & array) \
5148 printf("Dump of the array '%s'\n", name); \
5150 size_t nCount = array.GetCount(); \
5151 for ( size_t n = 0; n < nCount; n++ ) \
5153 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5157 static void TestArrayOf ## name ## s() \
5159 printf("*** Testing wxArray%s ***\n", #name); \
5167 puts("Initially:"); \
5168 PrintArray("a", a); \
5170 puts("After sort:"); \
5171 a.Sort(name ## Compare); \
5172 PrintArray("a", a); \
5174 puts("After reverse sort:"); \
5175 a.Sort(name ## RevCompare); \
5176 PrintArray("a", a); \
5178 wxSortedArray##name b; \
5184 puts("Sorted array initially:"); \
5185 PrintArray("b", b); \
5191 static void TestArrayOfObjects()
5193 puts("*** Testing wxObjArray ***\n");
5197 Bar
bar("second bar");
5199 printf("Initially: %u objects in the array, %u objects total.\n",
5200 bars
.GetCount(), Bar::GetNumber());
5202 bars
.Add(new Bar("first bar"));
5205 printf("Now: %u objects in the array, %u objects total.\n",
5206 bars
.GetCount(), Bar::GetNumber());
5210 printf("After Empty(): %u objects in the array, %u objects total.\n",
5211 bars
.GetCount(), Bar::GetNumber());
5214 printf("Finally: no more objects in the array, %u objects total.\n",
5218 #endif // TEST_ARRAYS
5220 // ----------------------------------------------------------------------------
5222 // ----------------------------------------------------------------------------
5226 #include "wx/timer.h"
5227 #include "wx/tokenzr.h"
5229 static void TestStringConstruction()
5231 puts("*** Testing wxString constructores ***");
5233 #define TEST_CTOR(args, res) \
5236 printf("wxString%s = %s ", #args, s.c_str()); \
5243 printf("(ERROR: should be %s)\n", res); \
5247 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5248 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5249 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5250 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5252 static const wxChar
*s
= _T("?really!");
5253 const wxChar
*start
= wxStrchr(s
, _T('r'));
5254 const wxChar
*end
= wxStrchr(s
, _T('!'));
5255 TEST_CTOR((start
, end
), _T("really"));
5260 static void TestString()
5270 for (int i
= 0; i
< 1000000; ++i
)
5274 c
= "! How'ya doin'?";
5277 c
= "Hello world! What's up?";
5282 printf ("TestString elapsed time: %ld\n", sw
.Time());
5285 static void TestPChar()
5293 for (int i
= 0; i
< 1000000; ++i
)
5295 strcpy (a
, "Hello");
5296 strcpy (b
, " world");
5297 strcpy (c
, "! How'ya doin'?");
5300 strcpy (c
, "Hello world! What's up?");
5301 if (strcmp (c
, a
) == 0)
5305 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5308 static void TestStringSub()
5310 wxString
s("Hello, world!");
5312 puts("*** Testing wxString substring extraction ***");
5314 printf("String = '%s'\n", s
.c_str());
5315 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5316 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5317 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5318 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5319 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5320 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5322 static const wxChar
*prefixes
[] =
5326 _T("Hello, world!"),
5327 _T("Hello, world!!!"),
5333 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5335 wxString prefix
= prefixes
[n
], rest
;
5336 bool rc
= s
.StartsWith(prefix
, &rest
);
5337 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5340 printf(" (the rest is '%s')\n", rest
.c_str());
5351 static void TestStringFormat()
5353 puts("*** Testing wxString formatting ***");
5356 s
.Printf("%03d", 18);
5358 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5359 printf("Number 18: %s\n", s
.c_str());
5364 // returns "not found" for npos, value for all others
5365 static wxString
PosToString(size_t res
)
5367 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5368 : wxString::Format(_T("%u"), res
);
5372 static void TestStringFind()
5374 puts("*** Testing wxString find() functions ***");
5376 static const wxChar
*strToFind
= _T("ell");
5377 static const struct StringFindTest
5381 result
; // of searching "ell" in str
5384 { _T("Well, hello world"), 0, 1 },
5385 { _T("Well, hello world"), 6, 7 },
5386 { _T("Well, hello world"), 9, wxString::npos
},
5389 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5391 const StringFindTest
& ft
= findTestData
[n
];
5392 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5394 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5395 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5397 size_t resTrue
= ft
.result
;
5398 if ( res
== resTrue
)
5404 printf(_T("(ERROR: should be %s)\n"),
5405 PosToString(resTrue
).c_str());
5412 static void TestStringTokenizer()
5414 puts("*** Testing wxStringTokenizer ***");
5416 static const wxChar
*modeNames
[] =
5420 _T("return all empty"),
5425 static const struct StringTokenizerTest
5427 const wxChar
*str
; // string to tokenize
5428 const wxChar
*delims
; // delimiters to use
5429 size_t count
; // count of token
5430 wxStringTokenizerMode mode
; // how should we tokenize it
5431 } tokenizerTestData
[] =
5433 { _T(""), _T(" "), 0 },
5434 { _T("Hello, world"), _T(" "), 2 },
5435 { _T("Hello, world "), _T(" "), 2 },
5436 { _T("Hello, world"), _T(","), 2 },
5437 { _T("Hello, world!"), _T(",!"), 2 },
5438 { _T("Hello,, world!"), _T(",!"), 3 },
5439 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5440 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5441 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5442 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5443 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5444 { _T("01/02/99"), _T("/-"), 3 },
5445 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5448 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5450 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5451 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5453 size_t count
= tkz
.CountTokens();
5454 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5455 MakePrintable(tt
.str
).c_str(),
5457 MakePrintable(tt
.delims
).c_str(),
5458 modeNames
[tkz
.GetMode()]);
5459 if ( count
== tt
.count
)
5465 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5470 // if we emulate strtok(), check that we do it correctly
5471 wxChar
*buf
, *s
= NULL
, *last
;
5473 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5475 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5476 wxStrcpy(buf
, tt
.str
);
5478 s
= wxStrtok(buf
, tt
.delims
, &last
);
5485 // now show the tokens themselves
5487 while ( tkz
.HasMoreTokens() )
5489 wxString token
= tkz
.GetNextToken();
5491 printf(_T("\ttoken %u: '%s'"),
5493 MakePrintable(token
).c_str());
5503 printf(" (ERROR: should be %s)\n", s
);
5506 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5510 // nothing to compare with
5515 if ( count2
!= count
)
5517 puts(_T("\tERROR: token count mismatch"));
5526 static void TestStringReplace()
5528 puts("*** Testing wxString::replace ***");
5530 static const struct StringReplaceTestData
5532 const wxChar
*original
; // original test string
5533 size_t start
, len
; // the part to replace
5534 const wxChar
*replacement
; // the replacement string
5535 const wxChar
*result
; // and the expected result
5536 } stringReplaceTestData
[] =
5538 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5539 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5540 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5541 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5542 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5545 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5547 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5549 wxString original
= data
.original
;
5550 original
.replace(data
.start
, data
.len
, data
.replacement
);
5552 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5553 data
.original
, data
.start
, data
.len
, data
.replacement
,
5556 if ( original
== data
.result
)
5562 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5569 static void TestStringMatch()
5571 wxPuts(_T("*** Testing wxString::Matches() ***"));
5573 static const struct StringMatchTestData
5576 const wxChar
*wildcard
;
5578 } stringMatchTestData
[] =
5580 { _T("foobar"), _T("foo*"), 1 },
5581 { _T("foobar"), _T("*oo*"), 1 },
5582 { _T("foobar"), _T("*bar"), 1 },
5583 { _T("foobar"), _T("??????"), 1 },
5584 { _T("foobar"), _T("f??b*"), 1 },
5585 { _T("foobar"), _T("f?b*"), 0 },
5586 { _T("foobar"), _T("*goo*"), 0 },
5587 { _T("foobar"), _T("*foo"), 0 },
5588 { _T("foobarfoo"), _T("*foo"), 1 },
5589 { _T(""), _T("*"), 1 },
5590 { _T(""), _T("?"), 0 },
5593 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5595 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5596 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5597 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5599 matches
? _T("matches") : _T("doesn't match"),
5601 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5607 #endif // TEST_STRINGS
5609 // ----------------------------------------------------------------------------
5611 // ----------------------------------------------------------------------------
5613 #ifdef TEST_SNGLINST
5614 #include "wx/snglinst.h"
5615 #endif // TEST_SNGLINST
5617 int main(int argc
, char **argv
)
5619 wxInitializer initializer
;
5622 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5627 #ifdef TEST_SNGLINST
5628 wxSingleInstanceChecker checker
;
5629 if ( checker
.Create(_T(".wxconsole.lock")) )
5631 if ( checker
.IsAnotherRunning() )
5633 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5638 // wait some time to give time to launch another instance
5639 wxPrintf(_T("Press \"Enter\" to continue..."));
5642 else // failed to create
5644 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5646 #endif // TEST_SNGLINST
5650 #endif // TEST_CHARSET
5653 TestCmdLineConvert();
5655 #if wxUSE_CMDLINE_PARSER
5656 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5658 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5659 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5660 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5661 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5663 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5664 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5665 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5666 wxCMD_LINE_VAL_NUMBER
},
5667 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5668 wxCMD_LINE_VAL_DATE
},
5670 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5671 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5676 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5678 parser
.AddOption("project_name", "", "full path to project file",
5679 wxCMD_LINE_VAL_STRING
,
5680 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5682 switch ( parser
.Parse() )
5685 wxLogMessage("Help was given, terminating.");
5689 ShowCmdLine(parser
);
5693 wxLogMessage("Syntax error detected, aborting.");
5696 #endif // wxUSE_CMDLINE_PARSER
5698 #endif // TEST_CMDLINE
5706 TestStringConstruction();
5709 TestStringTokenizer();
5710 TestStringReplace();
5716 #endif // TEST_STRINGS
5729 puts("*** Initially:");
5731 PrintArray("a1", a1
);
5733 wxArrayString
a2(a1
);
5734 PrintArray("a2", a2
);
5736 wxSortedArrayString
a3(a1
);
5737 PrintArray("a3", a3
);
5739 puts("*** After deleting a string from a1");
5742 PrintArray("a1", a1
);
5743 PrintArray("a2", a2
);
5744 PrintArray("a3", a3
);
5746 puts("*** After reassigning a1 to a2 and a3");
5748 PrintArray("a2", a2
);
5749 PrintArray("a3", a3
);
5751 puts("*** After sorting a1");
5753 PrintArray("a1", a1
);
5755 puts("*** After sorting a1 in reverse order");
5757 PrintArray("a1", a1
);
5759 puts("*** After sorting a1 by the string length");
5760 a1
.Sort(StringLenCompare
);
5761 PrintArray("a1", a1
);
5763 TestArrayOfObjects();
5764 TestArrayOfShorts();
5768 #endif // TEST_ARRAYS
5778 #ifdef TEST_DLLLOADER
5780 #endif // TEST_DLLLOADER
5784 #endif // TEST_ENVIRON
5788 #endif // TEST_EXECUTE
5790 #ifdef TEST_FILECONF
5792 #endif // TEST_FILECONF
5800 #endif // TEST_LOCALE
5804 for ( size_t n
= 0; n
< 8000; n
++ )
5806 s
<< (char)('A' + (n
% 26));
5810 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5812 // this one shouldn't be truncated
5815 // but this one will because log functions use fixed size buffer
5816 // (note that it doesn't need '\n' at the end neither - will be added
5818 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5830 #ifdef TEST_FILENAME
5834 fn
.Assign("c:\\foo", "bar.baz");
5841 TestFileNameConstruction();
5842 TestFileNameMakeRelative();
5843 TestFileNameSplit();
5846 TestFileNameComparison();
5847 TestFileNameOperations();
5849 #endif // TEST_FILENAME
5851 #ifdef TEST_FILETIME
5854 #endif // TEST_FILETIME
5857 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5858 if ( TestFtpConnect() )
5869 if ( TEST_INTERACTIVE
)
5870 TestFtpInteractive();
5872 //else: connecting to the FTP server failed
5878 #ifdef TEST_LONGLONG
5879 // seed pseudo random generator
5880 srand((unsigned)time(NULL
));
5889 TestMultiplication();
5892 TestLongLongConversion();
5893 TestBitOperations();
5894 TestLongLongComparison();
5895 TestLongLongPrint();
5897 #endif // TEST_LONGLONG
5905 #endif // TEST_HASHMAP
5908 wxLog::AddTraceMask(_T("mime"));
5916 TestMimeAssociate();
5919 #ifdef TEST_INFO_FUNCTIONS
5925 if ( TEST_INTERACTIVE
)
5928 #endif // TEST_INFO_FUNCTIONS
5930 #ifdef TEST_PATHLIST
5932 #endif // TEST_PATHLIST
5940 #endif // TEST_REGCONF
5943 // TODO: write a real test using src/regex/tests file
5948 TestRegExSubmatch();
5949 TestRegExReplacement();
5951 if ( TEST_INTERACTIVE
)
5952 TestRegExInteractive();
5954 #endif // TEST_REGEX
5956 #ifdef TEST_REGISTRY
5958 TestRegistryAssociation();
5959 #endif // TEST_REGISTRY
5964 #endif // TEST_SOCKETS
5969 #endif // TEST_STREAMS
5972 int nCPUs
= wxThread::GetCPUCount();
5973 printf("This system has %d CPUs\n", nCPUs
);
5975 wxThread::SetConcurrency(nCPUs
);
5979 TestDetachedThreads();
5980 TestJoinableThreads();
5981 TestThreadSuspend();
5983 TestThreadConditions();
5988 #endif // TEST_THREADS
5992 #endif // TEST_TIMER
5994 #ifdef TEST_DATETIME
6007 TestTimeArithmetics();
6010 TestTimeSpanFormat();
6016 if ( TEST_INTERACTIVE
)
6017 TestDateTimeInteractive();
6018 #endif // TEST_DATETIME
6021 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6023 #endif // TEST_USLEEP
6028 #endif // TEST_VCARD
6032 #endif // TEST_VOLUME
6036 TestEncodingConverter();
6037 #endif // TEST_WCHAR
6040 TestZipStreamRead();
6041 TestZipFileSystem();
6045 TestZlibStreamWrite();
6046 TestZlibStreamRead();