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(const Bar
& bar
) : m_name(bar
.m_name
) { ms_bars
++; }
119 ~Bar() { ms_bars
--; }
121 static size_t GetNumber() { return ms_bars
; }
123 const char *GetName() const { return m_name
; }
128 static size_t ms_bars
;
131 size_t Bar::ms_bars
= 0;
133 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
135 // ============================================================================
137 // ============================================================================
139 // ----------------------------------------------------------------------------
141 // ----------------------------------------------------------------------------
143 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
145 // replace TABs with \t and CRs with \n
146 static wxString
MakePrintable(const wxChar
*s
)
149 (void)str
.Replace(_T("\t"), _T("\\t"));
150 (void)str
.Replace(_T("\n"), _T("\\n"));
151 (void)str
.Replace(_T("\r"), _T("\\r"));
156 #endif // MakePrintable() is used
158 // ----------------------------------------------------------------------------
159 // wxFontMapper::CharsetToEncoding
160 // ----------------------------------------------------------------------------
164 #include "wx/fontmap.h"
166 static void TestCharset()
168 static const wxChar
*charsets
[] =
170 // some vali charsets
179 // and now some bogus ones
186 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
188 wxFontEncoding enc
= wxFontMapper::Get()->CharsetToEncoding(charsets
[n
]);
189 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
191 wxFontMapper::Get()->GetEncodingName(enc
).c_str(),
192 wxFontMapper::Get()->GetEncodingDescription(enc
).c_str());
196 #endif // TEST_CHARSET
198 // ----------------------------------------------------------------------------
200 // ----------------------------------------------------------------------------
204 #include "wx/cmdline.h"
205 #include "wx/datetime.h"
207 #if wxUSE_CMDLINE_PARSER
209 static void ShowCmdLine(const wxCmdLineParser
& parser
)
211 wxString s
= "Input files: ";
213 size_t count
= parser
.GetParamCount();
214 for ( size_t param
= 0; param
< count
; param
++ )
216 s
<< parser
.GetParam(param
) << ' ';
220 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
221 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
226 if ( parser
.Found("o", &strVal
) )
227 s
<< "Output file:\t" << strVal
<< '\n';
228 if ( parser
.Found("i", &strVal
) )
229 s
<< "Input dir:\t" << strVal
<< '\n';
230 if ( parser
.Found("s", &lVal
) )
231 s
<< "Size:\t" << lVal
<< '\n';
232 if ( parser
.Found("d", &dt
) )
233 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
234 if ( parser
.Found("project_name", &strVal
) )
235 s
<< "Project:\t" << strVal
<< '\n';
240 #endif // wxUSE_CMDLINE_PARSER
242 static void TestCmdLineConvert()
244 static const char *cmdlines
[] =
247 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
248 "literal \\\" and \"\"",
251 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
253 const char *cmdline
= cmdlines
[n
];
254 printf("Parsing: %s\n", cmdline
);
255 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
257 size_t count
= args
.GetCount();
258 printf("\targc = %u\n", count
);
259 for ( size_t arg
= 0; arg
< count
; arg
++ )
261 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
266 #endif // TEST_CMDLINE
268 // ----------------------------------------------------------------------------
270 // ----------------------------------------------------------------------------
277 static const wxChar
*ROOTDIR
= _T("/");
278 static const wxChar
*TESTDIR
= _T("/usr");
279 #elif defined(__WXMSW__)
280 static const wxChar
*ROOTDIR
= _T("c:\\");
281 static const wxChar
*TESTDIR
= _T("d:\\");
283 #error "don't know where the root directory is"
286 static void TestDirEnumHelper(wxDir
& dir
,
287 int flags
= wxDIR_DEFAULT
,
288 const wxString
& filespec
= wxEmptyString
)
292 if ( !dir
.IsOpened() )
295 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
298 printf("\t%s\n", filename
.c_str());
300 cont
= dir
.GetNext(&filename
);
306 static void TestDirEnum()
308 puts("*** Testing wxDir::GetFirst/GetNext ***");
310 wxDir
dir(wxGetCwd());
312 puts("Enumerating everything in current directory:");
313 TestDirEnumHelper(dir
);
315 puts("Enumerating really everything in current directory:");
316 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
318 puts("Enumerating object files in current directory:");
319 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
321 puts("Enumerating directories in current directory:");
322 TestDirEnumHelper(dir
, wxDIR_DIRS
);
324 puts("Enumerating files in current directory:");
325 TestDirEnumHelper(dir
, wxDIR_FILES
);
327 puts("Enumerating files including hidden in current directory:");
328 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
332 puts("Enumerating everything in root directory:");
333 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
335 puts("Enumerating directories in root directory:");
336 TestDirEnumHelper(dir
, wxDIR_DIRS
);
338 puts("Enumerating files in root directory:");
339 TestDirEnumHelper(dir
, wxDIR_FILES
);
341 puts("Enumerating files including hidden in root directory:");
342 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
344 puts("Enumerating files in non existing directory:");
345 wxDir
dirNo("nosuchdir");
346 TestDirEnumHelper(dirNo
);
349 class DirPrintTraverser
: public wxDirTraverser
352 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
354 return wxDIR_CONTINUE
;
357 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
359 wxString path
, name
, ext
;
360 wxSplitPath(dirname
, &path
, &name
, &ext
);
363 name
<< _T('.') << ext
;
366 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
368 if ( wxIsPathSeparator(*p
) )
372 printf("%s%s\n", indent
.c_str(), name
.c_str());
374 return wxDIR_CONTINUE
;
378 static void TestDirTraverse()
380 puts("*** Testing wxDir::Traverse() ***");
384 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
385 printf("There are %u files under '%s'\n", n
, TESTDIR
);
388 printf("First one is '%s'\n", files
[0u].c_str());
389 printf(" last one is '%s'\n", files
[n
- 1].c_str());
392 // enum again with custom traverser
394 DirPrintTraverser traverser
;
395 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
400 // ----------------------------------------------------------------------------
402 // ----------------------------------------------------------------------------
404 #ifdef TEST_DLLLOADER
406 #include "wx/dynlib.h"
408 static void TestDllLoad()
410 #if defined(__WXMSW__)
411 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
412 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
413 #elif defined(__UNIX__)
414 // weird: using just libc.so does *not* work!
415 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
416 static const wxChar
*FUNC_NAME
= _T("strlen");
418 #error "don't know how to test wxDllLoader on this platform"
421 puts("*** testing wxDllLoader ***\n");
423 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
426 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
430 typedef int (*strlenType
)(const char *);
431 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
434 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
435 FUNC_NAME
, LIB_NAME
);
439 if ( pfnStrlen("foo") != 3 )
441 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
449 wxDllLoader::UnloadLibrary(dllHandle
);
453 #endif // TEST_DLLLOADER
455 // ----------------------------------------------------------------------------
457 // ----------------------------------------------------------------------------
461 #include "wx/utils.h"
463 static wxString
MyGetEnv(const wxString
& var
)
466 if ( !wxGetEnv(var
, &val
) )
469 val
= wxString(_T('\'')) + val
+ _T('\'');
474 static void TestEnvironment()
476 const wxChar
*var
= _T("wxTestVar");
478 puts("*** testing environment access functions ***");
480 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
481 wxSetEnv(var
, _T("value for wxTestVar"));
482 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
483 wxSetEnv(var
, _T("another value"));
484 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
486 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
487 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
490 #endif // TEST_ENVIRON
492 // ----------------------------------------------------------------------------
494 // ----------------------------------------------------------------------------
498 #include "wx/utils.h"
500 static void TestExecute()
502 puts("*** testing wxExecute ***");
505 #define COMMAND "cat -n ../../Makefile" // "echo hi"
506 #define SHELL_COMMAND "echo hi from shell"
507 #define REDIRECT_COMMAND COMMAND // "date"
508 #elif defined(__WXMSW__)
509 #define COMMAND "command.com -c 'echo hi'"
510 #define SHELL_COMMAND "echo hi"
511 #define REDIRECT_COMMAND COMMAND
513 #error "no command to exec"
516 printf("Testing wxShell: ");
518 if ( wxShell(SHELL_COMMAND
) )
523 printf("Testing wxExecute: ");
525 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
530 #if 0 // no, it doesn't work (yet?)
531 printf("Testing async wxExecute: ");
533 if ( wxExecute(COMMAND
) != 0 )
534 puts("Ok (command launched).");
539 printf("Testing wxExecute with redirection:\n");
540 wxArrayString output
;
541 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
547 size_t count
= output
.GetCount();
548 for ( size_t n
= 0; n
< count
; n
++ )
550 printf("\t%s\n", output
[n
].c_str());
557 #endif // TEST_EXECUTE
559 // ----------------------------------------------------------------------------
561 // ----------------------------------------------------------------------------
566 #include "wx/ffile.h"
567 #include "wx/textfile.h"
569 static void TestFileRead()
571 puts("*** wxFile read test ***");
573 wxFile
file(_T("testdata.fc"));
574 if ( file
.IsOpened() )
576 printf("File length: %lu\n", file
.Length());
578 puts("File dump:\n----------");
580 static const off_t len
= 1024;
584 off_t nRead
= file
.Read(buf
, len
);
585 if ( nRead
== wxInvalidOffset
)
587 printf("Failed to read the file.");
591 fwrite(buf
, nRead
, 1, stdout
);
601 printf("ERROR: can't open test file.\n");
607 static void TestTextFileRead()
609 puts("*** wxTextFile read test ***");
611 wxTextFile
file(_T("testdata.fc"));
614 printf("Number of lines: %u\n", file
.GetLineCount());
615 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
619 puts("\nDumping the entire file:");
620 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
622 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
624 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
626 puts("\nAnd now backwards:");
627 for ( s
= file
.GetLastLine();
628 file
.GetCurrentLine() != 0;
629 s
= file
.GetPrevLine() )
631 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
633 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
637 printf("ERROR: can't open '%s'\n", file
.GetName());
643 static void TestFileCopy()
645 puts("*** Testing wxCopyFile ***");
647 static const wxChar
*filename1
= _T("testdata.fc");
648 static const wxChar
*filename2
= _T("test2");
649 if ( !wxCopyFile(filename1
, filename2
) )
651 puts("ERROR: failed to copy file");
655 wxFFile
f1(filename1
, "rb"),
658 if ( !f1
.IsOpened() || !f2
.IsOpened() )
660 puts("ERROR: failed to open file(s)");
665 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
667 puts("ERROR: failed to read file(s)");
671 if ( (s1
.length() != s2
.length()) ||
672 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
674 puts("ERROR: copy error!");
678 puts("File was copied ok.");
684 if ( !wxRemoveFile(filename2
) )
686 puts("ERROR: failed to remove the file");
694 // ----------------------------------------------------------------------------
696 // ----------------------------------------------------------------------------
700 #include "wx/confbase.h"
701 #include "wx/fileconf.h"
703 static const struct FileConfTestData
705 const wxChar
*name
; // value name
706 const wxChar
*value
; // the value from the file
709 { _T("value1"), _T("one") },
710 { _T("value2"), _T("two") },
711 { _T("novalue"), _T("default") },
714 static void TestFileConfRead()
716 puts("*** testing wxFileConfig loading/reading ***");
718 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
719 _T("testdata.fc"), wxEmptyString
,
720 wxCONFIG_USE_RELATIVE_PATH
);
722 // test simple reading
723 puts("\nReading config file:");
724 wxString
defValue(_T("default")), value
;
725 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
727 const FileConfTestData
& data
= fcTestData
[n
];
728 value
= fileconf
.Read(data
.name
, defValue
);
729 printf("\t%s = %s ", data
.name
, value
.c_str());
730 if ( value
== data
.value
)
736 printf("(ERROR: should be %s)\n", data
.value
);
740 // test enumerating the entries
741 puts("\nEnumerating all root entries:");
744 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
747 printf("\t%s = %s\n",
749 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
751 cont
= fileconf
.GetNextEntry(name
, dummy
);
755 #endif // TEST_FILECONF
757 // ----------------------------------------------------------------------------
759 // ----------------------------------------------------------------------------
763 #include "wx/filename.h"
765 static void DumpFileName(const wxFileName
& fn
)
767 wxString full
= fn
.GetFullPath();
769 wxString vol
, path
, name
, ext
;
770 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
772 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
773 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
775 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
776 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
777 path
.c_str(), name
.c_str(), ext
.c_str());
779 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
780 wxPrintf(_T("with volume: \t'%s'\n"),
781 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
782 wxPrintf(_T("with separator:\t'%s'\n"),
783 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
784 wxPrintf(_T("with both: \t'%s'\n"),
785 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
788 static struct FileNameInfo
790 const wxChar
*fullname
;
791 const wxChar
*volume
;
800 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
801 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
802 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
803 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
804 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
805 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
806 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
807 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
808 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
810 // Windows file names
811 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
812 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
813 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
814 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
815 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
816 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
818 // wxFileName support for Mac file names is broken currently
821 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
822 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
823 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
824 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
825 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
826 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
830 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
831 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
834 static void TestFileNameConstruction()
836 puts("*** testing wxFileName construction ***");
838 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
840 const FileNameInfo
& fni
= filenames
[n
];
842 wxFileName
fn(fni
.fullname
, fni
.format
);
844 wxString fullname
= fn
.GetFullPath(fni
.format
);
845 if ( fullname
!= fni
.fullname
)
847 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
850 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
851 printf("'%s' is %s (%s)\n\t",
853 isAbsolute
? "absolute" : "relative",
854 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
856 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
858 puts("ERROR (couldn't be normalized)");
862 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
869 static void TestFileNameSplit()
871 puts("*** testing wxFileName splitting ***");
873 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
875 const FileNameInfo
& fni
= filenames
[n
];
876 wxString volume
, path
, name
, ext
;
877 wxFileName::SplitPath(fni
.fullname
,
878 &volume
, &path
, &name
, &ext
, fni
.format
);
880 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
882 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
884 if ( volume
!= fni
.volume
)
885 printf(" (ERROR: volume = '%s')", fni
.volume
);
886 if ( path
!= fni
.path
)
887 printf(" (ERROR: path = '%s')", fni
.path
);
888 if ( name
!= fni
.name
)
889 printf(" (ERROR: name = '%s')", fni
.name
);
890 if ( ext
!= fni
.ext
)
891 printf(" (ERROR: ext = '%s')", fni
.ext
);
897 static void TestFileNameTemp()
899 puts("*** testing wxFileName temp file creation ***");
901 static const char *tmpprefixes
[] =
909 "/tmp/foo/bar", // this one must be an error
913 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
915 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
918 // "error" is not in upper case because it may be ok
919 printf("Prefix '%s'\t-> error\n", tmpprefixes
[n
]);
923 printf("Prefix '%s'\t-> temp file '%s'\n",
924 tmpprefixes
[n
], path
.c_str());
926 if ( !wxRemoveFile(path
) )
928 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
934 static void TestFileNameMakeRelative()
936 puts("*** testing wxFileName::MakeRelativeTo() ***");
938 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
940 const FileNameInfo
& fni
= filenames
[n
];
942 wxFileName
fn(fni
.fullname
, fni
.format
);
944 // choose the base dir of the same format
946 switch ( fni
.format
)
958 // TODO: I don't know how this is supposed to work there
961 case wxPATH_NATIVE
: // make gcc happy
963 wxFAIL_MSG( "unexpected path format" );
966 printf("'%s' relative to '%s': ",
967 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
969 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
975 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
980 static void TestFileNameComparison()
985 static void TestFileNameOperations()
990 static void TestFileNameCwd()
995 #endif // TEST_FILENAME
997 // ----------------------------------------------------------------------------
998 // wxFileName time functions
999 // ----------------------------------------------------------------------------
1001 #ifdef TEST_FILETIME
1003 #include <wx/filename.h>
1004 #include <wx/datetime.h>
1006 static void TestFileGetTimes()
1008 wxFileName
fn(_T("testdata.fc"));
1010 wxDateTime dtAccess
, dtMod
, dtCreate
;
1011 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
1013 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
1017 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
1019 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
1020 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
1021 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
1022 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
1026 static void TestFileSetTimes()
1028 wxFileName
fn(_T("testdata.fc"));
1032 wxPrintf(_T("ERROR: Touch() failed.\n"));
1036 #endif // TEST_FILETIME
1038 // ----------------------------------------------------------------------------
1040 // ----------------------------------------------------------------------------
1044 #include "wx/hash.h"
1048 Foo(int n_
) { n
= n_
; count
++; }
1053 static size_t count
;
1056 size_t Foo::count
= 0;
1058 WX_DECLARE_LIST(Foo
, wxListFoos
);
1059 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1061 #include "wx/listimpl.cpp"
1063 WX_DEFINE_LIST(wxListFoos
);
1065 static void TestHash()
1067 puts("*** Testing wxHashTable ***\n");
1071 hash
.DeleteContents(TRUE
);
1073 printf("Hash created: %u foos in hash, %u foos totally\n",
1074 hash
.GetCount(), Foo::count
);
1076 static const int hashTestData
[] =
1078 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1082 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1084 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1087 printf("Hash filled: %u foos in hash, %u foos totally\n",
1088 hash
.GetCount(), Foo::count
);
1090 puts("Hash access test:");
1091 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1093 printf("\tGetting element with key %d, value %d: ",
1094 hashTestData
[n
], n
);
1095 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1098 printf("ERROR, not found.\n");
1102 printf("%d (%s)\n", foo
->n
,
1103 (size_t)foo
->n
== n
? "ok" : "ERROR");
1107 printf("\nTrying to get an element not in hash: ");
1109 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1111 puts("ERROR: found!");
1115 puts("ok (not found)");
1119 printf("Hash destroyed: %u foos left\n", Foo::count
);
1124 // ----------------------------------------------------------------------------
1126 // ----------------------------------------------------------------------------
1130 #include "wx/hashmap.h"
1132 // test compilation of basic map types
1133 WX_DECLARE_HASH_MAP( int*, int*, wxPointerHash
, wxPointerEqual
, myPtrHashMap
);
1134 WX_DECLARE_HASH_MAP( long, long, wxIntegerHash
, wxIntegerEqual
, myLongHashMap
);
1135 WX_DECLARE_HASH_MAP( unsigned long, unsigned, wxIntegerHash
, wxIntegerEqual
,
1136 myUnsignedHashMap
);
1137 WX_DECLARE_HASH_MAP( unsigned int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1139 WX_DECLARE_HASH_MAP( int, unsigned, wxIntegerHash
, wxIntegerEqual
,
1141 WX_DECLARE_HASH_MAP( short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1143 WX_DECLARE_HASH_MAP( unsigned short, unsigned, wxIntegerHash
, wxIntegerEqual
,
1147 // WX_DECLARE_HASH_MAP( wxString, wxString, wxStringHash, wxStringEqual,
1148 // myStringHashMap );
1149 WX_DECLARE_STRING_HASH_MAP(wxString
, myStringHashMap
);
1151 typedef myStringHashMap::iterator Itor
;
1153 static void TestHashMap()
1155 puts("*** Testing wxHashMap ***\n");
1156 myStringHashMap
sh(0); // as small as possible
1159 const size_t count
= 10000;
1161 // init with some data
1162 for( i
= 0; i
< count
; ++i
)
1164 buf
.Printf(wxT("%d"), i
);
1165 sh
[buf
] = wxT("A") + buf
+ wxT("C");
1168 // test that insertion worked
1169 if( sh
.size() != count
)
1171 printf("*** ERROR: %u ELEMENTS, SHOULD BE %u ***\n", sh
.size(), count
);
1174 for( i
= 0; i
< count
; ++i
)
1176 buf
.Printf(wxT("%d"), i
);
1177 if( sh
[buf
] != wxT("A") + buf
+ wxT("C") )
1179 printf("*** ERROR INSERTION BROKEN! STOPPING NOW! ***\n");
1184 // check that iterators work
1186 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1190 printf("*** ERROR ITERATORS DO NOT TERMINATE! STOPPING NOW! ***\n");
1194 if( it
->second
!= sh
[it
->first
] )
1196 printf("*** ERROR ITERATORS BROKEN! STOPPING NOW! ***\n");
1201 if( sh
.size() != i
)
1203 printf("*** ERROR: %u ELEMENTS ITERATED, SHOULD BE %u ***\n", i
, count
);
1206 // test copy ctor, assignment operator
1207 myStringHashMap
h1( sh
), h2( 0 );
1210 for( i
= 0, it
= sh
.begin(); it
!= sh
.end(); ++it
, ++i
)
1212 if( h1
[it
->first
] != it
->second
)
1214 printf("*** ERROR: COPY CTOR BROKEN %s ***\n", it
->first
.c_str());
1217 if( h2
[it
->first
] != it
->second
)
1219 printf("*** ERROR: OPERATOR= BROKEN %s ***\n", it
->first
.c_str());
1224 for( i
= 0; i
< count
; ++i
)
1226 buf
.Printf(wxT("%d"), i
);
1227 size_t sz
= sh
.size();
1229 // test find() and erase(it)
1232 it
= sh
.find( buf
);
1233 if( it
!= sh
.end() )
1237 if( sh
.find( buf
) != sh
.end() )
1239 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1243 printf("*** ERROR: CANT FIND ELEMENT %u ***\n", i
);
1248 size_t c
= sh
.erase( buf
);
1250 printf("*** ERROR: SHOULD RETURN 1 ***\n");
1252 if( sh
.find( buf
) != sh
.end() )
1254 printf("*** ERROR: FOUND DELETED ELEMENT %u ***\n", i
);
1258 // count should decrease
1259 if( sh
.size() != sz
- 1 )
1261 printf("*** ERROR: COUNT DID NOT DECREASE ***\n");
1265 printf("*** Finished testing wxHashMap ***\n");
1268 #endif // TEST_HASHMAP
1270 // ----------------------------------------------------------------------------
1272 // ----------------------------------------------------------------------------
1276 #include "wx/list.h"
1278 WX_DECLARE_LIST(Bar
, wxListBars
);
1279 #include "wx/listimpl.cpp"
1280 WX_DEFINE_LIST(wxListBars
);
1282 static void TestListCtor()
1284 puts("*** Testing wxList construction ***\n");
1288 list1
.Append(new Bar(_T("first")));
1289 list1
.Append(new Bar(_T("second")));
1291 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1292 list1
.GetCount(), Bar::GetNumber());
1297 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1298 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1300 list1
.DeleteContents(TRUE
);
1303 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1308 // ----------------------------------------------------------------------------
1310 // ----------------------------------------------------------------------------
1314 #include "wx/intl.h"
1315 #include "wx/utils.h" // for wxSetEnv
1317 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1319 // find the name of the language from its value
1320 static const char *GetLangName(int lang
)
1322 static const char *languageNames
[] =
1343 "ARABIC_SAUDI_ARABIA",
1368 "CHINESE_SIMPLIFIED",
1369 "CHINESE_TRADITIONAL",
1372 "CHINESE_SINGAPORE",
1383 "ENGLISH_AUSTRALIA",
1387 "ENGLISH_CARIBBEAN",
1391 "ENGLISH_NEW_ZEALAND",
1392 "ENGLISH_PHILIPPINES",
1393 "ENGLISH_SOUTH_AFRICA",
1405 "FRENCH_LUXEMBOURG",
1414 "GERMAN_LIECHTENSTEIN",
1415 "GERMAN_LUXEMBOURG",
1456 "MALAY_BRUNEI_DARUSSALAM",
1468 "NORWEGIAN_NYNORSK",
1475 "PORTUGUESE_BRAZILIAN",
1500 "SPANISH_ARGENTINA",
1504 "SPANISH_COSTA_RICA",
1505 "SPANISH_DOMINICAN_REPUBLIC",
1507 "SPANISH_EL_SALVADOR",
1508 "SPANISH_GUATEMALA",
1512 "SPANISH_NICARAGUA",
1516 "SPANISH_PUERTO_RICO",
1519 "SPANISH_VENEZUELA",
1556 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1557 return languageNames
[lang
];
1562 static void TestDefaultLang()
1564 puts("*** Testing wxLocale::GetSystemLanguage ***");
1566 static const wxChar
*langStrings
[] =
1568 NULL
, // system default
1575 _T("de_DE.iso88591"),
1577 _T("?"), // invalid lang spec
1578 _T("klingonese"), // I bet on some systems it does exist...
1581 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1582 wxLocale::GetSystemEncodingName().c_str(),
1583 wxLocale::GetSystemEncoding());
1585 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1587 const char *langStr
= langStrings
[n
];
1590 // FIXME: this doesn't do anything at all under Windows, we need
1591 // to create a new wxLocale!
1592 wxSetEnv(_T("LC_ALL"), langStr
);
1595 int lang
= gs_localeDefault
.GetSystemLanguage();
1596 printf("Locale for '%s' is %s.\n",
1597 langStr
? langStr
: "system default", GetLangName(lang
));
1601 #endif // TEST_LOCALE
1603 // ----------------------------------------------------------------------------
1605 // ----------------------------------------------------------------------------
1609 #include "wx/mimetype.h"
1611 static void TestMimeEnum()
1613 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1615 wxArrayString mimetypes
;
1617 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1619 printf("*** All %u known filetypes: ***\n", count
);
1624 for ( size_t n
= 0; n
< count
; n
++ )
1626 wxFileType
*filetype
=
1627 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1630 printf("nothing known about the filetype '%s'!\n",
1631 mimetypes
[n
].c_str());
1635 filetype
->GetDescription(&desc
);
1636 filetype
->GetExtensions(exts
);
1638 filetype
->GetIcon(NULL
);
1641 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1644 extsAll
<< _T(", ");
1648 printf("\t%s: %s (%s)\n",
1649 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1655 static void TestMimeOverride()
1657 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1659 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1660 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1662 if ( wxFile::Exists(mailcap
) )
1663 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1665 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1667 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1670 if ( wxFile::Exists(mimetypes
) )
1671 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1673 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1675 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1681 static void TestMimeFilename()
1683 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1685 static const wxChar
*filenames
[] =
1692 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1694 const wxString fname
= filenames
[n
];
1695 wxString ext
= fname
.AfterLast(_T('.'));
1696 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1699 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1704 if ( !ft
->GetDescription(&desc
) )
1705 desc
= _T("<no description>");
1708 if ( !ft
->GetOpenCommand(&cmd
,
1709 wxFileType::MessageParameters(fname
, _T(""))) )
1710 cmd
= _T("<no command available>");
1712 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1713 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1722 static void TestMimeAssociate()
1724 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1726 wxFileTypeInfo
ftInfo(
1727 _T("application/x-xyz"),
1728 _T("xyzview '%s'"), // open cmd
1729 _T(""), // print cmd
1730 _T("XYZ File"), // description
1731 _T(".xyz"), // extensions
1732 NULL
// end of extensions
1734 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1736 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1739 wxPuts(_T("ERROR: failed to create association!"));
1743 // TODO: read it back
1752 // ----------------------------------------------------------------------------
1753 // misc information functions
1754 // ----------------------------------------------------------------------------
1756 #ifdef TEST_INFO_FUNCTIONS
1758 #include "wx/utils.h"
1760 static void TestDiskInfo()
1762 puts("*** Testing wxGetDiskSpace() ***");
1767 printf("\nEnter a directory name: ");
1768 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1771 // kill the last '\n'
1772 pathname
[strlen(pathname
) - 1] = 0;
1774 wxLongLong total
, free
;
1775 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1777 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1781 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1782 (total
/ 1024).ToString().c_str(),
1783 (free
/ 1024).ToString().c_str(),
1789 static void TestOsInfo()
1791 puts("*** Testing OS info functions ***\n");
1794 wxGetOsVersion(&major
, &minor
);
1795 printf("Running under: %s, version %d.%d\n",
1796 wxGetOsDescription().c_str(), major
, minor
);
1798 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1800 printf("Host name is %s (%s).\n",
1801 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1806 static void TestUserInfo()
1808 puts("*** Testing user info functions ***\n");
1810 printf("User id is:\t%s\n", wxGetUserId().c_str());
1811 printf("User name is:\t%s\n", wxGetUserName().c_str());
1812 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1813 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1818 #endif // TEST_INFO_FUNCTIONS
1820 // ----------------------------------------------------------------------------
1822 // ----------------------------------------------------------------------------
1824 #ifdef TEST_LONGLONG
1826 #include "wx/longlong.h"
1827 #include "wx/timer.h"
1829 // make a 64 bit number from 4 16 bit ones
1830 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1832 // get a random 64 bit number
1833 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1835 static const long testLongs
[] =
1846 #if wxUSE_LONGLONG_WX
1847 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1848 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1849 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1850 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1851 #endif // wxUSE_LONGLONG_WX
1853 static void TestSpeed()
1855 static const long max
= 100000000;
1862 for ( n
= 0; n
< max
; n
++ )
1867 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1870 #if wxUSE_LONGLONG_NATIVE
1875 for ( n
= 0; n
< max
; n
++ )
1880 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1882 #endif // wxUSE_LONGLONG_NATIVE
1888 for ( n
= 0; n
< max
; n
++ )
1893 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1897 static void TestLongLongConversion()
1899 puts("*** Testing wxLongLong conversions ***\n");
1903 for ( size_t n
= 0; n
< 100000; n
++ )
1907 #if wxUSE_LONGLONG_NATIVE
1908 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1910 wxASSERT_MSG( a
== b
, "conversions failure" );
1912 puts("Can't do it without native long long type, test skipped.");
1915 #endif // wxUSE_LONGLONG_NATIVE
1917 if ( !(nTested
% 1000) )
1929 static void TestMultiplication()
1931 puts("*** Testing wxLongLong multiplication ***\n");
1935 for ( size_t n
= 0; n
< 100000; n
++ )
1940 #if wxUSE_LONGLONG_NATIVE
1941 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1942 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1944 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1945 #else // !wxUSE_LONGLONG_NATIVE
1946 puts("Can't do it without native long long type, test skipped.");
1949 #endif // wxUSE_LONGLONG_NATIVE
1951 if ( !(nTested
% 1000) )
1963 static void TestDivision()
1965 puts("*** Testing wxLongLong division ***\n");
1969 for ( size_t n
= 0; n
< 100000; n
++ )
1971 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1972 // multiplication will not overflow)
1973 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1975 // get a random (but non null) long (not wxLongLong for now) to divide
1987 #if wxUSE_LONGLONG_NATIVE
1988 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1990 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1991 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1992 #else // !wxUSE_LONGLONG_NATIVE
1993 // verify the result
1994 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1995 #endif // wxUSE_LONGLONG_NATIVE
1997 if ( !(nTested
% 1000) )
2009 static void TestAddition()
2011 puts("*** Testing wxLongLong addition ***\n");
2015 for ( size_t n
= 0; n
< 100000; n
++ )
2021 #if wxUSE_LONGLONG_NATIVE
2022 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
2023 wxLongLongNative(b
.GetHi(), b
.GetLo()),
2024 "addition failure" );
2025 #else // !wxUSE_LONGLONG_NATIVE
2026 wxASSERT_MSG( c
- b
== a
, "addition failure" );
2027 #endif // wxUSE_LONGLONG_NATIVE
2029 if ( !(nTested
% 1000) )
2041 static void TestBitOperations()
2043 puts("*** Testing wxLongLong bit operation ***\n");
2047 for ( size_t n
= 0; n
< 100000; n
++ )
2051 #if wxUSE_LONGLONG_NATIVE
2052 for ( size_t n
= 0; n
< 33; n
++ )
2055 #else // !wxUSE_LONGLONG_NATIVE
2056 puts("Can't do it without native long long type, test skipped.");
2059 #endif // wxUSE_LONGLONG_NATIVE
2061 if ( !(nTested
% 1000) )
2073 static void TestLongLongComparison()
2075 #if wxUSE_LONGLONG_WX
2076 puts("*** Testing wxLongLong comparison ***\n");
2078 static const long ls
[2] =
2084 wxLongLongWx lls
[2];
2088 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2092 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
2094 res
= lls
[m
] > testLongs
[n
];
2095 printf("0x%lx > 0x%lx is %s (%s)\n",
2096 ls
[m
], testLongs
[n
], res
? "true" : "false",
2097 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
2099 res
= lls
[m
] < testLongs
[n
];
2100 printf("0x%lx < 0x%lx is %s (%s)\n",
2101 ls
[m
], testLongs
[n
], res
? "true" : "false",
2102 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
2104 res
= lls
[m
] == testLongs
[n
];
2105 printf("0x%lx == 0x%lx is %s (%s)\n",
2106 ls
[m
], testLongs
[n
], res
? "true" : "false",
2107 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
2110 #endif // wxUSE_LONGLONG_WX
2113 static void TestLongLongPrint()
2115 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
2117 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
2119 wxLongLong ll
= testLongs
[n
];
2120 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
2123 wxLongLong
ll(0x12345678, 0x87654321);
2124 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2127 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
2133 #endif // TEST_LONGLONG
2135 // ----------------------------------------------------------------------------
2137 // ----------------------------------------------------------------------------
2139 #ifdef TEST_PATHLIST
2141 static void TestPathList()
2143 puts("*** Testing wxPathList ***\n");
2145 wxPathList pathlist
;
2146 pathlist
.AddEnvList("PATH");
2147 wxString path
= pathlist
.FindValidPath("ls");
2150 printf("ERROR: command not found in the path.\n");
2154 printf("Command found in the path as '%s'.\n", path
.c_str());
2158 #endif // TEST_PATHLIST
2160 // ----------------------------------------------------------------------------
2161 // regular expressions
2162 // ----------------------------------------------------------------------------
2166 #include "wx/regex.h"
2168 static void TestRegExCompile()
2170 wxPuts(_T("*** Testing RE compilation ***\n"));
2172 static struct RegExCompTestData
2174 const wxChar
*pattern
;
2176 } regExCompTestData
[] =
2178 { _T("foo"), TRUE
},
2179 { _T("foo("), FALSE
},
2180 { _T("foo(bar"), FALSE
},
2181 { _T("foo(bar)"), TRUE
},
2182 { _T("foo["), FALSE
},
2183 { _T("foo[bar"), FALSE
},
2184 { _T("foo[bar]"), TRUE
},
2185 { _T("foo{"), TRUE
},
2186 { _T("foo{1"), FALSE
},
2187 { _T("foo{bar"), TRUE
},
2188 { _T("foo{1}"), TRUE
},
2189 { _T("foo{1,2}"), TRUE
},
2190 { _T("foo{bar}"), TRUE
},
2191 { _T("foo*"), TRUE
},
2192 { _T("foo**"), FALSE
},
2193 { _T("foo+"), TRUE
},
2194 { _T("foo++"), FALSE
},
2195 { _T("foo?"), TRUE
},
2196 { _T("foo??"), FALSE
},
2197 { _T("foo?+"), FALSE
},
2201 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2203 const RegExCompTestData
& data
= regExCompTestData
[n
];
2204 bool ok
= re
.Compile(data
.pattern
);
2206 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2208 ok
? _T("") : _T("not "),
2209 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2213 static void TestRegExMatch()
2215 wxPuts(_T("*** Testing RE matching ***\n"));
2217 static struct RegExMatchTestData
2219 const wxChar
*pattern
;
2222 } regExMatchTestData
[] =
2224 { _T("foo"), _T("bar"), FALSE
},
2225 { _T("foo"), _T("foobar"), TRUE
},
2226 { _T("^foo"), _T("foobar"), TRUE
},
2227 { _T("^foo"), _T("barfoo"), FALSE
},
2228 { _T("bar$"), _T("barbar"), TRUE
},
2229 { _T("bar$"), _T("barbar "), FALSE
},
2232 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2234 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2236 wxRegEx
re(data
.pattern
);
2237 bool ok
= re
.Matches(data
.text
);
2239 wxPrintf(_T("'%s' %s %s (%s)\n"),
2241 ok
? _T("matches") : _T("doesn't match"),
2243 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2247 static void TestRegExSubmatch()
2249 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2251 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2252 if ( !re
.IsValid() )
2254 wxPuts(_T("ERROR: compilation failed."));
2258 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2260 if ( !re
.Matches(text
) )
2262 wxPuts(_T("ERROR: match expected."));
2266 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2268 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2269 re
.GetMatch(text
, 3).c_str(),
2270 re
.GetMatch(text
, 2).c_str(),
2271 re
.GetMatch(text
, 4).c_str(),
2272 re
.GetMatch(text
, 1).c_str());
2276 static void TestRegExReplacement()
2278 wxPuts(_T("*** Testing RE replacement ***"));
2280 static struct RegExReplTestData
2284 const wxChar
*result
;
2286 } regExReplTestData
[] =
2288 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2289 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2290 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2291 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2292 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2293 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2294 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2297 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2298 wxRegEx
re(pattern
);
2300 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2302 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2304 const RegExReplTestData
& data
= regExReplTestData
[n
];
2306 wxString text
= data
.text
;
2307 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2309 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2310 data
.text
, data
.repl
,
2311 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2313 if ( text
== data
.result
&& nRepl
== data
.count
)
2319 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2320 data
.count
, data
.result
);
2325 static void TestRegExInteractive()
2327 wxPuts(_T("*** Testing RE interactively ***"));
2332 printf("\nEnter a pattern: ");
2333 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2336 // kill the last '\n'
2337 pattern
[strlen(pattern
) - 1] = 0;
2340 if ( !re
.Compile(pattern
) )
2348 printf("Enter text to match: ");
2349 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2352 // kill the last '\n'
2353 text
[strlen(text
) - 1] = 0;
2355 if ( !re
.Matches(text
) )
2357 printf("No match.\n");
2361 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2364 for ( size_t n
= 1; ; n
++ )
2366 if ( !re
.GetMatch(&start
, &len
, n
) )
2371 printf("Subexpr %u matched '%s'\n",
2372 n
, wxString(text
+ start
, len
).c_str());
2379 #endif // TEST_REGEX
2381 // ----------------------------------------------------------------------------
2383 // ----------------------------------------------------------------------------
2389 static void TestDbOpen()
2397 // ----------------------------------------------------------------------------
2398 // registry and related stuff
2399 // ----------------------------------------------------------------------------
2401 // this is for MSW only
2404 #undef TEST_REGISTRY
2409 #include "wx/confbase.h"
2410 #include "wx/msw/regconf.h"
2412 static void TestRegConfWrite()
2414 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2415 regconf
.Write(_T("Hello"), wxString(_T("world")));
2418 #endif // TEST_REGCONF
2420 #ifdef TEST_REGISTRY
2422 #include "wx/msw/registry.h"
2424 // I chose this one because I liked its name, but it probably only exists under
2426 static const wxChar
*TESTKEY
=
2427 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2429 static void TestRegistryRead()
2431 puts("*** testing registry reading ***");
2433 wxRegKey
key(TESTKEY
);
2434 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2437 puts("ERROR: test key can't be opened, aborting test.");
2442 size_t nSubKeys
, nValues
;
2443 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2445 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2448 printf("Enumerating values:\n");
2452 bool cont
= key
.GetFirstValue(value
, dummy
);
2455 printf("Value '%s': type ", value
.c_str());
2456 switch ( key
.GetValueType(value
) )
2458 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2459 case wxRegKey::Type_String
: printf("SZ"); break;
2460 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2461 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2462 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2463 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2464 default: printf("other (unknown)"); break;
2467 printf(", value = ");
2468 if ( key
.IsNumericValue(value
) )
2471 key
.QueryValue(value
, &val
);
2477 key
.QueryValue(value
, val
);
2478 printf("'%s'", val
.c_str());
2480 key
.QueryRawValue(value
, val
);
2481 printf(" (raw value '%s')", val
.c_str());
2486 cont
= key
.GetNextValue(value
, dummy
);
2490 static void TestRegistryAssociation()
2493 The second call to deleteself genertaes an error message, with a
2494 messagebox saying .flo is crucial to system operation, while the .ddf
2495 call also fails, but with no error message
2500 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2502 key
= "ddxf_auto_file" ;
2503 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2505 key
= "ddxf_auto_file" ;
2506 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2509 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2511 key
= "program \"%1\"" ;
2513 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2515 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2517 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2519 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2523 #endif // TEST_REGISTRY
2525 // ----------------------------------------------------------------------------
2527 // ----------------------------------------------------------------------------
2531 #include "wx/socket.h"
2532 #include "wx/protocol/protocol.h"
2533 #include "wx/protocol/http.h"
2535 static void TestSocketServer()
2537 puts("*** Testing wxSocketServer ***\n");
2539 static const int PORT
= 3000;
2544 wxSocketServer
*server
= new wxSocketServer(addr
);
2545 if ( !server
->Ok() )
2547 puts("ERROR: failed to bind");
2554 printf("Server: waiting for connection on port %d...\n", PORT
);
2556 wxSocketBase
*socket
= server
->Accept();
2559 puts("ERROR: wxSocketServer::Accept() failed.");
2563 puts("Server: got a client.");
2565 server
->SetTimeout(60); // 1 min
2567 while ( socket
->IsConnected() )
2573 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2575 // don't log error if the client just close the connection
2576 if ( socket
->IsConnected() )
2578 puts("ERROR: in wxSocket::Read.");
2598 printf("Server: got '%s'.\n", s
.c_str());
2599 if ( s
== _T("bye") )
2606 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2607 socket
->Write("\r\n", 2);
2608 printf("Server: wrote '%s'.\n", s
.c_str());
2611 puts("Server: lost a client.");
2616 // same as "delete server" but is consistent with GUI programs
2620 static void TestSocketClient()
2622 puts("*** Testing wxSocketClient ***\n");
2624 static const char *hostname
= "www.wxwindows.org";
2627 addr
.Hostname(hostname
);
2630 printf("--- Attempting to connect to %s:80...\n", hostname
);
2632 wxSocketClient client
;
2633 if ( !client
.Connect(addr
) )
2635 printf("ERROR: failed to connect to %s\n", hostname
);
2639 printf("--- Connected to %s:%u...\n",
2640 addr
.Hostname().c_str(), addr
.Service());
2644 // could use simply "GET" here I suppose
2646 wxString::Format("GET http://%s/\r\n", hostname
);
2647 client
.Write(cmdGet
, cmdGet
.length());
2648 printf("--- Sent command '%s' to the server\n",
2649 MakePrintable(cmdGet
).c_str());
2650 client
.Read(buf
, WXSIZEOF(buf
));
2651 printf("--- Server replied:\n%s", buf
);
2655 #endif // TEST_SOCKETS
2657 // ----------------------------------------------------------------------------
2659 // ----------------------------------------------------------------------------
2663 #include "wx/protocol/ftp.h"
2667 #define FTP_ANONYMOUS
2669 #ifdef FTP_ANONYMOUS
2670 static const char *directory
= "/pub";
2671 static const char *filename
= "welcome.msg";
2673 static const char *directory
= "/etc";
2674 static const char *filename
= "issue";
2677 static bool TestFtpConnect()
2679 puts("*** Testing FTP connect ***");
2681 #ifdef FTP_ANONYMOUS
2682 static const char *hostname
= "ftp.wxwindows.org";
2684 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2685 #else // !FTP_ANONYMOUS
2686 static const char *hostname
= "localhost";
2689 fgets(user
, WXSIZEOF(user
), stdin
);
2690 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2694 printf("Password for %s: ", password
);
2695 fgets(password
, WXSIZEOF(password
), stdin
);
2696 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2697 ftp
.SetPassword(password
);
2699 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2700 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2702 if ( !ftp
.Connect(hostname
) )
2704 printf("ERROR: failed to connect to %s\n", hostname
);
2710 printf("--- Connected to %s, current directory is '%s'\n",
2711 hostname
, ftp
.Pwd().c_str());
2717 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2718 static void TestFtpWuFtpd()
2721 static const char *hostname
= "ftp.eudora.com";
2722 if ( !ftp
.Connect(hostname
) )
2724 printf("ERROR: failed to connect to %s\n", hostname
);
2728 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2729 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2732 printf("ERROR: couldn't get input stream for %s\n", filename
);
2736 size_t size
= in
->StreamSize();
2737 printf("Reading file %s (%u bytes)...", filename
, size
);
2739 char *data
= new char[size
];
2740 if ( !in
->Read(data
, size
) )
2742 puts("ERROR: read error");
2746 printf("Successfully retrieved the file.\n");
2755 static void TestFtpList()
2757 puts("*** Testing wxFTP file listing ***\n");
2760 if ( !ftp
.ChDir(directory
) )
2762 printf("ERROR: failed to cd to %s\n", directory
);
2765 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2767 // test NLIST and LIST
2768 wxArrayString files
;
2769 if ( !ftp
.GetFilesList(files
) )
2771 puts("ERROR: failed to get NLIST of files");
2775 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2776 size_t count
= files
.GetCount();
2777 for ( size_t n
= 0; n
< count
; n
++ )
2779 printf("\t%s\n", files
[n
].c_str());
2781 puts("End of the file list");
2784 if ( !ftp
.GetDirList(files
) )
2786 puts("ERROR: failed to get LIST of files");
2790 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2791 size_t count
= files
.GetCount();
2792 for ( size_t n
= 0; n
< count
; n
++ )
2794 printf("\t%s\n", files
[n
].c_str());
2796 puts("End of the file list");
2799 if ( !ftp
.ChDir(_T("..")) )
2801 puts("ERROR: failed to cd to ..");
2804 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2807 static void TestFtpDownload()
2809 puts("*** Testing wxFTP download ***\n");
2812 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2815 printf("ERROR: couldn't get input stream for %s\n", filename
);
2819 size_t size
= in
->StreamSize();
2820 printf("Reading file %s (%u bytes)...", filename
, size
);
2823 char *data
= new char[size
];
2824 if ( !in
->Read(data
, size
) )
2826 puts("ERROR: read error");
2830 printf("\nContents of %s:\n%s\n", filename
, data
);
2838 static void TestFtpFileSize()
2840 puts("*** Testing FTP SIZE command ***");
2842 if ( !ftp
.ChDir(directory
) )
2844 printf("ERROR: failed to cd to %s\n", directory
);
2847 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2849 if ( ftp
.FileExists(filename
) )
2851 int size
= ftp
.GetFileSize(filename
);
2853 printf("ERROR: couldn't get size of '%s'\n", filename
);
2855 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2859 printf("ERROR: '%s' doesn't exist\n", filename
);
2863 static void TestFtpMisc()
2865 puts("*** Testing miscellaneous wxFTP functions ***");
2867 if ( ftp
.SendCommand("STAT") != '2' )
2869 puts("ERROR: STAT failed");
2873 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2876 if ( ftp
.SendCommand("HELP SITE") != '2' )
2878 puts("ERROR: HELP SITE failed");
2882 printf("The list of site-specific commands:\n\n%s\n",
2883 ftp
.GetLastResult().c_str());
2887 static void TestFtpInteractive()
2889 puts("\n*** Interactive wxFTP test ***");
2895 printf("Enter FTP command: ");
2896 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2899 // kill the last '\n'
2900 buf
[strlen(buf
) - 1] = 0;
2902 // special handling of LIST and NLST as they require data connection
2903 wxString
start(buf
, 4);
2905 if ( start
== "LIST" || start
== "NLST" )
2908 if ( strlen(buf
) > 4 )
2911 wxArrayString files
;
2912 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2914 printf("ERROR: failed to get %s of files\n", start
.c_str());
2918 printf("--- %s of '%s' under '%s':\n",
2919 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2920 size_t count
= files
.GetCount();
2921 for ( size_t n
= 0; n
< count
; n
++ )
2923 printf("\t%s\n", files
[n
].c_str());
2925 puts("--- End of the file list");
2930 char ch
= ftp
.SendCommand(buf
);
2931 printf("Command %s", ch
? "succeeded" : "failed");
2934 printf(" (return code %c)", ch
);
2937 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2941 puts("\n*** done ***");
2944 static void TestFtpUpload()
2946 puts("*** Testing wxFTP uploading ***\n");
2949 static const char *file1
= "test1";
2950 static const char *file2
= "test2";
2951 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2954 printf("--- Uploading to %s ---\n", file1
);
2955 out
->Write("First hello", 11);
2959 // send a command to check the remote file
2960 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2962 printf("ERROR: STAT %s failed\n", file1
);
2966 printf("STAT %s returned:\n\n%s\n",
2967 file1
, ftp
.GetLastResult().c_str());
2970 out
= ftp
.GetOutputStream(file2
);
2973 printf("--- Uploading to %s ---\n", file1
);
2974 out
->Write("Second hello", 12);
2981 // ----------------------------------------------------------------------------
2983 // ----------------------------------------------------------------------------
2987 #include "wx/wfstream.h"
2988 #include "wx/mstream.h"
2990 static void TestFileStream()
2992 puts("*** Testing wxFileInputStream ***");
2994 static const wxChar
*filename
= _T("testdata.fs");
2996 wxFileOutputStream
fsOut(filename
);
2997 fsOut
.Write("foo", 3);
3000 wxFileInputStream
fsIn(filename
);
3001 printf("File stream size: %u\n", fsIn
.GetSize());
3002 while ( !fsIn
.Eof() )
3004 putchar(fsIn
.GetC());
3007 if ( !wxRemoveFile(filename
) )
3009 printf("ERROR: failed to remove the file '%s'.\n", filename
);
3012 puts("\n*** wxFileInputStream test done ***");
3015 static void TestMemoryStream()
3017 puts("*** Testing wxMemoryInputStream ***");
3020 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
3022 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
3023 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
3024 while ( !memInpStream
.Eof() )
3026 putchar(memInpStream
.GetC());
3029 puts("\n*** wxMemoryInputStream test done ***");
3032 #endif // TEST_STREAMS
3034 // ----------------------------------------------------------------------------
3036 // ----------------------------------------------------------------------------
3040 #include "wx/timer.h"
3041 #include "wx/utils.h"
3043 static void TestStopWatch()
3045 puts("*** Testing wxStopWatch ***\n");
3049 printf("Initially paused, after 2 seconds time is...");
3052 printf("\t%ldms\n", sw
.Time());
3054 printf("Resuming stopwatch and sleeping 3 seconds...");
3058 printf("\telapsed time: %ldms\n", sw
.Time());
3061 printf("Pausing agan and sleeping 2 more seconds...");
3064 printf("\telapsed time: %ldms\n", sw
.Time());
3067 printf("Finally resuming and sleeping 2 more seconds...");
3070 printf("\telapsed time: %ldms\n", sw
.Time());
3073 puts("\nChecking for 'backwards clock' bug...");
3074 for ( size_t n
= 0; n
< 70; n
++ )
3078 for ( size_t m
= 0; m
< 100000; m
++ )
3080 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
3082 puts("\ntime is negative - ERROR!");
3093 #endif // TEST_TIMER
3095 // ----------------------------------------------------------------------------
3097 // ----------------------------------------------------------------------------
3101 #include "wx/vcard.h"
3103 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
3106 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
3110 wxString(_T('\t'), level
).c_str(),
3111 vcObj
->GetName().c_str());
3114 switch ( vcObj
->GetType() )
3116 case wxVCardObject::String
:
3117 case wxVCardObject::UString
:
3120 vcObj
->GetValue(&val
);
3121 value
<< _T('"') << val
<< _T('"');
3125 case wxVCardObject::Int
:
3128 vcObj
->GetValue(&i
);
3129 value
.Printf(_T("%u"), i
);
3133 case wxVCardObject::Long
:
3136 vcObj
->GetValue(&l
);
3137 value
.Printf(_T("%lu"), l
);
3141 case wxVCardObject::None
:
3144 case wxVCardObject::Object
:
3145 value
= _T("<node>");
3149 value
= _T("<unknown value type>");
3153 printf(" = %s", value
.c_str());
3156 DumpVObject(level
+ 1, *vcObj
);
3159 vcObj
= vcard
.GetNextProp(&cookie
);
3163 static void DumpVCardAddresses(const wxVCard
& vcard
)
3165 puts("\nShowing all addresses from vCard:\n");
3169 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
3173 int flags
= addr
->GetFlags();
3174 if ( flags
& wxVCardAddress::Domestic
)
3176 flagsStr
<< _T("domestic ");
3178 if ( flags
& wxVCardAddress::Intl
)
3180 flagsStr
<< _T("international ");
3182 if ( flags
& wxVCardAddress::Postal
)
3184 flagsStr
<< _T("postal ");
3186 if ( flags
& wxVCardAddress::Parcel
)
3188 flagsStr
<< _T("parcel ");
3190 if ( flags
& wxVCardAddress::Home
)
3192 flagsStr
<< _T("home ");
3194 if ( flags
& wxVCardAddress::Work
)
3196 flagsStr
<< _T("work ");
3199 printf("Address %u:\n"
3201 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
3204 addr
->GetPostOffice().c_str(),
3205 addr
->GetExtAddress().c_str(),
3206 addr
->GetStreet().c_str(),
3207 addr
->GetLocality().c_str(),
3208 addr
->GetRegion().c_str(),
3209 addr
->GetPostalCode().c_str(),
3210 addr
->GetCountry().c_str()
3214 addr
= vcard
.GetNextAddress(&cookie
);
3218 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3220 puts("\nShowing all phone numbers from vCard:\n");
3224 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3228 int flags
= phone
->GetFlags();
3229 if ( flags
& wxVCardPhoneNumber::Voice
)
3231 flagsStr
<< _T("voice ");
3233 if ( flags
& wxVCardPhoneNumber::Fax
)
3235 flagsStr
<< _T("fax ");
3237 if ( flags
& wxVCardPhoneNumber::Cellular
)
3239 flagsStr
<< _T("cellular ");
3241 if ( flags
& wxVCardPhoneNumber::Modem
)
3243 flagsStr
<< _T("modem ");
3245 if ( flags
& wxVCardPhoneNumber::Home
)
3247 flagsStr
<< _T("home ");
3249 if ( flags
& wxVCardPhoneNumber::Work
)
3251 flagsStr
<< _T("work ");
3254 printf("Phone number %u:\n"
3259 phone
->GetNumber().c_str()
3263 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3267 static void TestVCardRead()
3269 puts("*** Testing wxVCard reading ***\n");
3271 wxVCard
vcard(_T("vcard.vcf"));
3272 if ( !vcard
.IsOk() )
3274 puts("ERROR: couldn't load vCard.");
3278 // read individual vCard properties
3279 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3283 vcObj
->GetValue(&value
);
3288 value
= _T("<none>");
3291 printf("Full name retrieved directly: %s\n", value
.c_str());
3294 if ( !vcard
.GetFullName(&value
) )
3296 value
= _T("<none>");
3299 printf("Full name from wxVCard API: %s\n", value
.c_str());
3301 // now show how to deal with multiply occuring properties
3302 DumpVCardAddresses(vcard
);
3303 DumpVCardPhoneNumbers(vcard
);
3305 // and finally show all
3306 puts("\nNow dumping the entire vCard:\n"
3307 "-----------------------------\n");
3309 DumpVObject(0, vcard
);
3313 static void TestVCardWrite()
3315 puts("*** Testing wxVCard writing ***\n");
3318 if ( !vcard
.IsOk() )
3320 puts("ERROR: couldn't create vCard.");
3325 vcard
.SetName("Zeitlin", "Vadim");
3326 vcard
.SetFullName("Vadim Zeitlin");
3327 vcard
.SetOrganization("wxWindows", "R&D");
3329 // just dump the vCard back
3330 puts("Entire vCard follows:\n");
3331 puts(vcard
.Write());
3335 #endif // TEST_VCARD
3337 // ----------------------------------------------------------------------------
3339 // ----------------------------------------------------------------------------
3347 #include "wx/volume.h"
3349 static const wxChar
*volumeKinds
[] =
3355 _T("network volume"),
3359 static void TestFSVolume()
3361 wxPuts(_T("*** Testing wxFSVolume class ***"));
3363 wxArrayString volumes
= wxFSVolume::GetVolumes();
3364 size_t count
= volumes
.GetCount();
3368 wxPuts(_T("ERROR: no mounted volumes?"));
3372 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3374 for ( size_t n
= 0; n
< count
; n
++ )
3376 wxFSVolume
vol(volumes
[n
]);
3379 wxPuts(_T("ERROR: couldn't create volume"));
3383 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3385 vol
.GetDisplayName().c_str(),
3386 vol
.GetName().c_str(),
3387 volumeKinds
[vol
.GetKind()],
3388 vol
.IsWritable() ? _T("rw") : _T("ro"),
3389 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3394 #endif // TEST_VOLUME
3396 // ----------------------------------------------------------------------------
3397 // wide char (Unicode) support
3398 // ----------------------------------------------------------------------------
3402 #include "wx/strconv.h"
3403 #include "wx/fontenc.h"
3404 #include "wx/encconv.h"
3405 #include "wx/buffer.h"
3407 static const char textInUtf8
[] =
3409 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3410 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3411 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3412 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3413 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3414 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3415 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3418 static void TestUtf8()
3420 puts("*** Testing UTF8 support ***\n");
3424 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3426 puts("ERROR: UTF-8 decoding failed.");
3430 wxCSConv
conv(_T("koi8-r"));
3431 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3433 puts("ERROR: conversion to KOI8-R failed.");
3437 printf("The resulting string (in KOI8-R): %s\n", buf
);
3441 if ( wxConvUTF8
.WC2MB(buf
, L
"Ã la", WXSIZEOF(buf
)) <= 0 )
3443 puts("ERROR: conversion to UTF-8 failed.");
3447 printf("The string in UTF-8: %s\n", buf
);
3453 static void TestEncodingConverter()
3455 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3457 // using wxEncodingConverter should give the same result as above
3460 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3462 puts("ERROR: UTF-8 decoding failed.");
3466 wxEncodingConverter ec
;
3467 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3468 ec
.Convert(wbuf
, buf
);
3469 printf("The same string obtained using wxEC: %s\n", buf
);
3475 #endif // TEST_WCHAR
3477 // ----------------------------------------------------------------------------
3479 // ----------------------------------------------------------------------------
3483 #include "wx/filesys.h"
3484 #include "wx/fs_zip.h"
3485 #include "wx/zipstrm.h"
3487 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3489 static void TestZipStreamRead()
3491 puts("*** Testing ZIP reading ***\n");
3493 static const wxChar
*filename
= _T("foo");
3494 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3495 printf("Archive size: %u\n", istr
.GetSize());
3497 printf("Dumping the file '%s':\n", filename
);
3498 while ( !istr
.Eof() )
3500 putchar(istr
.GetC());
3504 puts("\n----- done ------");
3507 static void DumpZipDirectory(wxFileSystem
& fs
,
3508 const wxString
& dir
,
3509 const wxString
& indent
)
3511 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3512 TESTFILE_ZIP
, dir
.c_str());
3513 wxString wildcard
= prefix
+ _T("/*");
3515 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3516 while ( !dirname
.empty() )
3518 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3520 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3525 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3527 DumpZipDirectory(fs
, dirname
,
3528 indent
+ wxString(_T(' '), 4));
3530 dirname
= fs
.FindNext();
3533 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3534 while ( !filename
.empty() )
3536 if ( !filename
.StartsWith(prefix
, &filename
) )
3538 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3543 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3545 filename
= fs
.FindNext();
3549 static void TestZipFileSystem()
3551 puts("*** Testing ZIP file system ***\n");
3553 wxFileSystem::AddHandler(new wxZipFSHandler
);
3555 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3557 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3562 // ----------------------------------------------------------------------------
3564 // ----------------------------------------------------------------------------
3568 #include "wx/zstream.h"
3569 #include "wx/wfstream.h"
3571 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3572 static const char *TEST_DATA
= "hello and hello again";
3574 static void TestZlibStreamWrite()
3576 puts("*** Testing Zlib stream reading ***\n");
3578 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3579 wxZlibOutputStream
ostr(fileOutStream
, 0);
3580 printf("Compressing the test string... ");
3581 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3584 puts("(ERROR: failed)");
3591 puts("\n----- done ------");
3594 static void TestZlibStreamRead()
3596 puts("*** Testing Zlib stream reading ***\n");
3598 wxFileInputStream
fileInStream(FILENAME_GZ
);
3599 wxZlibInputStream
istr(fileInStream
);
3600 printf("Archive size: %u\n", istr
.GetSize());
3602 puts("Dumping the file:");
3603 while ( !istr
.Eof() )
3605 putchar(istr
.GetC());
3609 puts("\n----- done ------");
3614 // ----------------------------------------------------------------------------
3616 // ----------------------------------------------------------------------------
3618 #ifdef TEST_DATETIME
3622 #include "wx/date.h"
3623 #include "wx/datetime.h"
3628 wxDateTime::wxDateTime_t day
;
3629 wxDateTime::Month month
;
3631 wxDateTime::wxDateTime_t hour
, min
, sec
;
3633 wxDateTime::WeekDay wday
;
3634 time_t gmticks
, ticks
;
3636 void Init(const wxDateTime::Tm
& tm
)
3645 gmticks
= ticks
= -1;
3648 wxDateTime
DT() const
3649 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3651 bool SameDay(const wxDateTime::Tm
& tm
) const
3653 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3656 wxString
Format() const
3659 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3661 wxDateTime::GetMonthName(month
).c_str(),
3663 abs(wxDateTime::ConvertYearToBC(year
)),
3664 year
> 0 ? "AD" : "BC");
3668 wxString
FormatDate() const
3671 s
.Printf("%02d-%s-%4d%s",
3673 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3674 abs(wxDateTime::ConvertYearToBC(year
)),
3675 year
> 0 ? "AD" : "BC");
3680 static const Date testDates
[] =
3682 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3683 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3684 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3685 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3686 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3687 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3688 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3689 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3690 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3691 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3692 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3693 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3694 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3695 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3696 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3699 // this test miscellaneous static wxDateTime functions
3700 static void TestTimeStatic()
3702 puts("\n*** wxDateTime static methods test ***");
3704 // some info about the current date
3705 int year
= wxDateTime::GetCurrentYear();
3706 printf("Current year %d is %sa leap one and has %d days.\n",
3708 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3709 wxDateTime::GetNumberOfDays(year
));
3711 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3712 printf("Current month is '%s' ('%s') and it has %d days\n",
3713 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3714 wxDateTime::GetMonthName(month
).c_str(),
3715 wxDateTime::GetNumberOfDays(month
));
3718 static const size_t nYears
= 5;
3719 static const size_t years
[2][nYears
] =
3721 // first line: the years to test
3722 { 1990, 1976, 2000, 2030, 1984, },
3724 // second line: TRUE if leap, FALSE otherwise
3725 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3728 for ( size_t n
= 0; n
< nYears
; n
++ )
3730 int year
= years
[0][n
];
3731 bool should
= years
[1][n
] != 0,
3732 is
= wxDateTime::IsLeapYear(year
);
3734 printf("Year %d is %sa leap year (%s)\n",
3737 should
== is
? "ok" : "ERROR");
3739 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3743 // test constructing wxDateTime objects
3744 static void TestTimeSet()
3746 puts("\n*** wxDateTime construction test ***");
3748 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3750 const Date
& d1
= testDates
[n
];
3751 wxDateTime dt
= d1
.DT();
3754 d2
.Init(dt
.GetTm());
3756 wxString s1
= d1
.Format(),
3759 printf("Date: %s == %s (%s)\n",
3760 s1
.c_str(), s2
.c_str(),
3761 s1
== s2
? "ok" : "ERROR");
3765 // test time zones stuff
3766 static void TestTimeZones()
3768 puts("\n*** wxDateTime timezone test ***");
3770 wxDateTime now
= wxDateTime::Now();
3772 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3773 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3774 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3775 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3776 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3777 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3779 wxDateTime::Tm tm
= now
.GetTm();
3780 if ( wxDateTime(tm
) != now
)
3782 printf("ERROR: got %s instead of %s\n",
3783 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3787 // test some minimal support for the dates outside the standard range
3788 static void TestTimeRange()
3790 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3792 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3794 printf("Unix epoch:\t%s\n",
3795 wxDateTime(2440587.5).Format(fmt
).c_str());
3796 printf("Feb 29, 0: \t%s\n",
3797 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3798 printf("JDN 0: \t%s\n",
3799 wxDateTime(0.0).Format(fmt
).c_str());
3800 printf("Jan 1, 1AD:\t%s\n",
3801 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3802 printf("May 29, 2099:\t%s\n",
3803 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3806 static void TestTimeTicks()
3808 puts("\n*** wxDateTime ticks test ***");
3810 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3812 const Date
& d
= testDates
[n
];
3813 if ( d
.ticks
== -1 )
3816 wxDateTime dt
= d
.DT();
3817 long ticks
= (dt
.GetValue() / 1000).ToLong();
3818 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3819 if ( ticks
== d
.ticks
)
3825 printf(" (ERROR: should be %ld, delta = %ld)\n",
3826 d
.ticks
, ticks
- d
.ticks
);
3829 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3830 ticks
= (dt
.GetValue() / 1000).ToLong();
3831 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3832 if ( ticks
== d
.gmticks
)
3838 printf(" (ERROR: should be %ld, delta = %ld)\n",
3839 d
.gmticks
, ticks
- d
.gmticks
);
3846 // test conversions to JDN &c
3847 static void TestTimeJDN()
3849 puts("\n*** wxDateTime to JDN test ***");
3851 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3853 const Date
& d
= testDates
[n
];
3854 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3855 double jdn
= dt
.GetJulianDayNumber();
3857 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3864 printf(" (ERROR: should be %f, delta = %f)\n",
3865 d
.jdn
, jdn
- d
.jdn
);
3870 // test week days computation
3871 static void TestTimeWDays()
3873 puts("\n*** wxDateTime weekday test ***");
3875 // test GetWeekDay()
3877 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3879 const Date
& d
= testDates
[n
];
3880 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3882 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3885 wxDateTime::GetWeekDayName(wday
).c_str());
3886 if ( wday
== d
.wday
)
3892 printf(" (ERROR: should be %s)\n",
3893 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3899 // test SetToWeekDay()
3900 struct WeekDateTestData
3902 Date date
; // the real date (precomputed)
3903 int nWeek
; // its week index in the month
3904 wxDateTime::WeekDay wday
; // the weekday
3905 wxDateTime::Month month
; // the month
3906 int year
; // and the year
3908 wxString
Format() const
3911 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3913 case 1: which
= "first"; break;
3914 case 2: which
= "second"; break;
3915 case 3: which
= "third"; break;
3916 case 4: which
= "fourth"; break;
3917 case 5: which
= "fifth"; break;
3919 case -1: which
= "last"; break;
3924 which
+= " from end";
3927 s
.Printf("The %s %s of %s in %d",
3929 wxDateTime::GetWeekDayName(wday
).c_str(),
3930 wxDateTime::GetMonthName(month
).c_str(),
3937 // the array data was generated by the following python program
3939 from DateTime import *
3940 from whrandom import *
3941 from string import *
3943 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3944 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3946 week = DateTimeDelta(7)
3949 year = randint(1900, 2100)
3950 month = randint(1, 12)
3951 day = randint(1, 28)
3952 dt = DateTime(year, month, day)
3953 wday = dt.day_of_week
3955 countFromEnd = choice([-1, 1])
3958 while dt.month is month:
3959 dt = dt - countFromEnd * week
3960 weekNum = weekNum + countFromEnd
3962 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3964 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3965 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3968 static const WeekDateTestData weekDatesTestData
[] =
3970 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3971 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3972 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3973 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3974 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3975 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3976 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3977 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3978 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3979 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3980 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3981 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3982 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3983 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3984 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3985 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3986 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3987 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3988 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3989 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3992 static const char *fmt
= "%d-%b-%Y";
3995 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3997 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3999 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
4001 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
4003 const Date
& d
= wd
.date
;
4004 if ( d
.SameDay(dt
.GetTm()) )
4010 dt
.Set(d
.day
, d
.month
, d
.year
);
4012 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
4017 // test the computation of (ISO) week numbers
4018 static void TestTimeWNumber()
4020 puts("\n*** wxDateTime week number test ***");
4022 struct WeekNumberTestData
4024 Date date
; // the date
4025 wxDateTime::wxDateTime_t week
; // the week number in the year
4026 wxDateTime::wxDateTime_t wmon
; // the week number in the month
4027 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
4028 wxDateTime::wxDateTime_t dnum
; // day number in the year
4031 // data generated with the following python script:
4033 from DateTime import *
4034 from whrandom import *
4035 from string import *
4037 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
4038 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
4040 def GetMonthWeek(dt):
4041 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
4042 if weekNumMonth < 0:
4043 weekNumMonth = weekNumMonth + 53
4046 def GetLastSundayBefore(dt):
4047 if dt.iso_week[2] == 7:
4050 return dt - DateTimeDelta(dt.iso_week[2])
4053 year = randint(1900, 2100)
4054 month = randint(1, 12)
4055 day = randint(1, 28)
4056 dt = DateTime(year, month, day)
4057 dayNum = dt.day_of_year
4058 weekNum = dt.iso_week[1]
4059 weekNumMonth = GetMonthWeek(dt)
4062 dtSunday = GetLastSundayBefore(dt)
4064 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
4065 weekNumMonth2 = weekNumMonth2 + 1
4066 dtSunday = dtSunday - DateTimeDelta(7)
4068 data = { 'day': rjust(`day`, 2), \
4069 'month': monthNames[month - 1], \
4071 'weekNum': rjust(`weekNum`, 2), \
4072 'weekNumMonth': weekNumMonth, \
4073 'weekNumMonth2': weekNumMonth2, \
4074 'dayNum': rjust(`dayNum`, 3) }
4076 print " { { %(day)s, "\
4077 "wxDateTime::%(month)s, "\
4080 "%(weekNumMonth)s, "\
4081 "%(weekNumMonth2)s, "\
4082 "%(dayNum)s }," % data
4085 static const WeekNumberTestData weekNumberTestDates
[] =
4087 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
4088 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
4089 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
4090 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
4091 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
4092 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
4093 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
4094 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
4095 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
4096 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
4097 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
4098 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
4099 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
4100 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
4101 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
4102 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
4103 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
4104 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
4105 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
4106 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
4109 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
4111 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
4112 const Date
& d
= wn
.date
;
4114 wxDateTime dt
= d
.DT();
4116 wxDateTime::wxDateTime_t
4117 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
4118 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4119 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4120 dnum
= dt
.GetDayOfYear();
4122 printf("%s: the day number is %d",
4123 d
.FormatDate().c_str(), dnum
);
4124 if ( dnum
== wn
.dnum
)
4130 printf(" (ERROR: should be %d)", wn
.dnum
);
4133 printf(", week in month is %d", wmon
);
4134 if ( wmon
== wn
.wmon
)
4140 printf(" (ERROR: should be %d)", wn
.wmon
);
4143 printf(" or %d", wmon2
);
4144 if ( wmon2
== wn
.wmon2
)
4150 printf(" (ERROR: should be %d)", wn
.wmon2
);
4153 printf(", week in year is %d", week
);
4154 if ( week
== wn
.week
)
4160 printf(" (ERROR: should be %d)\n", wn
.week
);
4165 // test DST calculations
4166 static void TestTimeDST()
4168 puts("\n*** wxDateTime DST test ***");
4170 printf("DST is%s in effect now.\n\n",
4171 wxDateTime::Now().IsDST() ? "" : " not");
4173 // taken from http://www.energy.ca.gov/daylightsaving.html
4174 static const Date datesDST
[2][2004 - 1900 + 1] =
4177 { 1, wxDateTime::Apr
, 1990 },
4178 { 7, wxDateTime::Apr
, 1991 },
4179 { 5, wxDateTime::Apr
, 1992 },
4180 { 4, wxDateTime::Apr
, 1993 },
4181 { 3, wxDateTime::Apr
, 1994 },
4182 { 2, wxDateTime::Apr
, 1995 },
4183 { 7, wxDateTime::Apr
, 1996 },
4184 { 6, wxDateTime::Apr
, 1997 },
4185 { 5, wxDateTime::Apr
, 1998 },
4186 { 4, wxDateTime::Apr
, 1999 },
4187 { 2, wxDateTime::Apr
, 2000 },
4188 { 1, wxDateTime::Apr
, 2001 },
4189 { 7, wxDateTime::Apr
, 2002 },
4190 { 6, wxDateTime::Apr
, 2003 },
4191 { 4, wxDateTime::Apr
, 2004 },
4194 { 28, wxDateTime::Oct
, 1990 },
4195 { 27, wxDateTime::Oct
, 1991 },
4196 { 25, wxDateTime::Oct
, 1992 },
4197 { 31, wxDateTime::Oct
, 1993 },
4198 { 30, wxDateTime::Oct
, 1994 },
4199 { 29, wxDateTime::Oct
, 1995 },
4200 { 27, wxDateTime::Oct
, 1996 },
4201 { 26, wxDateTime::Oct
, 1997 },
4202 { 25, wxDateTime::Oct
, 1998 },
4203 { 31, wxDateTime::Oct
, 1999 },
4204 { 29, wxDateTime::Oct
, 2000 },
4205 { 28, wxDateTime::Oct
, 2001 },
4206 { 27, wxDateTime::Oct
, 2002 },
4207 { 26, wxDateTime::Oct
, 2003 },
4208 { 31, wxDateTime::Oct
, 2004 },
4213 for ( year
= 1990; year
< 2005; year
++ )
4215 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
4216 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
4218 printf("DST period in the US for year %d: from %s to %s",
4219 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
4221 size_t n
= year
- 1990;
4222 const Date
& dBegin
= datesDST
[0][n
];
4223 const Date
& dEnd
= datesDST
[1][n
];
4225 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
4231 printf(" (ERROR: should be %s %d to %s %d)\n",
4232 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
4233 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
4239 for ( year
= 1990; year
< 2005; year
++ )
4241 printf("DST period in Europe for year %d: from %s to %s\n",
4243 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
4244 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
4248 // test wxDateTime -> text conversion
4249 static void TestTimeFormat()
4251 puts("\n*** wxDateTime formatting test ***");
4253 // some information may be lost during conversion, so store what kind
4254 // of info should we recover after a round trip
4257 CompareNone
, // don't try comparing
4258 CompareBoth
, // dates and times should be identical
4259 CompareDate
, // dates only
4260 CompareTime
// time only
4265 CompareKind compareKind
;
4267 } formatTestFormats
[] =
4269 { CompareBoth
, "---> %c" },
4270 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
4271 { CompareBoth
, "Date is %x, time is %X" },
4272 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
4273 { CompareNone
, "The day of year: %j, the week of year: %W" },
4274 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
4277 static const Date formatTestDates
[] =
4279 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
4280 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
4282 // this test can't work for other centuries because it uses two digit
4283 // years in formats, so don't even try it
4284 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
4285 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
4286 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
4290 // an extra test (as it doesn't depend on date, don't do it in the loop)
4291 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4293 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4297 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4298 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4300 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4301 printf("%s", s
.c_str());
4303 // what can we recover?
4304 int kind
= formatTestFormats
[n
].compareKind
;
4308 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4311 // converion failed - should it have?
4312 if ( kind
== CompareNone
)
4315 puts(" (ERROR: conversion back failed)");
4319 // should have parsed the entire string
4320 puts(" (ERROR: conversion back stopped too soon)");
4324 bool equal
= FALSE
; // suppress compilaer warning
4332 equal
= dt
.IsSameDate(dt2
);
4336 equal
= dt
.IsSameTime(dt2
);
4342 printf(" (ERROR: got back '%s' instead of '%s')\n",
4343 dt2
.Format().c_str(), dt
.Format().c_str());
4354 // test text -> wxDateTime conversion
4355 static void TestTimeParse()
4357 puts("\n*** wxDateTime parse test ***");
4359 struct ParseTestData
4366 static const ParseTestData parseTestDates
[] =
4368 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4369 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4372 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4374 const char *format
= parseTestDates
[n
].format
;
4376 printf("%s => ", format
);
4379 if ( dt
.ParseRfc822Date(format
) )
4381 printf("%s ", dt
.Format().c_str());
4383 if ( parseTestDates
[n
].good
)
4385 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4392 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4397 puts("(ERROR: bad format)");
4402 printf("bad format (%s)\n",
4403 parseTestDates
[n
].good
? "ERROR" : "ok");
4408 static void TestDateTimeInteractive()
4410 puts("\n*** interactive wxDateTime tests ***");
4416 printf("Enter a date: ");
4417 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4420 // kill the last '\n'
4421 buf
[strlen(buf
) - 1] = 0;
4424 const char *p
= dt
.ParseDate(buf
);
4427 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4433 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4436 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4437 dt
.Format("%b %d, %Y").c_str(),
4439 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4440 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4441 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4444 puts("\n*** done ***");
4447 static void TestTimeMS()
4449 puts("*** testing millisecond-resolution support in wxDateTime ***");
4451 wxDateTime dt1
= wxDateTime::Now(),
4452 dt2
= wxDateTime::UNow();
4454 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4455 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4456 printf("Dummy loop: ");
4457 for ( int i
= 0; i
< 6000; i
++ )
4459 //for ( int j = 0; j < 10; j++ )
4462 s
.Printf("%g", sqrt(i
));
4471 dt2
= wxDateTime::UNow();
4472 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4474 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4476 puts("\n*** done ***");
4479 static void TestTimeArithmetics()
4481 puts("\n*** testing arithmetic operations on wxDateTime ***");
4483 static const struct ArithmData
4485 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4486 : span(sp
), name(nam
) { }
4490 } testArithmData
[] =
4492 ArithmData(wxDateSpan::Day(), "day"),
4493 ArithmData(wxDateSpan::Week(), "week"),
4494 ArithmData(wxDateSpan::Month(), "month"),
4495 ArithmData(wxDateSpan::Year(), "year"),
4496 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4499 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4501 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4503 wxDateSpan span
= testArithmData
[n
].span
;
4507 const char *name
= testArithmData
[n
].name
;
4508 printf("%s + %s = %s, %s - %s = %s\n",
4509 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4510 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4512 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4513 if ( dt1
- span
== dt
)
4519 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4522 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4523 if ( dt2
+ span
== dt
)
4529 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4532 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4533 if ( dt2
+ 2*span
== dt1
)
4539 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4546 static void TestTimeHolidays()
4548 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4550 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4551 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4552 dtEnd
= dtStart
.GetLastMonthDay();
4554 wxDateTimeArray hol
;
4555 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4557 const wxChar
*format
= "%d-%b-%Y (%a)";
4559 printf("All holidays between %s and %s:\n",
4560 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4562 size_t count
= hol
.GetCount();
4563 for ( size_t n
= 0; n
< count
; n
++ )
4565 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4571 static void TestTimeZoneBug()
4573 puts("\n*** testing for DST/timezone bug ***\n");
4575 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4576 for ( int i
= 0; i
< 31; i
++ )
4578 printf("Date %s: week day %s.\n",
4579 date
.Format(_T("%d-%m-%Y")).c_str(),
4580 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4582 date
+= wxDateSpan::Day();
4588 static void TestTimeSpanFormat()
4590 puts("\n*** wxTimeSpan tests ***");
4592 static const char *formats
[] =
4594 _T("(default) %H:%M:%S"),
4595 _T("%E weeks and %D days"),
4596 _T("%l milliseconds"),
4597 _T("(with ms) %H:%M:%S:%l"),
4598 _T("100%% of minutes is %M"), // test "%%"
4599 _T("%D days and %H hours"),
4600 _T("or also %S seconds"),
4603 wxTimeSpan
ts1(1, 2, 3, 4),
4605 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4607 printf("ts1 = %s\tts2 = %s\n",
4608 ts1
.Format(formats
[n
]).c_str(),
4609 ts2
.Format(formats
[n
]).c_str());
4617 // test compatibility with the old wxDate/wxTime classes
4618 static void TestTimeCompatibility()
4620 puts("\n*** wxDateTime compatibility test ***");
4622 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4623 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4625 double jdnNow
= wxDateTime::Now().GetJDN();
4626 long jdnMidnight
= (long)(jdnNow
- 0.5);
4627 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4629 jdnMidnight
= wxDate().Set().GetJulianDate();
4630 printf("wxDateTime for today: %s\n",
4631 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4633 int flags
= wxEUROPEAN
;//wxFULL;
4636 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4637 for ( int n
= 0; n
< 7; n
++ )
4639 printf("Previous %s is %s\n",
4640 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4641 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4647 #endif // TEST_DATETIME
4649 // ----------------------------------------------------------------------------
4651 // ----------------------------------------------------------------------------
4655 #include "wx/thread.h"
4657 static size_t gs_counter
= (size_t)-1;
4658 static wxCriticalSection gs_critsect
;
4659 static wxSemaphore gs_cond
;
4661 class MyJoinableThread
: public wxThread
4664 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4665 { m_n
= n
; Create(); }
4667 // thread execution starts here
4668 virtual ExitCode
Entry();
4674 wxThread::ExitCode
MyJoinableThread::Entry()
4676 unsigned long res
= 1;
4677 for ( size_t n
= 1; n
< m_n
; n
++ )
4681 // it's a loooong calculation :-)
4685 return (ExitCode
)res
;
4688 class MyDetachedThread
: public wxThread
4691 MyDetachedThread(size_t n
, char ch
)
4695 m_cancelled
= FALSE
;
4700 // thread execution starts here
4701 virtual ExitCode
Entry();
4704 virtual void OnExit();
4707 size_t m_n
; // number of characters to write
4708 char m_ch
; // character to write
4710 bool m_cancelled
; // FALSE if we exit normally
4713 wxThread::ExitCode
MyDetachedThread::Entry()
4716 wxCriticalSectionLocker
lock(gs_critsect
);
4717 if ( gs_counter
== (size_t)-1 )
4723 for ( size_t n
= 0; n
< m_n
; n
++ )
4725 if ( TestDestroy() )
4735 wxThread::Sleep(100);
4741 void MyDetachedThread::OnExit()
4743 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4745 wxCriticalSectionLocker
lock(gs_critsect
);
4746 if ( !--gs_counter
&& !m_cancelled
)
4750 static void TestDetachedThreads()
4752 puts("\n*** Testing detached threads ***");
4754 static const size_t nThreads
= 3;
4755 MyDetachedThread
*threads
[nThreads
];
4757 for ( n
= 0; n
< nThreads
; n
++ )
4759 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4762 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4763 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4765 for ( n
= 0; n
< nThreads
; n
++ )
4770 // wait until all threads terminate
4776 static void TestJoinableThreads()
4778 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4780 // calc 10! in the background
4781 MyJoinableThread
thread(10);
4784 printf("\nThread terminated with exit code %lu.\n",
4785 (unsigned long)thread
.Wait());
4788 static void TestThreadSuspend()
4790 puts("\n*** Testing thread suspend/resume functions ***");
4792 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4796 // this is for this demo only, in a real life program we'd use another
4797 // condition variable which would be signaled from wxThread::Entry() to
4798 // tell us that the thread really started running - but here just wait a
4799 // bit and hope that it will be enough (the problem is, of course, that
4800 // the thread might still not run when we call Pause() which will result
4802 wxThread::Sleep(300);
4804 for ( size_t n
= 0; n
< 3; n
++ )
4808 puts("\nThread suspended");
4811 // don't sleep but resume immediately the first time
4812 wxThread::Sleep(300);
4814 puts("Going to resume the thread");
4819 puts("Waiting until it terminates now");
4821 // wait until the thread terminates
4827 static void TestThreadDelete()
4829 // As above, using Sleep() is only for testing here - we must use some
4830 // synchronisation object instead to ensure that the thread is still
4831 // running when we delete it - deleting a detached thread which already
4832 // terminated will lead to a crash!
4834 puts("\n*** Testing thread delete function ***");
4836 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4840 puts("\nDeleted a thread which didn't start to run yet.");
4842 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4846 wxThread::Sleep(300);
4850 puts("\nDeleted a running thread.");
4852 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4856 wxThread::Sleep(300);
4862 puts("\nDeleted a sleeping thread.");
4864 MyJoinableThread
thread3(20);
4869 puts("\nDeleted a joinable thread.");
4871 MyJoinableThread
thread4(2);
4874 wxThread::Sleep(300);
4878 puts("\nDeleted a joinable thread which already terminated.");
4883 class MyWaitingThread
: public wxThread
4886 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
4889 m_condition
= condition
;
4894 virtual ExitCode
Entry()
4896 printf("Thread %lu has started running.\n", GetId());
4901 printf("Thread %lu starts to wait...\n", GetId());
4905 m_condition
->Wait();
4908 printf("Thread %lu finished to wait, exiting.\n", GetId());
4916 wxCondition
*m_condition
;
4919 static void TestThreadConditions()
4922 wxCondition
condition(mutex
);
4924 // otherwise its difficult to understand which log messages pertain to
4926 //wxLogTrace("thread", "Local condition var is %08x, gs_cond = %08x",
4927 // condition.GetId(), gs_cond.GetId());
4929 // create and launch threads
4930 MyWaitingThread
*threads
[10];
4933 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4935 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
4938 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
4943 // wait until all threads run
4944 puts("Main thread is waiting for the other threads to start");
4947 size_t nRunning
= 0;
4948 while ( nRunning
< WXSIZEOF(threads
) )
4954 printf("Main thread: %u already running\n", nRunning
);
4958 puts("Main thread: all threads started up.");
4961 wxThread::Sleep(500);
4964 // now wake one of them up
4965 printf("Main thread: about to signal the condition.\n");
4970 wxThread::Sleep(200);
4972 // wake all the (remaining) threads up, so that they can exit
4973 printf("Main thread: about to broadcast the condition.\n");
4975 condition
.Broadcast();
4977 // give them time to terminate (dirty!)
4978 wxThread::Sleep(500);
4981 #include "wx/utils.h"
4983 class MyExecThread
: public wxThread
4986 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
4992 virtual ExitCode
Entry()
4994 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
5001 static void TestThreadExec()
5003 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
5005 MyExecThread
thread(_T("true"));
5008 wxPrintf(_T("Main program exit code: %ld.\n"),
5009 wxExecute(_T("false"), wxEXEC_SYNC
));
5011 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
5015 #include "wx/datetime.h"
5017 class MySemaphoreThread
: public wxThread
5020 MySemaphoreThread(int i
, wxSemaphore
*sem
)
5021 : wxThread(wxTHREAD_JOINABLE
),
5028 virtual ExitCode
Entry()
5030 wxPrintf(_T("%s: Thread %d starting to wait for semaphore...\n"),
5031 wxDateTime::Now().FormatTime().c_str(), m_i
);
5035 wxPrintf(_T("%s: Thread %d acquired the semaphore.\n"),
5036 wxDateTime::Now().FormatTime().c_str(), m_i
);
5040 wxPrintf(_T("%s: Thread %d releasing the semaphore.\n"),
5041 wxDateTime::Now().FormatTime().c_str(), m_i
);
5053 WX_DEFINE_ARRAY(wxThread
*, ArrayThreads
);
5055 static void TestSemaphore()
5057 wxPuts(_T("*** Testing wxSemaphore class. ***"));
5059 static const int SEM_LIMIT
= 3;
5061 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
5062 ArrayThreads threads
;
5064 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
5066 threads
.Add(new MySemaphoreThread(i
, &sem
));
5067 threads
.Last()->Run();
5070 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
5077 #endif // TEST_THREADS
5079 // ----------------------------------------------------------------------------
5081 // ----------------------------------------------------------------------------
5085 #include "wx/dynarray.h"
5087 typedef unsigned short ushort
;
5089 #define DefineCompare(name, T) \
5091 int wxCMPFUNC_CONV name ## CompareValues(T first, T second) \
5093 return first - second; \
5096 int wxCMPFUNC_CONV name ## Compare(T* first, T* second) \
5098 return *first - *second; \
5101 int wxCMPFUNC_CONV name ## RevCompare(T* first, T* second) \
5103 return *second - *first; \
5106 DefineCompare(UShort, ushort);
5107 DefineCompare(Int
, int);
5109 // test compilation of all macros
5110 WX_DEFINE_ARRAY_SHORT(ushort
, wxArrayUShort
);
5111 WX_DEFINE_SORTED_ARRAY_SHORT(ushort
, wxSortedArrayUShortNoCmp
);
5112 WX_DEFINE_SORTED_ARRAY_CMP_SHORT(ushort
, UShortCompareValues
, wxSortedArrayUShort
);
5113 WX_DEFINE_SORTED_ARRAY_CMP_INT(int, IntCompareValues
, wxSortedArrayInt
);
5115 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
5116 #include "wx/arrimpl.cpp"
5117 WX_DEFINE_OBJARRAY(ArrayBars
);
5119 static void PrintArray(const char* name
, const wxArrayString
& array
)
5121 printf("Dump of the array '%s'\n", name
);
5123 size_t nCount
= array
.GetCount();
5124 for ( size_t n
= 0; n
< nCount
; n
++ )
5126 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
5130 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
5131 const wxString
& second
)
5133 return first
.length() - second
.length();
5136 #define TestArrayOf(name) \
5138 static void PrintArray(const char* name, const wxSortedArray##name & array) \
5140 printf("Dump of the array '%s'\n", name); \
5142 size_t nCount = array.GetCount(); \
5143 for ( size_t n = 0; n < nCount; n++ ) \
5145 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5149 static void PrintArray(const char* name, const wxArray##name & array) \
5151 printf("Dump of the array '%s'\n", name); \
5153 size_t nCount = array.GetCount(); \
5154 for ( size_t n = 0; n < nCount; n++ ) \
5156 printf("\t%s[%u] = %d\n", name, n, array[n]); \
5160 static void TestArrayOf ## name ## s() \
5162 printf("*** Testing wxArray%s ***\n", #name); \
5170 puts("Initially:"); \
5171 PrintArray("a", a); \
5173 puts("After sort:"); \
5174 a.Sort(name ## Compare); \
5175 PrintArray("a", a); \
5177 puts("After reverse sort:"); \
5178 a.Sort(name ## RevCompare); \
5179 PrintArray("a", a); \
5181 wxSortedArray##name b; \
5187 puts("Sorted array initially:"); \
5188 PrintArray("b", b); \
5191 TestArrayOf(UShort
);
5194 static void TestArrayOfObjects()
5196 puts("*** Testing wxObjArray ***\n");
5200 Bar
bar("second bar (two copies!)");
5202 printf("Initially: %u objects in the array, %u objects total.\n",
5203 bars
.GetCount(), Bar::GetNumber());
5205 bars
.Add(new Bar("first bar"));
5208 printf("Now: %u objects in the array, %u objects total.\n",
5209 bars
.GetCount(), Bar::GetNumber());
5211 bars
.RemoveAt(1, bars
.GetCount() - 1);
5213 printf("After removing all but first element: %u objects in the "
5214 "array, %u objects total.\n",
5215 bars
.GetCount(), Bar::GetNumber());
5219 printf("After Empty(): %u objects in the array, %u objects total.\n",
5220 bars
.GetCount(), Bar::GetNumber());
5223 printf("Finally: no more objects in the array, %u objects total.\n",
5227 #endif // TEST_ARRAYS
5229 // ----------------------------------------------------------------------------
5231 // ----------------------------------------------------------------------------
5235 #include "wx/timer.h"
5236 #include "wx/tokenzr.h"
5238 static void TestStringConstruction()
5240 puts("*** Testing wxString constructores ***");
5242 #define TEST_CTOR(args, res) \
5245 printf("wxString%s = %s ", #args, s.c_str()); \
5252 printf("(ERROR: should be %s)\n", res); \
5256 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
5257 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
5258 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
5259 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
5261 static const wxChar
*s
= _T("?really!");
5262 const wxChar
*start
= wxStrchr(s
, _T('r'));
5263 const wxChar
*end
= wxStrchr(s
, _T('!'));
5264 TEST_CTOR((start
, end
), _T("really"));
5269 static void TestString()
5279 for (int i
= 0; i
< 1000000; ++i
)
5283 c
= "! How'ya doin'?";
5286 c
= "Hello world! What's up?";
5291 printf ("TestString elapsed time: %ld\n", sw
.Time());
5294 static void TestPChar()
5302 for (int i
= 0; i
< 1000000; ++i
)
5304 strcpy (a
, "Hello");
5305 strcpy (b
, " world");
5306 strcpy (c
, "! How'ya doin'?");
5309 strcpy (c
, "Hello world! What's up?");
5310 if (strcmp (c
, a
) == 0)
5314 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
5317 static void TestStringSub()
5319 wxString
s("Hello, world!");
5321 puts("*** Testing wxString substring extraction ***");
5323 printf("String = '%s'\n", s
.c_str());
5324 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
5325 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
5326 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
5327 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
5328 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
5329 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
5331 static const wxChar
*prefixes
[] =
5335 _T("Hello, world!"),
5336 _T("Hello, world!!!"),
5342 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
5344 wxString prefix
= prefixes
[n
], rest
;
5345 bool rc
= s
.StartsWith(prefix
, &rest
);
5346 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
5349 printf(" (the rest is '%s')\n", rest
.c_str());
5360 static void TestStringFormat()
5362 puts("*** Testing wxString formatting ***");
5365 s
.Printf("%03d", 18);
5367 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
5368 printf("Number 18: %s\n", s
.c_str());
5373 // returns "not found" for npos, value for all others
5374 static wxString
PosToString(size_t res
)
5376 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
5377 : wxString::Format(_T("%u"), res
);
5381 static void TestStringFind()
5383 puts("*** Testing wxString find() functions ***");
5385 static const wxChar
*strToFind
= _T("ell");
5386 static const struct StringFindTest
5390 result
; // of searching "ell" in str
5393 { _T("Well, hello world"), 0, 1 },
5394 { _T("Well, hello world"), 6, 7 },
5395 { _T("Well, hello world"), 9, wxString::npos
},
5398 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
5400 const StringFindTest
& ft
= findTestData
[n
];
5401 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
5403 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
5404 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
5406 size_t resTrue
= ft
.result
;
5407 if ( res
== resTrue
)
5413 printf(_T("(ERROR: should be %s)\n"),
5414 PosToString(resTrue
).c_str());
5421 static void TestStringTokenizer()
5423 puts("*** Testing wxStringTokenizer ***");
5425 static const wxChar
*modeNames
[] =
5429 _T("return all empty"),
5434 static const struct StringTokenizerTest
5436 const wxChar
*str
; // string to tokenize
5437 const wxChar
*delims
; // delimiters to use
5438 size_t count
; // count of token
5439 wxStringTokenizerMode mode
; // how should we tokenize it
5440 } tokenizerTestData
[] =
5442 { _T(""), _T(" "), 0 },
5443 { _T("Hello, world"), _T(" "), 2 },
5444 { _T("Hello, world "), _T(" "), 2 },
5445 { _T("Hello, world"), _T(","), 2 },
5446 { _T("Hello, world!"), _T(",!"), 2 },
5447 { _T("Hello,, world!"), _T(",!"), 3 },
5448 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
5449 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
5450 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
5451 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
5452 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
5453 { _T("01/02/99"), _T("/-"), 3 },
5454 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
5457 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
5459 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
5460 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
5462 size_t count
= tkz
.CountTokens();
5463 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
5464 MakePrintable(tt
.str
).c_str(),
5466 MakePrintable(tt
.delims
).c_str(),
5467 modeNames
[tkz
.GetMode()]);
5468 if ( count
== tt
.count
)
5474 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
5479 // if we emulate strtok(), check that we do it correctly
5480 wxChar
*buf
, *s
= NULL
, *last
;
5482 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
5484 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
5485 wxStrcpy(buf
, tt
.str
);
5487 s
= wxStrtok(buf
, tt
.delims
, &last
);
5494 // now show the tokens themselves
5496 while ( tkz
.HasMoreTokens() )
5498 wxString token
= tkz
.GetNextToken();
5500 printf(_T("\ttoken %u: '%s'"),
5502 MakePrintable(token
).c_str());
5512 printf(" (ERROR: should be %s)\n", s
);
5515 s
= wxStrtok(NULL
, tt
.delims
, &last
);
5519 // nothing to compare with
5524 if ( count2
!= count
)
5526 puts(_T("\tERROR: token count mismatch"));
5535 static void TestStringReplace()
5537 puts("*** Testing wxString::replace ***");
5539 static const struct StringReplaceTestData
5541 const wxChar
*original
; // original test string
5542 size_t start
, len
; // the part to replace
5543 const wxChar
*replacement
; // the replacement string
5544 const wxChar
*result
; // and the expected result
5545 } stringReplaceTestData
[] =
5547 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5548 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5549 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5550 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5551 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5554 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5556 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5558 wxString original
= data
.original
;
5559 original
.replace(data
.start
, data
.len
, data
.replacement
);
5561 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5562 data
.original
, data
.start
, data
.len
, data
.replacement
,
5565 if ( original
== data
.result
)
5571 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5578 static void TestStringMatch()
5580 wxPuts(_T("*** Testing wxString::Matches() ***"));
5582 static const struct StringMatchTestData
5585 const wxChar
*wildcard
;
5587 } stringMatchTestData
[] =
5589 { _T("foobar"), _T("foo*"), 1 },
5590 { _T("foobar"), _T("*oo*"), 1 },
5591 { _T("foobar"), _T("*bar"), 1 },
5592 { _T("foobar"), _T("??????"), 1 },
5593 { _T("foobar"), _T("f??b*"), 1 },
5594 { _T("foobar"), _T("f?b*"), 0 },
5595 { _T("foobar"), _T("*goo*"), 0 },
5596 { _T("foobar"), _T("*foo"), 0 },
5597 { _T("foobarfoo"), _T("*foo"), 1 },
5598 { _T(""), _T("*"), 1 },
5599 { _T(""), _T("?"), 0 },
5602 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5604 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5605 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5606 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5608 matches
? _T("matches") : _T("doesn't match"),
5610 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5616 #endif // TEST_STRINGS
5618 // ----------------------------------------------------------------------------
5620 // ----------------------------------------------------------------------------
5622 #ifdef TEST_SNGLINST
5623 #include "wx/snglinst.h"
5624 #endif // TEST_SNGLINST
5626 int main(int argc
, char **argv
)
5628 wxInitializer initializer
;
5631 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5636 #ifdef TEST_SNGLINST
5637 wxSingleInstanceChecker checker
;
5638 if ( checker
.Create(_T(".wxconsole.lock")) )
5640 if ( checker
.IsAnotherRunning() )
5642 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5647 // wait some time to give time to launch another instance
5648 wxPrintf(_T("Press \"Enter\" to continue..."));
5651 else // failed to create
5653 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5655 #endif // TEST_SNGLINST
5659 #endif // TEST_CHARSET
5662 TestCmdLineConvert();
5664 #if wxUSE_CMDLINE_PARSER
5665 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5667 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5668 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5669 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5670 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5672 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5673 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5674 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5675 wxCMD_LINE_VAL_NUMBER
},
5676 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5677 wxCMD_LINE_VAL_DATE
},
5679 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5680 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5685 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5687 parser
.AddOption("project_name", "", "full path to project file",
5688 wxCMD_LINE_VAL_STRING
,
5689 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5691 switch ( parser
.Parse() )
5694 wxLogMessage("Help was given, terminating.");
5698 ShowCmdLine(parser
);
5702 wxLogMessage("Syntax error detected, aborting.");
5705 #endif // wxUSE_CMDLINE_PARSER
5707 #endif // TEST_CMDLINE
5715 TestStringConstruction();
5718 TestStringTokenizer();
5719 TestStringReplace();
5725 #endif // TEST_STRINGS
5738 puts("*** Initially:");
5740 PrintArray("a1", a1
);
5742 wxArrayString
a2(a1
);
5743 PrintArray("a2", a2
);
5745 wxSortedArrayString
a3(a1
);
5746 PrintArray("a3", a3
);
5748 puts("*** After deleting three strings from a1");
5751 PrintArray("a1", a1
);
5752 PrintArray("a2", a2
);
5753 PrintArray("a3", a3
);
5755 puts("*** After reassigning a1 to a2 and a3");
5757 PrintArray("a2", a2
);
5758 PrintArray("a3", a3
);
5760 puts("*** After sorting a1");
5762 PrintArray("a1", a1
);
5764 puts("*** After sorting a1 in reverse order");
5766 PrintArray("a1", a1
);
5768 puts("*** After sorting a1 by the string length");
5769 a1
.Sort(StringLenCompare
);
5770 PrintArray("a1", a1
);
5772 TestArrayOfObjects();
5773 TestArrayOfUShorts();
5777 #endif // TEST_ARRAYS
5787 #ifdef TEST_DLLLOADER
5789 #endif // TEST_DLLLOADER
5793 #endif // TEST_ENVIRON
5797 #endif // TEST_EXECUTE
5799 #ifdef TEST_FILECONF
5801 #endif // TEST_FILECONF
5809 #endif // TEST_LOCALE
5813 for ( size_t n
= 0; n
< 8000; n
++ )
5815 s
<< (char)('A' + (n
% 26));
5819 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5821 // this one shouldn't be truncated
5824 // but this one will because log functions use fixed size buffer
5825 // (note that it doesn't need '\n' at the end neither - will be added
5827 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5839 #ifdef TEST_FILENAME
5843 fn
.Assign("c:\\foo", "bar.baz");
5850 TestFileNameConstruction();
5851 TestFileNameMakeRelative();
5852 TestFileNameSplit();
5855 TestFileNameComparison();
5856 TestFileNameOperations();
5858 #endif // TEST_FILENAME
5860 #ifdef TEST_FILETIME
5863 #endif // TEST_FILETIME
5866 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5867 if ( TestFtpConnect() )
5878 if ( TEST_INTERACTIVE
)
5879 TestFtpInteractive();
5881 //else: connecting to the FTP server failed
5887 #ifdef TEST_LONGLONG
5888 // seed pseudo random generator
5889 srand((unsigned)time(NULL
));
5898 TestMultiplication();
5901 TestLongLongConversion();
5902 TestBitOperations();
5903 TestLongLongComparison();
5904 TestLongLongPrint();
5906 #endif // TEST_LONGLONG
5914 #endif // TEST_HASHMAP
5917 wxLog::AddTraceMask(_T("mime"));
5925 TestMimeAssociate();
5928 #ifdef TEST_INFO_FUNCTIONS
5934 if ( TEST_INTERACTIVE
)
5937 #endif // TEST_INFO_FUNCTIONS
5939 #ifdef TEST_PATHLIST
5941 #endif // TEST_PATHLIST
5949 #endif // TEST_REGCONF
5952 // TODO: write a real test using src/regex/tests file
5957 TestRegExSubmatch();
5958 TestRegExReplacement();
5960 if ( TEST_INTERACTIVE
)
5961 TestRegExInteractive();
5963 #endif // TEST_REGEX
5965 #ifdef TEST_REGISTRY
5967 TestRegistryAssociation();
5968 #endif // TEST_REGISTRY
5973 #endif // TEST_SOCKETS
5978 #endif // TEST_STREAMS
5981 int nCPUs
= wxThread::GetCPUCount();
5982 printf("This system has %d CPUs\n", nCPUs
);
5984 wxThread::SetConcurrency(nCPUs
);
5988 TestDetachedThreads();
5989 TestJoinableThreads();
5990 TestThreadSuspend();
5992 TestThreadConditions();
5997 #endif // TEST_THREADS
6001 #endif // TEST_TIMER
6003 #ifdef TEST_DATETIME
6016 TestTimeArithmetics();
6019 TestTimeSpanFormat();
6025 if ( TEST_INTERACTIVE
)
6026 TestDateTimeInteractive();
6027 #endif // TEST_DATETIME
6030 puts("Sleeping for 3 seconds... z-z-z-z-z...");
6032 #endif // TEST_USLEEP
6037 #endif // TEST_VCARD
6041 #endif // TEST_VOLUME
6045 TestEncodingConverter();
6046 #endif // TEST_WCHAR
6049 TestZipStreamRead();
6050 TestZipFileSystem();
6054 TestZlibStreamWrite();
6055 TestZlibStreamRead();