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 // ----------------------------------------------------------------------------
42 // what to test (in alphabetic order)? uncomment the line below to do all tests
50 #define TEST_DLLLOADER
59 #define TEST_INFO_FUNCTIONS
75 // #define TEST_VCARD -- don't enable this (VZ)
84 #include "wx/snglinst.h"
85 #endif // TEST_SNGLINST
87 // ----------------------------------------------------------------------------
88 // test class for container objects
89 // ----------------------------------------------------------------------------
91 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
93 class Bar
// Foo is already taken in the hash test
96 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
99 static size_t GetNumber() { return ms_bars
; }
101 const char *GetName() const { return m_name
; }
106 static size_t ms_bars
;
109 size_t Bar::ms_bars
= 0;
111 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
113 // ============================================================================
115 // ============================================================================
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
121 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
123 // replace TABs with \t and CRs with \n
124 static wxString
MakePrintable(const wxChar
*s
)
127 (void)str
.Replace(_T("\t"), _T("\\t"));
128 (void)str
.Replace(_T("\n"), _T("\\n"));
129 (void)str
.Replace(_T("\r"), _T("\\r"));
134 #endif // MakePrintable() is used
136 // ----------------------------------------------------------------------------
137 // wxFontMapper::CharsetToEncoding
138 // ----------------------------------------------------------------------------
142 #include "wx/fontmap.h"
144 static void TestCharset()
146 static const wxChar
*charsets
[] =
148 // some vali charsets
157 // and now some bogus ones
164 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
166 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
167 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
169 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
170 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
174 #endif // TEST_CHARSET
176 // ----------------------------------------------------------------------------
178 // ----------------------------------------------------------------------------
182 #include "wx/cmdline.h"
183 #include "wx/datetime.h"
185 #if wxUSE_CMDLINE_PARSER
187 static void ShowCmdLine(const wxCmdLineParser
& parser
)
189 wxString s
= "Input files: ";
191 size_t count
= parser
.GetParamCount();
192 for ( size_t param
= 0; param
< count
; param
++ )
194 s
<< parser
.GetParam(param
) << ' ';
198 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
199 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
204 if ( parser
.Found("o", &strVal
) )
205 s
<< "Output file:\t" << strVal
<< '\n';
206 if ( parser
.Found("i", &strVal
) )
207 s
<< "Input dir:\t" << strVal
<< '\n';
208 if ( parser
.Found("s", &lVal
) )
209 s
<< "Size:\t" << lVal
<< '\n';
210 if ( parser
.Found("d", &dt
) )
211 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
212 if ( parser
.Found("project_name", &strVal
) )
213 s
<< "Project:\t" << strVal
<< '\n';
218 #endif // wxUSE_CMDLINE_PARSER
220 static void TestCmdLineConvert()
222 static const char *cmdlines
[] =
225 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
226 "literal \\\" and \"\"",
229 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
231 const char *cmdline
= cmdlines
[n
];
232 printf("Parsing: %s\n", cmdline
);
233 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
235 size_t count
= args
.GetCount();
236 printf("\targc = %u\n", count
);
237 for ( size_t arg
= 0; arg
< count
; arg
++ )
239 printf("\targv[%u] = %s\n", arg
, args
[arg
]);
244 #endif // TEST_CMDLINE
246 // ----------------------------------------------------------------------------
248 // ----------------------------------------------------------------------------
255 static const wxChar
*ROOTDIR
= _T("/");
256 static const wxChar
*TESTDIR
= _T("/usr");
257 #elif defined(__WXMSW__)
258 static const wxChar
*ROOTDIR
= _T("c:\\");
259 static const wxChar
*TESTDIR
= _T("d:\\");
261 #error "don't know where the root directory is"
264 static void TestDirEnumHelper(wxDir
& dir
,
265 int flags
= wxDIR_DEFAULT
,
266 const wxString
& filespec
= wxEmptyString
)
270 if ( !dir
.IsOpened() )
273 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
276 printf("\t%s\n", filename
.c_str());
278 cont
= dir
.GetNext(&filename
);
284 static void TestDirEnum()
286 puts("*** Testing wxDir::GetFirst/GetNext ***");
288 wxDir
dir(wxGetCwd());
290 puts("Enumerating everything in current directory:");
291 TestDirEnumHelper(dir
);
293 puts("Enumerating really everything in current directory:");
294 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
296 puts("Enumerating object files in current directory:");
297 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
299 puts("Enumerating directories in current directory:");
300 TestDirEnumHelper(dir
, wxDIR_DIRS
);
302 puts("Enumerating files in current directory:");
303 TestDirEnumHelper(dir
, wxDIR_FILES
);
305 puts("Enumerating files including hidden in current directory:");
306 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
310 puts("Enumerating everything in root directory:");
311 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
313 puts("Enumerating directories in root directory:");
314 TestDirEnumHelper(dir
, wxDIR_DIRS
);
316 puts("Enumerating files in root directory:");
317 TestDirEnumHelper(dir
, wxDIR_FILES
);
319 puts("Enumerating files including hidden in root directory:");
320 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
322 puts("Enumerating files in non existing directory:");
323 wxDir
dirNo("nosuchdir");
324 TestDirEnumHelper(dirNo
);
327 class DirPrintTraverser
: public wxDirTraverser
330 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
332 return wxDIR_CONTINUE
;
335 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
337 wxString path
, name
, ext
;
338 wxSplitPath(dirname
, &path
, &name
, &ext
);
341 name
<< _T('.') << ext
;
344 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
346 if ( wxIsPathSeparator(*p
) )
350 printf("%s%s\n", indent
.c_str(), name
.c_str());
352 return wxDIR_CONTINUE
;
356 static void TestDirTraverse()
358 puts("*** Testing wxDir::Traverse() ***");
362 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
363 printf("There are %u files under '%s'\n", n
, TESTDIR
);
366 printf("First one is '%s'\n", files
[0u].c_str());
367 printf(" last one is '%s'\n", files
[n
- 1].c_str());
370 // enum again with custom traverser
372 DirPrintTraverser traverser
;
373 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
378 // ----------------------------------------------------------------------------
380 // ----------------------------------------------------------------------------
382 #ifdef TEST_DLLLOADER
384 #include "wx/dynlib.h"
386 static void TestDllLoad()
388 #if defined(__WXMSW__)
389 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
390 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
391 #elif defined(__UNIX__)
392 // weird: using just libc.so does *not* work!
393 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
394 static const wxChar
*FUNC_NAME
= _T("strlen");
396 #error "don't know how to test wxDllLoader on this platform"
399 puts("*** testing wxDllLoader ***\n");
401 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
404 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
408 typedef int (*strlenType
)(const char *);
409 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
412 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
413 FUNC_NAME
, LIB_NAME
);
417 if ( pfnStrlen("foo") != 3 )
419 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
427 wxDllLoader::UnloadLibrary(dllHandle
);
431 #endif // TEST_DLLLOADER
433 // ----------------------------------------------------------------------------
435 // ----------------------------------------------------------------------------
439 #include "wx/utils.h"
441 static wxString
MyGetEnv(const wxString
& var
)
444 if ( !wxGetEnv(var
, &val
) )
447 val
= wxString(_T('\'')) + val
+ _T('\'');
452 static void TestEnvironment()
454 const wxChar
*var
= _T("wxTestVar");
456 puts("*** testing environment access functions ***");
458 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
459 wxSetEnv(var
, _T("value for wxTestVar"));
460 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
461 wxSetEnv(var
, _T("another value"));
462 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
464 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
465 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
468 #endif // TEST_ENVIRON
470 // ----------------------------------------------------------------------------
472 // ----------------------------------------------------------------------------
476 #include "wx/utils.h"
478 static void TestExecute()
480 puts("*** testing wxExecute ***");
483 #define COMMAND "cat -n ../../Makefile" // "echo hi"
484 #define SHELL_COMMAND "echo hi from shell"
485 #define REDIRECT_COMMAND COMMAND // "date"
486 #elif defined(__WXMSW__)
487 #define COMMAND "command.com -c 'echo hi'"
488 #define SHELL_COMMAND "echo hi"
489 #define REDIRECT_COMMAND COMMAND
491 #error "no command to exec"
494 printf("Testing wxShell: ");
496 if ( wxShell(SHELL_COMMAND
) )
501 printf("Testing wxExecute: ");
503 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
508 #if 0 // no, it doesn't work (yet?)
509 printf("Testing async wxExecute: ");
511 if ( wxExecute(COMMAND
) != 0 )
512 puts("Ok (command launched).");
517 printf("Testing wxExecute with redirection:\n");
518 wxArrayString output
;
519 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
525 size_t count
= output
.GetCount();
526 for ( size_t n
= 0; n
< count
; n
++ )
528 printf("\t%s\n", output
[n
].c_str());
535 #endif // TEST_EXECUTE
537 // ----------------------------------------------------------------------------
539 // ----------------------------------------------------------------------------
544 #include "wx/ffile.h"
545 #include "wx/textfile.h"
547 static void TestFileRead()
549 puts("*** wxFile read test ***");
551 wxFile
file(_T("testdata.fc"));
552 if ( file
.IsOpened() )
554 printf("File length: %lu\n", file
.Length());
556 puts("File dump:\n----------");
558 static const off_t len
= 1024;
562 off_t nRead
= file
.Read(buf
, len
);
563 if ( nRead
== wxInvalidOffset
)
565 printf("Failed to read the file.");
569 fwrite(buf
, nRead
, 1, stdout
);
579 printf("ERROR: can't open test file.\n");
585 static void TestTextFileRead()
587 puts("*** wxTextFile read test ***");
589 wxTextFile
file(_T("testdata.fc"));
592 printf("Number of lines: %u\n", file
.GetLineCount());
593 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
597 puts("\nDumping the entire file:");
598 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
600 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
602 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
604 puts("\nAnd now backwards:");
605 for ( s
= file
.GetLastLine();
606 file
.GetCurrentLine() != 0;
607 s
= file
.GetPrevLine() )
609 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
611 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
615 printf("ERROR: can't open '%s'\n", file
.GetName());
621 static void TestFileCopy()
623 puts("*** Testing wxCopyFile ***");
625 static const wxChar
*filename1
= _T("testdata.fc");
626 static const wxChar
*filename2
= _T("test2");
627 if ( !wxCopyFile(filename1
, filename2
) )
629 puts("ERROR: failed to copy file");
633 wxFFile
f1(filename1
, "rb"),
636 if ( !f1
.IsOpened() || !f2
.IsOpened() )
638 puts("ERROR: failed to open file(s)");
643 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
645 puts("ERROR: failed to read file(s)");
649 if ( (s1
.length() != s2
.length()) ||
650 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
652 puts("ERROR: copy error!");
656 puts("File was copied ok.");
662 if ( !wxRemoveFile(filename2
) )
664 puts("ERROR: failed to remove the file");
672 // ----------------------------------------------------------------------------
674 // ----------------------------------------------------------------------------
678 #include "wx/confbase.h"
679 #include "wx/fileconf.h"
681 static const struct FileConfTestData
683 const wxChar
*name
; // value name
684 const wxChar
*value
; // the value from the file
687 { _T("value1"), _T("one") },
688 { _T("value2"), _T("two") },
689 { _T("novalue"), _T("default") },
692 static void TestFileConfRead()
694 puts("*** testing wxFileConfig loading/reading ***");
696 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
697 _T("testdata.fc"), wxEmptyString
,
698 wxCONFIG_USE_RELATIVE_PATH
);
700 // test simple reading
701 puts("\nReading config file:");
702 wxString
defValue(_T("default")), value
;
703 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
705 const FileConfTestData
& data
= fcTestData
[n
];
706 value
= fileconf
.Read(data
.name
, defValue
);
707 printf("\t%s = %s ", data
.name
, value
.c_str());
708 if ( value
== data
.value
)
714 printf("(ERROR: should be %s)\n", data
.value
);
718 // test enumerating the entries
719 puts("\nEnumerating all root entries:");
722 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
725 printf("\t%s = %s\n",
727 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
729 cont
= fileconf
.GetNextEntry(name
, dummy
);
733 #endif // TEST_FILECONF
735 // ----------------------------------------------------------------------------
737 // ----------------------------------------------------------------------------
741 #include "wx/filename.h"
743 static struct FileNameInfo
745 const wxChar
*fullname
;
746 const wxChar
*volume
;
755 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
756 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
757 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
758 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
759 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
760 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
761 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
762 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
763 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
765 // Windows file names
766 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
767 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
768 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
769 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
770 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
771 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
774 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
775 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
776 { _T(":File"), _T(""), _T(""), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
777 { _T("File"), _T(""), _T(""), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
780 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
781 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
784 static void TestFileNameConstruction()
786 puts("*** testing wxFileName construction ***");
788 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
790 const FileNameInfo
& fni
= filenames
[n
];
792 wxFileName
fn(fni
.fullname
, fni
.format
);
794 wxString fullname
= fn
.GetFullPath(fni
.format
);
795 if ( fullname
!= fni
.fullname
)
797 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
800 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
801 printf("'%s' is %s (%s)\n\t",
803 isAbsolute
? "absolute" : "relative",
804 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
806 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
808 puts("ERROR (couldn't be normalized)");
812 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
819 static void TestFileNameSplit()
821 puts("*** testing wxFileName splitting ***");
823 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
825 const FileNameInfo
& fni
= filenames
[n
];
826 wxString volume
, path
, name
, ext
;
827 wxFileName::SplitPath(fni
.fullname
,
828 &volume
, &path
, &name
, &ext
, fni
.format
);
830 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
832 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
834 if ( volume
!= fni
.volume
)
835 printf(" (ERROR: volume = '%s')", fni
.volume
);
836 if ( path
!= fni
.path
)
837 printf(" (ERROR: path = '%s')", fni
.path
);
838 if ( name
!= fni
.name
)
839 printf(" (ERROR: name = '%s')", fni
.name
);
840 if ( ext
!= fni
.ext
)
841 printf(" (ERROR: ext = '%s')", fni
.ext
);
847 static void TestFileNameComparison()
852 static void TestFileNameOperations()
857 static void TestFileNameCwd()
862 #endif // TEST_FILENAME
864 // ----------------------------------------------------------------------------
865 // wxFileName time functions
866 // ----------------------------------------------------------------------------
870 #include <wx/filename.h>
871 #include <wx/datetime.h>
873 static void TestFileGetTimes()
875 wxFileName
fn(_T("testdata.fc"));
877 wxDateTime dtAccess
, dtMod
, dtChange
;
878 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
880 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
884 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
886 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
887 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
888 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
889 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
893 static void TestFileSetTimes()
895 wxFileName
fn(_T("testdata.fc"));
897 wxDateTime dtAccess
, dtMod
, dtChange
;
900 wxPrintf(_T("ERROR: Touch() failed.\n"));
904 #endif // TEST_FILETIME
906 // ----------------------------------------------------------------------------
908 // ----------------------------------------------------------------------------
916 Foo(int n_
) { n
= n_
; count
++; }
924 size_t Foo::count
= 0;
926 WX_DECLARE_LIST(Foo
, wxListFoos
);
927 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
929 #include "wx/listimpl.cpp"
931 WX_DEFINE_LIST(wxListFoos
);
933 static void TestHash()
935 puts("*** Testing wxHashTable ***\n");
939 hash
.DeleteContents(TRUE
);
941 printf("Hash created: %u foos in hash, %u foos totally\n",
942 hash
.GetCount(), Foo::count
);
944 static const int hashTestData
[] =
946 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
950 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
952 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
955 printf("Hash filled: %u foos in hash, %u foos totally\n",
956 hash
.GetCount(), Foo::count
);
958 puts("Hash access test:");
959 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
961 printf("\tGetting element with key %d, value %d: ",
963 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
966 printf("ERROR, not found.\n");
970 printf("%d (%s)\n", foo
->n
,
971 (size_t)foo
->n
== n
? "ok" : "ERROR");
975 printf("\nTrying to get an element not in hash: ");
977 if ( hash
.Get(1234) || hash
.Get(1, 0) )
979 puts("ERROR: found!");
983 puts("ok (not found)");
987 printf("Hash destroyed: %u foos left\n", Foo::count
);
992 // ----------------------------------------------------------------------------
994 // ----------------------------------------------------------------------------
1000 WX_DECLARE_LIST(Bar
, wxListBars
);
1001 #include "wx/listimpl.cpp"
1002 WX_DEFINE_LIST(wxListBars
);
1004 static void TestListCtor()
1006 puts("*** Testing wxList construction ***\n");
1010 list1
.Append(new Bar(_T("first")));
1011 list1
.Append(new Bar(_T("second")));
1013 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1014 list1
.GetCount(), Bar::GetNumber());
1019 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1020 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1022 list1
.DeleteContents(TRUE
);
1025 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1030 // ----------------------------------------------------------------------------
1032 // ----------------------------------------------------------------------------
1036 #include "wx/intl.h"
1037 #include "wx/utils.h" // for wxSetEnv
1039 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1041 // find the name of the language from its value
1042 static const char *GetLangName(int lang
)
1044 static const char *languageNames
[] =
1065 "ARABIC_SAUDI_ARABIA",
1090 "CHINESE_SIMPLIFIED",
1091 "CHINESE_TRADITIONAL",
1094 "CHINESE_SINGAPORE",
1105 "ENGLISH_AUSTRALIA",
1109 "ENGLISH_CARIBBEAN",
1113 "ENGLISH_NEW_ZEALAND",
1114 "ENGLISH_PHILIPPINES",
1115 "ENGLISH_SOUTH_AFRICA",
1127 "FRENCH_LUXEMBOURG",
1136 "GERMAN_LIECHTENSTEIN",
1137 "GERMAN_LUXEMBOURG",
1178 "MALAY_BRUNEI_DARUSSALAM",
1190 "NORWEGIAN_NYNORSK",
1197 "PORTUGUESE_BRAZILIAN",
1222 "SPANISH_ARGENTINA",
1226 "SPANISH_COSTA_RICA",
1227 "SPANISH_DOMINICAN_REPUBLIC",
1229 "SPANISH_EL_SALVADOR",
1230 "SPANISH_GUATEMALA",
1234 "SPANISH_NICARAGUA",
1238 "SPANISH_PUERTO_RICO",
1241 "SPANISH_VENEZUELA",
1278 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1279 return languageNames
[lang
];
1284 static void TestDefaultLang()
1286 puts("*** Testing wxLocale::GetSystemLanguage ***");
1288 static const wxChar
*langStrings
[] =
1290 NULL
, // system default
1297 _T("de_DE.iso88591"),
1299 _T("?"), // invalid lang spec
1300 _T("klingonese"), // I bet on some systems it does exist...
1303 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1304 wxLocale::GetSystemEncodingName().c_str(),
1305 wxLocale::GetSystemEncoding());
1307 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1309 const char *langStr
= langStrings
[n
];
1312 // FIXME: this doesn't do anything at all under Windows, we need
1313 // to create a new wxLocale!
1314 wxSetEnv(_T("LC_ALL"), langStr
);
1317 int lang
= gs_localeDefault
.GetSystemLanguage();
1318 printf("Locale for '%s' is %s.\n",
1319 langStr
? langStr
: "system default", GetLangName(lang
));
1323 #endif // TEST_LOCALE
1325 // ----------------------------------------------------------------------------
1327 // ----------------------------------------------------------------------------
1331 #include "wx/mimetype.h"
1333 static void TestMimeEnum()
1335 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1337 wxArrayString mimetypes
;
1339 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1341 printf("*** All %u known filetypes: ***\n", count
);
1346 for ( size_t n
= 0; n
< count
; n
++ )
1348 wxFileType
*filetype
=
1349 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1352 printf("nothing known about the filetype '%s'!\n",
1353 mimetypes
[n
].c_str());
1357 filetype
->GetDescription(&desc
);
1358 filetype
->GetExtensions(exts
);
1360 filetype
->GetIcon(NULL
);
1363 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1366 extsAll
<< _T(", ");
1370 printf("\t%s: %s (%s)\n",
1371 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1377 static void TestMimeOverride()
1379 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1381 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1382 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1384 if ( wxFile::Exists(mailcap
) )
1385 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1387 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1389 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1392 if ( wxFile::Exists(mimetypes
) )
1393 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1395 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1397 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1403 static void TestMimeFilename()
1405 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1407 static const wxChar
*filenames
[] =
1414 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1416 const wxString fname
= filenames
[n
];
1417 wxString ext
= fname
.AfterLast(_T('.'));
1418 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1421 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1426 if ( !ft
->GetDescription(&desc
) )
1427 desc
= _T("<no description>");
1430 if ( !ft
->GetOpenCommand(&cmd
,
1431 wxFileType::MessageParameters(fname
, _T(""))) )
1432 cmd
= _T("<no command available>");
1434 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1435 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1444 static void TestMimeAssociate()
1446 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1448 wxFileTypeInfo
ftInfo(
1449 _T("application/x-xyz"),
1450 _T("xyzview '%s'"), // open cmd
1451 _T(""), // print cmd
1452 _T("XYZ File") // description
1453 _T(".xyz"), // extensions
1454 NULL
// end of extensions
1456 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1458 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1461 wxPuts(_T("ERROR: failed to create association!"));
1465 // TODO: read it back
1474 // ----------------------------------------------------------------------------
1475 // misc information functions
1476 // ----------------------------------------------------------------------------
1478 #ifdef TEST_INFO_FUNCTIONS
1480 #include "wx/utils.h"
1482 static void TestDiskInfo()
1484 puts("*** Testing wxGetDiskSpace() ***");
1489 printf("\nEnter a directory name: ");
1490 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1493 // kill the last '\n'
1494 pathname
[strlen(pathname
) - 1] = 0;
1496 wxLongLong total
, free
;
1497 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1499 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1503 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1504 (total
/ 1024).ToString().c_str(),
1505 (free
/ 1024).ToString().c_str(),
1511 static void TestOsInfo()
1513 puts("*** Testing OS info functions ***\n");
1516 wxGetOsVersion(&major
, &minor
);
1517 printf("Running under: %s, version %d.%d\n",
1518 wxGetOsDescription().c_str(), major
, minor
);
1520 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1522 printf("Host name is %s (%s).\n",
1523 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1528 static void TestUserInfo()
1530 puts("*** Testing user info functions ***\n");
1532 printf("User id is:\t%s\n", wxGetUserId().c_str());
1533 printf("User name is:\t%s\n", wxGetUserName().c_str());
1534 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1535 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1540 #endif // TEST_INFO_FUNCTIONS
1542 // ----------------------------------------------------------------------------
1544 // ----------------------------------------------------------------------------
1546 #ifdef TEST_LONGLONG
1548 #include "wx/longlong.h"
1549 #include "wx/timer.h"
1551 // make a 64 bit number from 4 16 bit ones
1552 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1554 // get a random 64 bit number
1555 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1557 static const long testLongs
[] =
1568 #if wxUSE_LONGLONG_WX
1569 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1570 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1571 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1572 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1573 #endif // wxUSE_LONGLONG_WX
1575 static void TestSpeed()
1577 static const long max
= 100000000;
1584 for ( n
= 0; n
< max
; n
++ )
1589 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1592 #if wxUSE_LONGLONG_NATIVE
1597 for ( n
= 0; n
< max
; n
++ )
1602 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1604 #endif // wxUSE_LONGLONG_NATIVE
1610 for ( n
= 0; n
< max
; n
++ )
1615 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1619 static void TestLongLongConversion()
1621 puts("*** Testing wxLongLong conversions ***\n");
1625 for ( size_t n
= 0; n
< 100000; n
++ )
1629 #if wxUSE_LONGLONG_NATIVE
1630 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1632 wxASSERT_MSG( a
== b
, "conversions failure" );
1634 puts("Can't do it without native long long type, test skipped.");
1637 #endif // wxUSE_LONGLONG_NATIVE
1639 if ( !(nTested
% 1000) )
1651 static void TestMultiplication()
1653 puts("*** Testing wxLongLong multiplication ***\n");
1657 for ( size_t n
= 0; n
< 100000; n
++ )
1662 #if wxUSE_LONGLONG_NATIVE
1663 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1664 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1666 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1667 #else // !wxUSE_LONGLONG_NATIVE
1668 puts("Can't do it without native long long type, test skipped.");
1671 #endif // wxUSE_LONGLONG_NATIVE
1673 if ( !(nTested
% 1000) )
1685 static void TestDivision()
1687 puts("*** Testing wxLongLong division ***\n");
1691 for ( size_t n
= 0; n
< 100000; n
++ )
1693 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1694 // multiplication will not overflow)
1695 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1697 // get a random long (not wxLongLong for now) to divide it with
1702 #if wxUSE_LONGLONG_NATIVE
1703 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1705 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1706 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1707 #else // !wxUSE_LONGLONG_NATIVE
1708 // verify the result
1709 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1710 #endif // wxUSE_LONGLONG_NATIVE
1712 if ( !(nTested
% 1000) )
1724 static void TestAddition()
1726 puts("*** Testing wxLongLong addition ***\n");
1730 for ( size_t n
= 0; n
< 100000; n
++ )
1736 #if wxUSE_LONGLONG_NATIVE
1737 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1738 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1739 "addition failure" );
1740 #else // !wxUSE_LONGLONG_NATIVE
1741 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1742 #endif // wxUSE_LONGLONG_NATIVE
1744 if ( !(nTested
% 1000) )
1756 static void TestBitOperations()
1758 puts("*** Testing wxLongLong bit operation ***\n");
1762 for ( size_t n
= 0; n
< 100000; n
++ )
1766 #if wxUSE_LONGLONG_NATIVE
1767 for ( size_t n
= 0; n
< 33; n
++ )
1770 #else // !wxUSE_LONGLONG_NATIVE
1771 puts("Can't do it without native long long type, test skipped.");
1774 #endif // wxUSE_LONGLONG_NATIVE
1776 if ( !(nTested
% 1000) )
1788 static void TestLongLongComparison()
1790 #if wxUSE_LONGLONG_WX
1791 puts("*** Testing wxLongLong comparison ***\n");
1793 static const long ls
[2] =
1799 wxLongLongWx lls
[2];
1803 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1807 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1809 res
= lls
[m
] > testLongs
[n
];
1810 printf("0x%lx > 0x%lx is %s (%s)\n",
1811 ls
[m
], testLongs
[n
], res
? "true" : "false",
1812 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1814 res
= lls
[m
] < testLongs
[n
];
1815 printf("0x%lx < 0x%lx is %s (%s)\n",
1816 ls
[m
], testLongs
[n
], res
? "true" : "false",
1817 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1819 res
= lls
[m
] == testLongs
[n
];
1820 printf("0x%lx == 0x%lx is %s (%s)\n",
1821 ls
[m
], testLongs
[n
], res
? "true" : "false",
1822 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1825 #endif // wxUSE_LONGLONG_WX
1828 static void TestLongLongPrint()
1830 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1832 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1834 wxLongLong ll
= testLongs
[n
];
1835 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1838 wxLongLong
ll(0x12345678, 0x87654321);
1839 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1842 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1848 #endif // TEST_LONGLONG
1850 // ----------------------------------------------------------------------------
1852 // ----------------------------------------------------------------------------
1854 #ifdef TEST_PATHLIST
1856 static void TestPathList()
1858 puts("*** Testing wxPathList ***\n");
1860 wxPathList pathlist
;
1861 pathlist
.AddEnvList("PATH");
1862 wxString path
= pathlist
.FindValidPath("ls");
1865 printf("ERROR: command not found in the path.\n");
1869 printf("Command found in the path as '%s'.\n", path
.c_str());
1873 #endif // TEST_PATHLIST
1875 // ----------------------------------------------------------------------------
1876 // regular expressions
1877 // ----------------------------------------------------------------------------
1881 #include "wx/regex.h"
1883 static void TestRegExCompile()
1885 wxPuts(_T("*** Testing RE compilation ***\n"));
1887 static struct RegExCompTestData
1889 const wxChar
*pattern
;
1891 } regExCompTestData
[] =
1893 { _T("foo"), TRUE
},
1894 { _T("foo("), FALSE
},
1895 { _T("foo(bar"), FALSE
},
1896 { _T("foo(bar)"), TRUE
},
1897 { _T("foo["), FALSE
},
1898 { _T("foo[bar"), FALSE
},
1899 { _T("foo[bar]"), TRUE
},
1900 { _T("foo{"), TRUE
},
1901 { _T("foo{1"), FALSE
},
1902 { _T("foo{bar"), TRUE
},
1903 { _T("foo{1}"), TRUE
},
1904 { _T("foo{1,2}"), TRUE
},
1905 { _T("foo{bar}"), TRUE
},
1906 { _T("foo*"), TRUE
},
1907 { _T("foo**"), FALSE
},
1908 { _T("foo+"), TRUE
},
1909 { _T("foo++"), FALSE
},
1910 { _T("foo?"), TRUE
},
1911 { _T("foo??"), FALSE
},
1912 { _T("foo?+"), FALSE
},
1916 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1918 const RegExCompTestData
& data
= regExCompTestData
[n
];
1919 bool ok
= re
.Compile(data
.pattern
);
1921 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1923 ok
? _T("") : _T("not "),
1924 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1928 static void TestRegExMatch()
1930 wxPuts(_T("*** Testing RE matching ***\n"));
1932 static struct RegExMatchTestData
1934 const wxChar
*pattern
;
1937 } regExMatchTestData
[] =
1939 { _T("foo"), _T("bar"), FALSE
},
1940 { _T("foo"), _T("foobar"), TRUE
},
1941 { _T("^foo"), _T("foobar"), TRUE
},
1942 { _T("^foo"), _T("barfoo"), FALSE
},
1943 { _T("bar$"), _T("barbar"), TRUE
},
1944 { _T("bar$"), _T("barbar "), FALSE
},
1947 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1949 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1951 wxRegEx
re(data
.pattern
);
1952 bool ok
= re
.Matches(data
.text
);
1954 wxPrintf(_T("'%s' %s %s (%s)\n"),
1956 ok
? _T("matches") : _T("doesn't match"),
1958 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1962 static void TestRegExSubmatch()
1964 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1966 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1967 if ( !re
.IsValid() )
1969 wxPuts(_T("ERROR: compilation failed."));
1973 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
1975 if ( !re
.Matches(text
) )
1977 wxPuts(_T("ERROR: match expected."));
1981 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
1983 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1984 re
.GetMatch(text
, 3).c_str(),
1985 re
.GetMatch(text
, 2).c_str(),
1986 re
.GetMatch(text
, 4).c_str(),
1987 re
.GetMatch(text
, 1).c_str());
1991 static void TestRegExReplacement()
1993 wxPuts(_T("*** Testing RE replacement ***"));
1995 static struct RegExReplTestData
1999 const wxChar
*result
;
2001 } regExReplTestData
[] =
2003 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2004 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2005 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2006 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2007 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2008 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2009 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2012 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2013 wxRegEx re
= pattern
;
2015 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2017 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2019 const RegExReplTestData
& data
= regExReplTestData
[n
];
2021 wxString text
= data
.text
;
2022 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2024 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2025 data
.text
, data
.repl
,
2026 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2028 if ( text
== data
.result
&& nRepl
== data
.count
)
2034 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2035 data
.count
, data
.result
);
2040 static void TestRegExInteractive()
2042 wxPuts(_T("*** Testing RE interactively ***"));
2047 printf("\nEnter a pattern: ");
2048 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2051 // kill the last '\n'
2052 pattern
[strlen(pattern
) - 1] = 0;
2055 if ( !re
.Compile(pattern
) )
2063 printf("Enter text to match: ");
2064 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2067 // kill the last '\n'
2068 text
[strlen(text
) - 1] = 0;
2070 if ( !re
.Matches(text
) )
2072 printf("No match.\n");
2076 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2079 for ( size_t n
= 1; ; n
++ )
2081 if ( !re
.GetMatch(&start
, &len
, n
) )
2086 printf("Subexpr %u matched '%s'\n",
2087 n
, wxString(text
+ start
, len
).c_str());
2094 #endif // TEST_REGEX
2096 // ----------------------------------------------------------------------------
2097 // registry and related stuff
2098 // ----------------------------------------------------------------------------
2100 // this is for MSW only
2103 #undef TEST_REGISTRY
2108 #include "wx/confbase.h"
2109 #include "wx/msw/regconf.h"
2111 static void TestRegConfWrite()
2113 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2114 regconf
.Write(_T("Hello"), wxString(_T("world")));
2117 #endif // TEST_REGCONF
2119 #ifdef TEST_REGISTRY
2121 #include "wx/msw/registry.h"
2123 // I chose this one because I liked its name, but it probably only exists under
2125 static const wxChar
*TESTKEY
=
2126 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2128 static void TestRegistryRead()
2130 puts("*** testing registry reading ***");
2132 wxRegKey
key(TESTKEY
);
2133 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2136 puts("ERROR: test key can't be opened, aborting test.");
2141 size_t nSubKeys
, nValues
;
2142 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2144 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2147 printf("Enumerating values:\n");
2151 bool cont
= key
.GetFirstValue(value
, dummy
);
2154 printf("Value '%s': type ", value
.c_str());
2155 switch ( key
.GetValueType(value
) )
2157 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2158 case wxRegKey::Type_String
: printf("SZ"); break;
2159 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2160 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2161 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2162 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2163 default: printf("other (unknown)"); break;
2166 printf(", value = ");
2167 if ( key
.IsNumericValue(value
) )
2170 key
.QueryValue(value
, &val
);
2176 key
.QueryValue(value
, val
);
2177 printf("'%s'", val
.c_str());
2179 key
.QueryRawValue(value
, val
);
2180 printf(" (raw value '%s')", val
.c_str());
2185 cont
= key
.GetNextValue(value
, dummy
);
2189 static void TestRegistryAssociation()
2192 The second call to deleteself genertaes an error message, with a
2193 messagebox saying .flo is crucial to system operation, while the .ddf
2194 call also fails, but with no error message
2199 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2201 key
= "ddxf_auto_file" ;
2202 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2204 key
= "ddxf_auto_file" ;
2205 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2208 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2210 key
= "program \"%1\"" ;
2212 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2214 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2216 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2218 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2222 #endif // TEST_REGISTRY
2224 // ----------------------------------------------------------------------------
2226 // ----------------------------------------------------------------------------
2230 #include "wx/socket.h"
2231 #include "wx/protocol/protocol.h"
2232 #include "wx/protocol/http.h"
2234 static void TestSocketServer()
2236 puts("*** Testing wxSocketServer ***\n");
2238 static const int PORT
= 3000;
2243 wxSocketServer
*server
= new wxSocketServer(addr
);
2244 if ( !server
->Ok() )
2246 puts("ERROR: failed to bind");
2253 printf("Server: waiting for connection on port %d...\n", PORT
);
2255 wxSocketBase
*socket
= server
->Accept();
2258 puts("ERROR: wxSocketServer::Accept() failed.");
2262 puts("Server: got a client.");
2264 server
->SetTimeout(60); // 1 min
2266 while ( socket
->IsConnected() )
2272 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2274 // don't log error if the client just close the connection
2275 if ( socket
->IsConnected() )
2277 puts("ERROR: in wxSocket::Read.");
2297 printf("Server: got '%s'.\n", s
.c_str());
2298 if ( s
== _T("bye") )
2305 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2306 socket
->Write("\r\n", 2);
2307 printf("Server: wrote '%s'.\n", s
.c_str());
2310 puts("Server: lost a client.");
2315 // same as "delete server" but is consistent with GUI programs
2319 static void TestSocketClient()
2321 puts("*** Testing wxSocketClient ***\n");
2323 static const char *hostname
= "www.wxwindows.org";
2326 addr
.Hostname(hostname
);
2329 printf("--- Attempting to connect to %s:80...\n", hostname
);
2331 wxSocketClient client
;
2332 if ( !client
.Connect(addr
) )
2334 printf("ERROR: failed to connect to %s\n", hostname
);
2338 printf("--- Connected to %s:%u...\n",
2339 addr
.Hostname().c_str(), addr
.Service());
2343 // could use simply "GET" here I suppose
2345 wxString::Format("GET http://%s/\r\n", hostname
);
2346 client
.Write(cmdGet
, cmdGet
.length());
2347 printf("--- Sent command '%s' to the server\n",
2348 MakePrintable(cmdGet
).c_str());
2349 client
.Read(buf
, WXSIZEOF(buf
));
2350 printf("--- Server replied:\n%s", buf
);
2354 #endif // TEST_SOCKETS
2356 // ----------------------------------------------------------------------------
2358 // ----------------------------------------------------------------------------
2362 #include "wx/protocol/ftp.h"
2366 #define FTP_ANONYMOUS
2368 #ifdef FTP_ANONYMOUS
2369 static const char *directory
= "/pub";
2370 static const char *filename
= "welcome.msg";
2372 static const char *directory
= "/etc";
2373 static const char *filename
= "issue";
2376 static bool TestFtpConnect()
2378 puts("*** Testing FTP connect ***");
2380 #ifdef FTP_ANONYMOUS
2381 static const char *hostname
= "ftp.wxwindows.org";
2383 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2384 #else // !FTP_ANONYMOUS
2385 static const char *hostname
= "localhost";
2388 fgets(user
, WXSIZEOF(user
), stdin
);
2389 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2393 printf("Password for %s: ", password
);
2394 fgets(password
, WXSIZEOF(password
), stdin
);
2395 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2396 ftp
.SetPassword(password
);
2398 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2399 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2401 if ( !ftp
.Connect(hostname
) )
2403 printf("ERROR: failed to connect to %s\n", hostname
);
2409 printf("--- Connected to %s, current directory is '%s'\n",
2410 hostname
, ftp
.Pwd().c_str());
2416 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2417 static void TestFtpWuFtpd()
2420 static const char *hostname
= "ftp.eudora.com";
2421 if ( !ftp
.Connect(hostname
) )
2423 printf("ERROR: failed to connect to %s\n", hostname
);
2427 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2428 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2431 printf("ERROR: couldn't get input stream for %s\n", filename
);
2435 size_t size
= in
->StreamSize();
2436 printf("Reading file %s (%u bytes)...", filename
, size
);
2438 char *data
= new char[size
];
2439 if ( !in
->Read(data
, size
) )
2441 puts("ERROR: read error");
2445 printf("Successfully retrieved the file.\n");
2454 static void TestFtpList()
2456 puts("*** Testing wxFTP file listing ***\n");
2459 if ( !ftp
.ChDir(directory
) )
2461 printf("ERROR: failed to cd to %s\n", directory
);
2464 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2466 // test NLIST and LIST
2467 wxArrayString files
;
2468 if ( !ftp
.GetFilesList(files
) )
2470 puts("ERROR: failed to get NLIST of files");
2474 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2475 size_t count
= files
.GetCount();
2476 for ( size_t n
= 0; n
< count
; n
++ )
2478 printf("\t%s\n", files
[n
].c_str());
2480 puts("End of the file list");
2483 if ( !ftp
.GetDirList(files
) )
2485 puts("ERROR: failed to get LIST of files");
2489 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2490 size_t count
= files
.GetCount();
2491 for ( size_t n
= 0; n
< count
; n
++ )
2493 printf("\t%s\n", files
[n
].c_str());
2495 puts("End of the file list");
2498 if ( !ftp
.ChDir(_T("..")) )
2500 puts("ERROR: failed to cd to ..");
2503 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2506 static void TestFtpDownload()
2508 puts("*** Testing wxFTP download ***\n");
2511 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2514 printf("ERROR: couldn't get input stream for %s\n", filename
);
2518 size_t size
= in
->StreamSize();
2519 printf("Reading file %s (%u bytes)...", filename
, size
);
2522 char *data
= new char[size
];
2523 if ( !in
->Read(data
, size
) )
2525 puts("ERROR: read error");
2529 printf("\nContents of %s:\n%s\n", filename
, data
);
2537 static void TestFtpFileSize()
2539 puts("*** Testing FTP SIZE command ***");
2541 if ( !ftp
.ChDir(directory
) )
2543 printf("ERROR: failed to cd to %s\n", directory
);
2546 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2548 if ( ftp
.FileExists(filename
) )
2550 int size
= ftp
.GetFileSize(filename
);
2552 printf("ERROR: couldn't get size of '%s'\n", filename
);
2554 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2558 printf("ERROR: '%s' doesn't exist\n", filename
);
2562 static void TestFtpMisc()
2564 puts("*** Testing miscellaneous wxFTP functions ***");
2566 if ( ftp
.SendCommand("STAT") != '2' )
2568 puts("ERROR: STAT failed");
2572 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2575 if ( ftp
.SendCommand("HELP SITE") != '2' )
2577 puts("ERROR: HELP SITE failed");
2581 printf("The list of site-specific commands:\n\n%s\n",
2582 ftp
.GetLastResult().c_str());
2586 static void TestFtpInteractive()
2588 puts("\n*** Interactive wxFTP test ***");
2594 printf("Enter FTP command: ");
2595 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2598 // kill the last '\n'
2599 buf
[strlen(buf
) - 1] = 0;
2601 // special handling of LIST and NLST as they require data connection
2602 wxString
start(buf
, 4);
2604 if ( start
== "LIST" || start
== "NLST" )
2607 if ( strlen(buf
) > 4 )
2610 wxArrayString files
;
2611 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2613 printf("ERROR: failed to get %s of files\n", start
.c_str());
2617 printf("--- %s of '%s' under '%s':\n",
2618 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2619 size_t count
= files
.GetCount();
2620 for ( size_t n
= 0; n
< count
; n
++ )
2622 printf("\t%s\n", files
[n
].c_str());
2624 puts("--- End of the file list");
2629 char ch
= ftp
.SendCommand(buf
);
2630 printf("Command %s", ch
? "succeeded" : "failed");
2633 printf(" (return code %c)", ch
);
2636 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2640 puts("\n*** done ***");
2643 static void TestFtpUpload()
2645 puts("*** Testing wxFTP uploading ***\n");
2648 static const char *file1
= "test1";
2649 static const char *file2
= "test2";
2650 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2653 printf("--- Uploading to %s ---\n", file1
);
2654 out
->Write("First hello", 11);
2658 // send a command to check the remote file
2659 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2661 printf("ERROR: STAT %s failed\n", file1
);
2665 printf("STAT %s returned:\n\n%s\n",
2666 file1
, ftp
.GetLastResult().c_str());
2669 out
= ftp
.GetOutputStream(file2
);
2672 printf("--- Uploading to %s ---\n", file1
);
2673 out
->Write("Second hello", 12);
2680 // ----------------------------------------------------------------------------
2682 // ----------------------------------------------------------------------------
2686 #include "wx/wfstream.h"
2687 #include "wx/mstream.h"
2689 static void TestFileStream()
2691 puts("*** Testing wxFileInputStream ***");
2693 static const wxChar
*filename
= _T("testdata.fs");
2695 wxFileOutputStream
fsOut(filename
);
2696 fsOut
.Write("foo", 3);
2699 wxFileInputStream
fsIn(filename
);
2700 printf("File stream size: %u\n", fsIn
.GetSize());
2701 while ( !fsIn
.Eof() )
2703 putchar(fsIn
.GetC());
2706 if ( !wxRemoveFile(filename
) )
2708 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2711 puts("\n*** wxFileInputStream test done ***");
2714 static void TestMemoryStream()
2716 puts("*** Testing wxMemoryInputStream ***");
2719 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2721 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2722 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2723 while ( !memInpStream
.Eof() )
2725 putchar(memInpStream
.GetC());
2728 puts("\n*** wxMemoryInputStream test done ***");
2731 #endif // TEST_STREAMS
2733 // ----------------------------------------------------------------------------
2735 // ----------------------------------------------------------------------------
2739 #include "wx/timer.h"
2740 #include "wx/utils.h"
2742 static void TestStopWatch()
2744 puts("*** Testing wxStopWatch ***\n");
2747 printf("Sleeping 3 seconds...");
2749 printf("\telapsed time: %ldms\n", sw
.Time());
2752 printf("Sleeping 2 more seconds...");
2754 printf("\telapsed time: %ldms\n", sw
.Time());
2757 printf("And 3 more seconds...");
2759 printf("\telapsed time: %ldms\n", sw
.Time());
2762 puts("\nChecking for 'backwards clock' bug...");
2763 for ( size_t n
= 0; n
< 70; n
++ )
2767 for ( size_t m
= 0; m
< 100000; m
++ )
2769 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2771 puts("\ntime is negative - ERROR!");
2781 #endif // TEST_TIMER
2783 // ----------------------------------------------------------------------------
2785 // ----------------------------------------------------------------------------
2789 #include "wx/vcard.h"
2791 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2794 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2798 wxString(_T('\t'), level
).c_str(),
2799 vcObj
->GetName().c_str());
2802 switch ( vcObj
->GetType() )
2804 case wxVCardObject::String
:
2805 case wxVCardObject::UString
:
2808 vcObj
->GetValue(&val
);
2809 value
<< _T('"') << val
<< _T('"');
2813 case wxVCardObject::Int
:
2816 vcObj
->GetValue(&i
);
2817 value
.Printf(_T("%u"), i
);
2821 case wxVCardObject::Long
:
2824 vcObj
->GetValue(&l
);
2825 value
.Printf(_T("%lu"), l
);
2829 case wxVCardObject::None
:
2832 case wxVCardObject::Object
:
2833 value
= _T("<node>");
2837 value
= _T("<unknown value type>");
2841 printf(" = %s", value
.c_str());
2844 DumpVObject(level
+ 1, *vcObj
);
2847 vcObj
= vcard
.GetNextProp(&cookie
);
2851 static void DumpVCardAddresses(const wxVCard
& vcard
)
2853 puts("\nShowing all addresses from vCard:\n");
2857 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2861 int flags
= addr
->GetFlags();
2862 if ( flags
& wxVCardAddress::Domestic
)
2864 flagsStr
<< _T("domestic ");
2866 if ( flags
& wxVCardAddress::Intl
)
2868 flagsStr
<< _T("international ");
2870 if ( flags
& wxVCardAddress::Postal
)
2872 flagsStr
<< _T("postal ");
2874 if ( flags
& wxVCardAddress::Parcel
)
2876 flagsStr
<< _T("parcel ");
2878 if ( flags
& wxVCardAddress::Home
)
2880 flagsStr
<< _T("home ");
2882 if ( flags
& wxVCardAddress::Work
)
2884 flagsStr
<< _T("work ");
2887 printf("Address %u:\n"
2889 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2892 addr
->GetPostOffice().c_str(),
2893 addr
->GetExtAddress().c_str(),
2894 addr
->GetStreet().c_str(),
2895 addr
->GetLocality().c_str(),
2896 addr
->GetRegion().c_str(),
2897 addr
->GetPostalCode().c_str(),
2898 addr
->GetCountry().c_str()
2902 addr
= vcard
.GetNextAddress(&cookie
);
2906 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2908 puts("\nShowing all phone numbers from vCard:\n");
2912 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2916 int flags
= phone
->GetFlags();
2917 if ( flags
& wxVCardPhoneNumber::Voice
)
2919 flagsStr
<< _T("voice ");
2921 if ( flags
& wxVCardPhoneNumber::Fax
)
2923 flagsStr
<< _T("fax ");
2925 if ( flags
& wxVCardPhoneNumber::Cellular
)
2927 flagsStr
<< _T("cellular ");
2929 if ( flags
& wxVCardPhoneNumber::Modem
)
2931 flagsStr
<< _T("modem ");
2933 if ( flags
& wxVCardPhoneNumber::Home
)
2935 flagsStr
<< _T("home ");
2937 if ( flags
& wxVCardPhoneNumber::Work
)
2939 flagsStr
<< _T("work ");
2942 printf("Phone number %u:\n"
2947 phone
->GetNumber().c_str()
2951 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2955 static void TestVCardRead()
2957 puts("*** Testing wxVCard reading ***\n");
2959 wxVCard
vcard(_T("vcard.vcf"));
2960 if ( !vcard
.IsOk() )
2962 puts("ERROR: couldn't load vCard.");
2966 // read individual vCard properties
2967 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2971 vcObj
->GetValue(&value
);
2976 value
= _T("<none>");
2979 printf("Full name retrieved directly: %s\n", value
.c_str());
2982 if ( !vcard
.GetFullName(&value
) )
2984 value
= _T("<none>");
2987 printf("Full name from wxVCard API: %s\n", value
.c_str());
2989 // now show how to deal with multiply occuring properties
2990 DumpVCardAddresses(vcard
);
2991 DumpVCardPhoneNumbers(vcard
);
2993 // and finally show all
2994 puts("\nNow dumping the entire vCard:\n"
2995 "-----------------------------\n");
2997 DumpVObject(0, vcard
);
3001 static void TestVCardWrite()
3003 puts("*** Testing wxVCard writing ***\n");
3006 if ( !vcard
.IsOk() )
3008 puts("ERROR: couldn't create vCard.");
3013 vcard
.SetName("Zeitlin", "Vadim");
3014 vcard
.SetFullName("Vadim Zeitlin");
3015 vcard
.SetOrganization("wxWindows", "R&D");
3017 // just dump the vCard back
3018 puts("Entire vCard follows:\n");
3019 puts(vcard
.Write());
3023 #endif // TEST_VCARD
3025 // ----------------------------------------------------------------------------
3026 // wide char (Unicode) support
3027 // ----------------------------------------------------------------------------
3031 #include "wx/strconv.h"
3032 #include "wx/fontenc.h"
3033 #include "wx/encconv.h"
3034 #include "wx/buffer.h"
3036 static void TestUtf8()
3038 puts("*** Testing UTF8 support ***\n");
3040 static const char textInUtf8
[] =
3042 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3043 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3044 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3045 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3046 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3047 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3048 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3053 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3055 puts("ERROR: UTF-8 decoding failed.");
3059 // using wxEncodingConverter
3061 wxEncodingConverter ec
;
3062 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3063 ec
.Convert(wbuf
, buf
);
3064 #else // using wxCSConv
3065 wxCSConv
conv(_T("koi8-r"));
3066 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3068 puts("ERROR: conversion to KOI8-R failed.");
3073 printf("The resulting string (in koi8-r): %s\n", buf
);
3077 #endif // TEST_WCHAR
3079 // ----------------------------------------------------------------------------
3081 // ----------------------------------------------------------------------------
3085 #include "wx/filesys.h"
3086 #include "wx/fs_zip.h"
3087 #include "wx/zipstrm.h"
3089 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3091 static void TestZipStreamRead()
3093 puts("*** Testing ZIP reading ***\n");
3095 static const wxChar
*filename
= _T("foo");
3096 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3097 printf("Archive size: %u\n", istr
.GetSize());
3099 printf("Dumping the file '%s':\n", filename
);
3100 while ( !istr
.Eof() )
3102 putchar(istr
.GetC());
3106 puts("\n----- done ------");
3109 static void DumpZipDirectory(wxFileSystem
& fs
,
3110 const wxString
& dir
,
3111 const wxString
& indent
)
3113 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3114 TESTFILE_ZIP
, dir
.c_str());
3115 wxString wildcard
= prefix
+ _T("/*");
3117 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3118 while ( !dirname
.empty() )
3120 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3122 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3127 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3129 DumpZipDirectory(fs
, dirname
,
3130 indent
+ wxString(_T(' '), 4));
3132 dirname
= fs
.FindNext();
3135 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3136 while ( !filename
.empty() )
3138 if ( !filename
.StartsWith(prefix
, &filename
) )
3140 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3145 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3147 filename
= fs
.FindNext();
3151 static void TestZipFileSystem()
3153 puts("*** Testing ZIP file system ***\n");
3155 wxFileSystem::AddHandler(new wxZipFSHandler
);
3157 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3159 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3164 // ----------------------------------------------------------------------------
3166 // ----------------------------------------------------------------------------
3170 #include "wx/zstream.h"
3171 #include "wx/wfstream.h"
3173 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3174 static const char *TEST_DATA
= "hello and hello again";
3176 static void TestZlibStreamWrite()
3178 puts("*** Testing Zlib stream reading ***\n");
3180 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3181 wxZlibOutputStream
ostr(fileOutStream
, 0);
3182 printf("Compressing the test string... ");
3183 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3186 puts("(ERROR: failed)");
3193 puts("\n----- done ------");
3196 static void TestZlibStreamRead()
3198 puts("*** Testing Zlib stream reading ***\n");
3200 wxFileInputStream
fileInStream(FILENAME_GZ
);
3201 wxZlibInputStream
istr(fileInStream
);
3202 printf("Archive size: %u\n", istr
.GetSize());
3204 puts("Dumping the file:");
3205 while ( !istr
.Eof() )
3207 putchar(istr
.GetC());
3211 puts("\n----- done ------");
3216 // ----------------------------------------------------------------------------
3218 // ----------------------------------------------------------------------------
3220 #ifdef TEST_DATETIME
3224 #include "wx/date.h"
3225 #include "wx/datetime.h"
3230 wxDateTime::wxDateTime_t day
;
3231 wxDateTime::Month month
;
3233 wxDateTime::wxDateTime_t hour
, min
, sec
;
3235 wxDateTime::WeekDay wday
;
3236 time_t gmticks
, ticks
;
3238 void Init(const wxDateTime::Tm
& tm
)
3247 gmticks
= ticks
= -1;
3250 wxDateTime
DT() const
3251 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3253 bool SameDay(const wxDateTime::Tm
& tm
) const
3255 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3258 wxString
Format() const
3261 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3263 wxDateTime::GetMonthName(month
).c_str(),
3265 abs(wxDateTime::ConvertYearToBC(year
)),
3266 year
> 0 ? "AD" : "BC");
3270 wxString
FormatDate() const
3273 s
.Printf("%02d-%s-%4d%s",
3275 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3276 abs(wxDateTime::ConvertYearToBC(year
)),
3277 year
> 0 ? "AD" : "BC");
3282 static const Date testDates
[] =
3284 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3285 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3286 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3287 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3288 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3289 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3290 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3291 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3292 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3293 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3294 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3295 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3296 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3297 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3298 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3301 // this test miscellaneous static wxDateTime functions
3302 static void TestTimeStatic()
3304 puts("\n*** wxDateTime static methods test ***");
3306 // some info about the current date
3307 int year
= wxDateTime::GetCurrentYear();
3308 printf("Current year %d is %sa leap one and has %d days.\n",
3310 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3311 wxDateTime::GetNumberOfDays(year
));
3313 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3314 printf("Current month is '%s' ('%s') and it has %d days\n",
3315 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3316 wxDateTime::GetMonthName(month
).c_str(),
3317 wxDateTime::GetNumberOfDays(month
));
3320 static const size_t nYears
= 5;
3321 static const size_t years
[2][nYears
] =
3323 // first line: the years to test
3324 { 1990, 1976, 2000, 2030, 1984, },
3326 // second line: TRUE if leap, FALSE otherwise
3327 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3330 for ( size_t n
= 0; n
< nYears
; n
++ )
3332 int year
= years
[0][n
];
3333 bool should
= years
[1][n
] != 0,
3334 is
= wxDateTime::IsLeapYear(year
);
3336 printf("Year %d is %sa leap year (%s)\n",
3339 should
== is
? "ok" : "ERROR");
3341 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3345 // test constructing wxDateTime objects
3346 static void TestTimeSet()
3348 puts("\n*** wxDateTime construction test ***");
3350 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3352 const Date
& d1
= testDates
[n
];
3353 wxDateTime dt
= d1
.DT();
3356 d2
.Init(dt
.GetTm());
3358 wxString s1
= d1
.Format(),
3361 printf("Date: %s == %s (%s)\n",
3362 s1
.c_str(), s2
.c_str(),
3363 s1
== s2
? "ok" : "ERROR");
3367 // test time zones stuff
3368 static void TestTimeZones()
3370 puts("\n*** wxDateTime timezone test ***");
3372 wxDateTime now
= wxDateTime::Now();
3374 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3375 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3376 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3377 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3378 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3379 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3381 wxDateTime::Tm tm
= now
.GetTm();
3382 if ( wxDateTime(tm
) != now
)
3384 printf("ERROR: got %s instead of %s\n",
3385 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3389 // test some minimal support for the dates outside the standard range
3390 static void TestTimeRange()
3392 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3394 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3396 printf("Unix epoch:\t%s\n",
3397 wxDateTime(2440587.5).Format(fmt
).c_str());
3398 printf("Feb 29, 0: \t%s\n",
3399 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3400 printf("JDN 0: \t%s\n",
3401 wxDateTime(0.0).Format(fmt
).c_str());
3402 printf("Jan 1, 1AD:\t%s\n",
3403 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3404 printf("May 29, 2099:\t%s\n",
3405 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3408 static void TestTimeTicks()
3410 puts("\n*** wxDateTime ticks test ***");
3412 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3414 const Date
& d
= testDates
[n
];
3415 if ( d
.ticks
== -1 )
3418 wxDateTime dt
= d
.DT();
3419 long ticks
= (dt
.GetValue() / 1000).ToLong();
3420 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3421 if ( ticks
== d
.ticks
)
3427 printf(" (ERROR: should be %ld, delta = %ld)\n",
3428 d
.ticks
, ticks
- d
.ticks
);
3431 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3432 ticks
= (dt
.GetValue() / 1000).ToLong();
3433 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3434 if ( ticks
== d
.gmticks
)
3440 printf(" (ERROR: should be %ld, delta = %ld)\n",
3441 d
.gmticks
, ticks
- d
.gmticks
);
3448 // test conversions to JDN &c
3449 static void TestTimeJDN()
3451 puts("\n*** wxDateTime to JDN test ***");
3453 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3455 const Date
& d
= testDates
[n
];
3456 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3457 double jdn
= dt
.GetJulianDayNumber();
3459 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3466 printf(" (ERROR: should be %f, delta = %f)\n",
3467 d
.jdn
, jdn
- d
.jdn
);
3472 // test week days computation
3473 static void TestTimeWDays()
3475 puts("\n*** wxDateTime weekday test ***");
3477 // test GetWeekDay()
3479 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3481 const Date
& d
= testDates
[n
];
3482 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3484 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3487 wxDateTime::GetWeekDayName(wday
).c_str());
3488 if ( wday
== d
.wday
)
3494 printf(" (ERROR: should be %s)\n",
3495 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3501 // test SetToWeekDay()
3502 struct WeekDateTestData
3504 Date date
; // the real date (precomputed)
3505 int nWeek
; // its week index in the month
3506 wxDateTime::WeekDay wday
; // the weekday
3507 wxDateTime::Month month
; // the month
3508 int year
; // and the year
3510 wxString
Format() const
3513 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3515 case 1: which
= "first"; break;
3516 case 2: which
= "second"; break;
3517 case 3: which
= "third"; break;
3518 case 4: which
= "fourth"; break;
3519 case 5: which
= "fifth"; break;
3521 case -1: which
= "last"; break;
3526 which
+= " from end";
3529 s
.Printf("The %s %s of %s in %d",
3531 wxDateTime::GetWeekDayName(wday
).c_str(),
3532 wxDateTime::GetMonthName(month
).c_str(),
3539 // the array data was generated by the following python program
3541 from DateTime import *
3542 from whrandom import *
3543 from string import *
3545 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3546 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3548 week = DateTimeDelta(7)
3551 year = randint(1900, 2100)
3552 month = randint(1, 12)
3553 day = randint(1, 28)
3554 dt = DateTime(year, month, day)
3555 wday = dt.day_of_week
3557 countFromEnd = choice([-1, 1])
3560 while dt.month is month:
3561 dt = dt - countFromEnd * week
3562 weekNum = weekNum + countFromEnd
3564 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3566 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3567 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3570 static const WeekDateTestData weekDatesTestData
[] =
3572 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3573 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3574 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3575 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3576 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3577 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3578 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3579 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3580 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3581 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3582 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3583 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3584 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3585 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3586 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3587 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3588 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3589 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3590 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3591 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3594 static const char *fmt
= "%d-%b-%Y";
3597 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3599 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3601 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3603 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3605 const Date
& d
= wd
.date
;
3606 if ( d
.SameDay(dt
.GetTm()) )
3612 dt
.Set(d
.day
, d
.month
, d
.year
);
3614 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3619 // test the computation of (ISO) week numbers
3620 static void TestTimeWNumber()
3622 puts("\n*** wxDateTime week number test ***");
3624 struct WeekNumberTestData
3626 Date date
; // the date
3627 wxDateTime::wxDateTime_t week
; // the week number in the year
3628 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3629 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3630 wxDateTime::wxDateTime_t dnum
; // day number in the year
3633 // data generated with the following python script:
3635 from DateTime import *
3636 from whrandom import *
3637 from string import *
3639 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3640 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3642 def GetMonthWeek(dt):
3643 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3644 if weekNumMonth < 0:
3645 weekNumMonth = weekNumMonth + 53
3648 def GetLastSundayBefore(dt):
3649 if dt.iso_week[2] == 7:
3652 return dt - DateTimeDelta(dt.iso_week[2])
3655 year = randint(1900, 2100)
3656 month = randint(1, 12)
3657 day = randint(1, 28)
3658 dt = DateTime(year, month, day)
3659 dayNum = dt.day_of_year
3660 weekNum = dt.iso_week[1]
3661 weekNumMonth = GetMonthWeek(dt)
3664 dtSunday = GetLastSundayBefore(dt)
3666 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3667 weekNumMonth2 = weekNumMonth2 + 1
3668 dtSunday = dtSunday - DateTimeDelta(7)
3670 data = { 'day': rjust(`day`, 2), \
3671 'month': monthNames[month - 1], \
3673 'weekNum': rjust(`weekNum`, 2), \
3674 'weekNumMonth': weekNumMonth, \
3675 'weekNumMonth2': weekNumMonth2, \
3676 'dayNum': rjust(`dayNum`, 3) }
3678 print " { { %(day)s, "\
3679 "wxDateTime::%(month)s, "\
3682 "%(weekNumMonth)s, "\
3683 "%(weekNumMonth2)s, "\
3684 "%(dayNum)s }," % data
3687 static const WeekNumberTestData weekNumberTestDates
[] =
3689 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3690 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3691 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3692 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3693 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3694 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3695 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3696 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3697 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3698 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3699 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3700 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3701 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3702 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3703 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3704 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3705 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3706 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3707 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3708 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3711 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3713 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3714 const Date
& d
= wn
.date
;
3716 wxDateTime dt
= d
.DT();
3718 wxDateTime::wxDateTime_t
3719 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3720 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3721 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3722 dnum
= dt
.GetDayOfYear();
3724 printf("%s: the day number is %d",
3725 d
.FormatDate().c_str(), dnum
);
3726 if ( dnum
== wn
.dnum
)
3732 printf(" (ERROR: should be %d)", wn
.dnum
);
3735 printf(", week in month is %d", wmon
);
3736 if ( wmon
== wn
.wmon
)
3742 printf(" (ERROR: should be %d)", wn
.wmon
);
3745 printf(" or %d", wmon2
);
3746 if ( wmon2
== wn
.wmon2
)
3752 printf(" (ERROR: should be %d)", wn
.wmon2
);
3755 printf(", week in year is %d", week
);
3756 if ( week
== wn
.week
)
3762 printf(" (ERROR: should be %d)\n", wn
.week
);
3767 // test DST calculations
3768 static void TestTimeDST()
3770 puts("\n*** wxDateTime DST test ***");
3772 printf("DST is%s in effect now.\n\n",
3773 wxDateTime::Now().IsDST() ? "" : " not");
3775 // taken from http://www.energy.ca.gov/daylightsaving.html
3776 static const Date datesDST
[2][2004 - 1900 + 1] =
3779 { 1, wxDateTime::Apr
, 1990 },
3780 { 7, wxDateTime::Apr
, 1991 },
3781 { 5, wxDateTime::Apr
, 1992 },
3782 { 4, wxDateTime::Apr
, 1993 },
3783 { 3, wxDateTime::Apr
, 1994 },
3784 { 2, wxDateTime::Apr
, 1995 },
3785 { 7, wxDateTime::Apr
, 1996 },
3786 { 6, wxDateTime::Apr
, 1997 },
3787 { 5, wxDateTime::Apr
, 1998 },
3788 { 4, wxDateTime::Apr
, 1999 },
3789 { 2, wxDateTime::Apr
, 2000 },
3790 { 1, wxDateTime::Apr
, 2001 },
3791 { 7, wxDateTime::Apr
, 2002 },
3792 { 6, wxDateTime::Apr
, 2003 },
3793 { 4, wxDateTime::Apr
, 2004 },
3796 { 28, wxDateTime::Oct
, 1990 },
3797 { 27, wxDateTime::Oct
, 1991 },
3798 { 25, wxDateTime::Oct
, 1992 },
3799 { 31, wxDateTime::Oct
, 1993 },
3800 { 30, wxDateTime::Oct
, 1994 },
3801 { 29, wxDateTime::Oct
, 1995 },
3802 { 27, wxDateTime::Oct
, 1996 },
3803 { 26, wxDateTime::Oct
, 1997 },
3804 { 25, wxDateTime::Oct
, 1998 },
3805 { 31, wxDateTime::Oct
, 1999 },
3806 { 29, wxDateTime::Oct
, 2000 },
3807 { 28, wxDateTime::Oct
, 2001 },
3808 { 27, wxDateTime::Oct
, 2002 },
3809 { 26, wxDateTime::Oct
, 2003 },
3810 { 31, wxDateTime::Oct
, 2004 },
3815 for ( year
= 1990; year
< 2005; year
++ )
3817 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3818 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3820 printf("DST period in the US for year %d: from %s to %s",
3821 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3823 size_t n
= year
- 1990;
3824 const Date
& dBegin
= datesDST
[0][n
];
3825 const Date
& dEnd
= datesDST
[1][n
];
3827 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3833 printf(" (ERROR: should be %s %d to %s %d)\n",
3834 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3835 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3841 for ( year
= 1990; year
< 2005; year
++ )
3843 printf("DST period in Europe for year %d: from %s to %s\n",
3845 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3846 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3850 // test wxDateTime -> text conversion
3851 static void TestTimeFormat()
3853 puts("\n*** wxDateTime formatting test ***");
3855 // some information may be lost during conversion, so store what kind
3856 // of info should we recover after a round trip
3859 CompareNone
, // don't try comparing
3860 CompareBoth
, // dates and times should be identical
3861 CompareDate
, // dates only
3862 CompareTime
// time only
3867 CompareKind compareKind
;
3869 } formatTestFormats
[] =
3871 { CompareBoth
, "---> %c" },
3872 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3873 { CompareBoth
, "Date is %x, time is %X" },
3874 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3875 { CompareNone
, "The day of year: %j, the week of year: %W" },
3876 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3879 static const Date formatTestDates
[] =
3881 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3882 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3884 // this test can't work for other centuries because it uses two digit
3885 // years in formats, so don't even try it
3886 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3887 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3888 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3892 // an extra test (as it doesn't depend on date, don't do it in the loop)
3893 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3895 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3899 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3900 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3902 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3903 printf("%s", s
.c_str());
3905 // what can we recover?
3906 int kind
= formatTestFormats
[n
].compareKind
;
3910 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3913 // converion failed - should it have?
3914 if ( kind
== CompareNone
)
3917 puts(" (ERROR: conversion back failed)");
3921 // should have parsed the entire string
3922 puts(" (ERROR: conversion back stopped too soon)");
3926 bool equal
= FALSE
; // suppress compilaer warning
3934 equal
= dt
.IsSameDate(dt2
);
3938 equal
= dt
.IsSameTime(dt2
);
3944 printf(" (ERROR: got back '%s' instead of '%s')\n",
3945 dt2
.Format().c_str(), dt
.Format().c_str());
3956 // test text -> wxDateTime conversion
3957 static void TestTimeParse()
3959 puts("\n*** wxDateTime parse test ***");
3961 struct ParseTestData
3968 static const ParseTestData parseTestDates
[] =
3970 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3971 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3974 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3976 const char *format
= parseTestDates
[n
].format
;
3978 printf("%s => ", format
);
3981 if ( dt
.ParseRfc822Date(format
) )
3983 printf("%s ", dt
.Format().c_str());
3985 if ( parseTestDates
[n
].good
)
3987 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3994 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3999 puts("(ERROR: bad format)");
4004 printf("bad format (%s)\n",
4005 parseTestDates
[n
].good
? "ERROR" : "ok");
4010 static void TestDateTimeInteractive()
4012 puts("\n*** interactive wxDateTime tests ***");
4018 printf("Enter a date: ");
4019 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4022 // kill the last '\n'
4023 buf
[strlen(buf
) - 1] = 0;
4026 const char *p
= dt
.ParseDate(buf
);
4029 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4035 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4038 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4039 dt
.Format("%b %d, %Y").c_str(),
4041 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4042 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4043 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4046 puts("\n*** done ***");
4049 static void TestTimeMS()
4051 puts("*** testing millisecond-resolution support in wxDateTime ***");
4053 wxDateTime dt1
= wxDateTime::Now(),
4054 dt2
= wxDateTime::UNow();
4056 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4057 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4058 printf("Dummy loop: ");
4059 for ( int i
= 0; i
< 6000; i
++ )
4061 //for ( int j = 0; j < 10; j++ )
4064 s
.Printf("%g", sqrt(i
));
4073 dt2
= wxDateTime::UNow();
4074 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4076 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4078 puts("\n*** done ***");
4081 static void TestTimeArithmetics()
4083 puts("\n*** testing arithmetic operations on wxDateTime ***");
4085 static const struct ArithmData
4087 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4088 : span(sp
), name(nam
) { }
4092 } testArithmData
[] =
4094 ArithmData(wxDateSpan::Day(), "day"),
4095 ArithmData(wxDateSpan::Week(), "week"),
4096 ArithmData(wxDateSpan::Month(), "month"),
4097 ArithmData(wxDateSpan::Year(), "year"),
4098 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4101 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4103 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4105 wxDateSpan span
= testArithmData
[n
].span
;
4109 const char *name
= testArithmData
[n
].name
;
4110 printf("%s + %s = %s, %s - %s = %s\n",
4111 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4112 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4114 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4115 if ( dt1
- span
== dt
)
4121 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4124 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4125 if ( dt2
+ span
== dt
)
4131 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4134 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4135 if ( dt2
+ 2*span
== dt1
)
4141 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4148 static void TestTimeHolidays()
4150 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4152 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4153 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4154 dtEnd
= dtStart
.GetLastMonthDay();
4156 wxDateTimeArray hol
;
4157 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4159 const wxChar
*format
= "%d-%b-%Y (%a)";
4161 printf("All holidays between %s and %s:\n",
4162 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4164 size_t count
= hol
.GetCount();
4165 for ( size_t n
= 0; n
< count
; n
++ )
4167 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4173 static void TestTimeZoneBug()
4175 puts("\n*** testing for DST/timezone bug ***\n");
4177 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4178 for ( int i
= 0; i
< 31; i
++ )
4180 printf("Date %s: week day %s.\n",
4181 date
.Format(_T("%d-%m-%Y")).c_str(),
4182 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4184 date
+= wxDateSpan::Day();
4190 static void TestTimeSpanFormat()
4192 puts("\n*** wxTimeSpan tests ***");
4194 static const char *formats
[] =
4196 _T("(default) %H:%M:%S"),
4197 _T("%E weeks and %D days"),
4198 _T("%l milliseconds"),
4199 _T("(with ms) %H:%M:%S:%l"),
4200 _T("100%% of minutes is %M"), // test "%%"
4201 _T("%D days and %H hours"),
4202 _T("or also %S seconds"),
4205 wxTimeSpan
ts1(1, 2, 3, 4),
4207 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4209 printf("ts1 = %s\tts2 = %s\n",
4210 ts1
.Format(formats
[n
]).c_str(),
4211 ts2
.Format(formats
[n
]).c_str());
4219 // test compatibility with the old wxDate/wxTime classes
4220 static void TestTimeCompatibility()
4222 puts("\n*** wxDateTime compatibility test ***");
4224 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4225 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4227 double jdnNow
= wxDateTime::Now().GetJDN();
4228 long jdnMidnight
= (long)(jdnNow
- 0.5);
4229 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4231 jdnMidnight
= wxDate().Set().GetJulianDate();
4232 printf("wxDateTime for today: %s\n",
4233 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4235 int flags
= wxEUROPEAN
;//wxFULL;
4238 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4239 for ( int n
= 0; n
< 7; n
++ )
4241 printf("Previous %s is %s\n",
4242 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4243 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4249 #endif // TEST_DATETIME
4251 // ----------------------------------------------------------------------------
4253 // ----------------------------------------------------------------------------
4257 #include "wx/thread.h"
4259 static size_t gs_counter
= (size_t)-1;
4260 static wxCriticalSection gs_critsect
;
4261 static wxCondition gs_cond
;
4263 class MyJoinableThread
: public wxThread
4266 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4267 { m_n
= n
; Create(); }
4269 // thread execution starts here
4270 virtual ExitCode
Entry();
4276 wxThread::ExitCode
MyJoinableThread::Entry()
4278 unsigned long res
= 1;
4279 for ( size_t n
= 1; n
< m_n
; n
++ )
4283 // it's a loooong calculation :-)
4287 return (ExitCode
)res
;
4290 class MyDetachedThread
: public wxThread
4293 MyDetachedThread(size_t n
, char ch
)
4297 m_cancelled
= FALSE
;
4302 // thread execution starts here
4303 virtual ExitCode
Entry();
4306 virtual void OnExit();
4309 size_t m_n
; // number of characters to write
4310 char m_ch
; // character to write
4312 bool m_cancelled
; // FALSE if we exit normally
4315 wxThread::ExitCode
MyDetachedThread::Entry()
4318 wxCriticalSectionLocker
lock(gs_critsect
);
4319 if ( gs_counter
== (size_t)-1 )
4325 for ( size_t n
= 0; n
< m_n
; n
++ )
4327 if ( TestDestroy() )
4337 wxThread::Sleep(100);
4343 void MyDetachedThread::OnExit()
4345 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4347 wxCriticalSectionLocker
lock(gs_critsect
);
4348 if ( !--gs_counter
&& !m_cancelled
)
4352 void TestDetachedThreads()
4354 puts("\n*** Testing detached threads ***");
4356 static const size_t nThreads
= 3;
4357 MyDetachedThread
*threads
[nThreads
];
4359 for ( n
= 0; n
< nThreads
; n
++ )
4361 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4364 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4365 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4367 for ( n
= 0; n
< nThreads
; n
++ )
4372 // wait until all threads terminate
4378 void TestJoinableThreads()
4380 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4382 // calc 10! in the background
4383 MyJoinableThread
thread(10);
4386 printf("\nThread terminated with exit code %lu.\n",
4387 (unsigned long)thread
.Wait());
4390 void TestThreadSuspend()
4392 puts("\n*** Testing thread suspend/resume functions ***");
4394 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4398 // this is for this demo only, in a real life program we'd use another
4399 // condition variable which would be signaled from wxThread::Entry() to
4400 // tell us that the thread really started running - but here just wait a
4401 // bit and hope that it will be enough (the problem is, of course, that
4402 // the thread might still not run when we call Pause() which will result
4404 wxThread::Sleep(300);
4406 for ( size_t n
= 0; n
< 3; n
++ )
4410 puts("\nThread suspended");
4413 // don't sleep but resume immediately the first time
4414 wxThread::Sleep(300);
4416 puts("Going to resume the thread");
4421 puts("Waiting until it terminates now");
4423 // wait until the thread terminates
4429 void TestThreadDelete()
4431 // As above, using Sleep() is only for testing here - we must use some
4432 // synchronisation object instead to ensure that the thread is still
4433 // running when we delete it - deleting a detached thread which already
4434 // terminated will lead to a crash!
4436 puts("\n*** Testing thread delete function ***");
4438 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4442 puts("\nDeleted a thread which didn't start to run yet.");
4444 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4448 wxThread::Sleep(300);
4452 puts("\nDeleted a running thread.");
4454 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4458 wxThread::Sleep(300);
4464 puts("\nDeleted a sleeping thread.");
4466 MyJoinableThread
thread3(20);
4471 puts("\nDeleted a joinable thread.");
4473 MyJoinableThread
thread4(2);
4476 wxThread::Sleep(300);
4480 puts("\nDeleted a joinable thread which already terminated.");
4485 #endif // TEST_THREADS
4487 // ----------------------------------------------------------------------------
4489 // ----------------------------------------------------------------------------
4493 static void PrintArray(const char* name
, const wxArrayString
& array
)
4495 printf("Dump of the array '%s'\n", name
);
4497 size_t nCount
= array
.GetCount();
4498 for ( size_t n
= 0; n
< nCount
; n
++ )
4500 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4504 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4506 printf("Dump of the array '%s'\n", name
);
4508 size_t nCount
= array
.GetCount();
4509 for ( size_t n
= 0; n
< nCount
; n
++ )
4511 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4515 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4516 const wxString
& second
)
4518 return first
.length() - second
.length();
4521 int wxCMPFUNC_CONV
IntCompare(int *first
,
4524 return *first
- *second
;
4527 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4530 return *second
- *first
;
4533 static void TestArrayOfInts()
4535 puts("*** Testing wxArrayInt ***\n");
4546 puts("After sort:");
4550 puts("After reverse sort:");
4551 a
.Sort(IntRevCompare
);
4555 #include "wx/dynarray.h"
4557 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4558 #include "wx/arrimpl.cpp"
4559 WX_DEFINE_OBJARRAY(ArrayBars
);
4561 static void TestArrayOfObjects()
4563 puts("*** Testing wxObjArray ***\n");
4567 Bar
bar("second bar");
4569 printf("Initially: %u objects in the array, %u objects total.\n",
4570 bars
.GetCount(), Bar::GetNumber());
4572 bars
.Add(new Bar("first bar"));
4575 printf("Now: %u objects in the array, %u objects total.\n",
4576 bars
.GetCount(), Bar::GetNumber());
4580 printf("After Empty(): %u objects in the array, %u objects total.\n",
4581 bars
.GetCount(), Bar::GetNumber());
4584 printf("Finally: no more objects in the array, %u objects total.\n",
4588 #endif // TEST_ARRAYS
4590 // ----------------------------------------------------------------------------
4592 // ----------------------------------------------------------------------------
4596 #include "wx/timer.h"
4597 #include "wx/tokenzr.h"
4599 static void TestStringConstruction()
4601 puts("*** Testing wxString constructores ***");
4603 #define TEST_CTOR(args, res) \
4606 printf("wxString%s = %s ", #args, s.c_str()); \
4613 printf("(ERROR: should be %s)\n", res); \
4617 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4618 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4619 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4620 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4622 static const wxChar
*s
= _T("?really!");
4623 const wxChar
*start
= wxStrchr(s
, _T('r'));
4624 const wxChar
*end
= wxStrchr(s
, _T('!'));
4625 TEST_CTOR((start
, end
), _T("really"));
4630 static void TestString()
4640 for (int i
= 0; i
< 1000000; ++i
)
4644 c
= "! How'ya doin'?";
4647 c
= "Hello world! What's up?";
4652 printf ("TestString elapsed time: %ld\n", sw
.Time());
4655 static void TestPChar()
4663 for (int i
= 0; i
< 1000000; ++i
)
4665 strcpy (a
, "Hello");
4666 strcpy (b
, " world");
4667 strcpy (c
, "! How'ya doin'?");
4670 strcpy (c
, "Hello world! What's up?");
4671 if (strcmp (c
, a
) == 0)
4675 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4678 static void TestStringSub()
4680 wxString
s("Hello, world!");
4682 puts("*** Testing wxString substring extraction ***");
4684 printf("String = '%s'\n", s
.c_str());
4685 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4686 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4687 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4688 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4689 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4690 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4692 static const wxChar
*prefixes
[] =
4696 _T("Hello, world!"),
4697 _T("Hello, world!!!"),
4703 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4705 wxString prefix
= prefixes
[n
], rest
;
4706 bool rc
= s
.StartsWith(prefix
, &rest
);
4707 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4710 printf(" (the rest is '%s')\n", rest
.c_str());
4721 static void TestStringFormat()
4723 puts("*** Testing wxString formatting ***");
4726 s
.Printf("%03d", 18);
4728 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4729 printf("Number 18: %s\n", s
.c_str());
4734 // returns "not found" for npos, value for all others
4735 static wxString
PosToString(size_t res
)
4737 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4738 : wxString::Format(_T("%u"), res
);
4742 static void TestStringFind()
4744 puts("*** Testing wxString find() functions ***");
4746 static const wxChar
*strToFind
= _T("ell");
4747 static const struct StringFindTest
4751 result
; // of searching "ell" in str
4754 { _T("Well, hello world"), 0, 1 },
4755 { _T("Well, hello world"), 6, 7 },
4756 { _T("Well, hello world"), 9, wxString::npos
},
4759 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4761 const StringFindTest
& ft
= findTestData
[n
];
4762 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4764 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4765 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4767 size_t resTrue
= ft
.result
;
4768 if ( res
== resTrue
)
4774 printf(_T("(ERROR: should be %s)\n"),
4775 PosToString(resTrue
).c_str());
4782 static void TestStringTokenizer()
4784 puts("*** Testing wxStringTokenizer ***");
4786 static const wxChar
*modeNames
[] =
4790 _T("return all empty"),
4795 static const struct StringTokenizerTest
4797 const wxChar
*str
; // string to tokenize
4798 const wxChar
*delims
; // delimiters to use
4799 size_t count
; // count of token
4800 wxStringTokenizerMode mode
; // how should we tokenize it
4801 } tokenizerTestData
[] =
4803 { _T(""), _T(" "), 0 },
4804 { _T("Hello, world"), _T(" "), 2 },
4805 { _T("Hello, world "), _T(" "), 2 },
4806 { _T("Hello, world"), _T(","), 2 },
4807 { _T("Hello, world!"), _T(",!"), 2 },
4808 { _T("Hello,, world!"), _T(",!"), 3 },
4809 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4810 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4811 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4812 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4813 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4814 { _T("01/02/99"), _T("/-"), 3 },
4815 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4818 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4820 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4821 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4823 size_t count
= tkz
.CountTokens();
4824 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4825 MakePrintable(tt
.str
).c_str(),
4827 MakePrintable(tt
.delims
).c_str(),
4828 modeNames
[tkz
.GetMode()]);
4829 if ( count
== tt
.count
)
4835 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4840 // if we emulate strtok(), check that we do it correctly
4841 wxChar
*buf
, *s
= NULL
, *last
;
4843 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4845 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4846 wxStrcpy(buf
, tt
.str
);
4848 s
= wxStrtok(buf
, tt
.delims
, &last
);
4855 // now show the tokens themselves
4857 while ( tkz
.HasMoreTokens() )
4859 wxString token
= tkz
.GetNextToken();
4861 printf(_T("\ttoken %u: '%s'"),
4863 MakePrintable(token
).c_str());
4873 printf(" (ERROR: should be %s)\n", s
);
4876 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4880 // nothing to compare with
4885 if ( count2
!= count
)
4887 puts(_T("\tERROR: token count mismatch"));
4896 static void TestStringReplace()
4898 puts("*** Testing wxString::replace ***");
4900 static const struct StringReplaceTestData
4902 const wxChar
*original
; // original test string
4903 size_t start
, len
; // the part to replace
4904 const wxChar
*replacement
; // the replacement string
4905 const wxChar
*result
; // and the expected result
4906 } stringReplaceTestData
[] =
4908 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4909 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4910 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4911 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4912 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4915 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4917 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4919 wxString original
= data
.original
;
4920 original
.replace(data
.start
, data
.len
, data
.replacement
);
4922 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4923 data
.original
, data
.start
, data
.len
, data
.replacement
,
4926 if ( original
== data
.result
)
4932 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4939 static void TestStringMatch()
4941 wxPuts(_T("*** Testing wxString::Matches() ***"));
4943 static const struct StringMatchTestData
4946 const wxChar
*wildcard
;
4948 } stringMatchTestData
[] =
4950 { _T("foobar"), _T("foo*"), 1 },
4951 { _T("foobar"), _T("*oo*"), 1 },
4952 { _T("foobar"), _T("*bar"), 1 },
4953 { _T("foobar"), _T("??????"), 1 },
4954 { _T("foobar"), _T("f??b*"), 1 },
4955 { _T("foobar"), _T("f?b*"), 0 },
4956 { _T("foobar"), _T("*goo*"), 0 },
4957 { _T("foobar"), _T("*foo"), 0 },
4958 { _T("foobarfoo"), _T("*foo"), 1 },
4959 { _T(""), _T("*"), 1 },
4960 { _T(""), _T("?"), 0 },
4963 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4965 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4966 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4967 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4969 matches
? _T("matches") : _T("doesn't match"),
4971 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4977 #endif // TEST_STRINGS
4979 // ----------------------------------------------------------------------------
4981 // ----------------------------------------------------------------------------
4983 int main(int argc
, char **argv
)
4985 wxInitializer initializer
;
4988 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4993 #ifdef TEST_SNGLINST
4994 wxSingleInstanceChecker checker
;
4995 if ( checker
.Create(_T(".wxconsole.lock")) )
4997 if ( checker
.IsAnotherRunning() )
4999 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5004 // wait some time to give time to launch another instance
5005 wxPrintf(_T("Press \"Enter\" to continue..."));
5008 else // failed to create
5010 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5012 #endif // TEST_SNGLINST
5016 #endif // TEST_CHARSET
5019 TestCmdLineConvert();
5021 #if wxUSE_CMDLINE_PARSER
5022 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5024 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5025 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5026 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5027 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5029 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5030 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5031 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5032 wxCMD_LINE_VAL_NUMBER
},
5033 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5034 wxCMD_LINE_VAL_DATE
},
5036 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5037 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5042 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5044 parser
.AddOption("project_name", "", "full path to project file",
5045 wxCMD_LINE_VAL_STRING
,
5046 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5048 switch ( parser
.Parse() )
5051 wxLogMessage("Help was given, terminating.");
5055 ShowCmdLine(parser
);
5059 wxLogMessage("Syntax error detected, aborting.");
5062 #endif // wxUSE_CMDLINE_PARSER
5064 #endif // TEST_CMDLINE
5072 TestStringConstruction();
5075 TestStringTokenizer();
5076 TestStringReplace();
5079 #endif // TEST_STRINGS
5092 puts("*** Initially:");
5094 PrintArray("a1", a1
);
5096 wxArrayString
a2(a1
);
5097 PrintArray("a2", a2
);
5099 wxSortedArrayString
a3(a1
);
5100 PrintArray("a3", a3
);
5102 puts("*** After deleting a string from a1");
5105 PrintArray("a1", a1
);
5106 PrintArray("a2", a2
);
5107 PrintArray("a3", a3
);
5109 puts("*** After reassigning a1 to a2 and a3");
5111 PrintArray("a2", a2
);
5112 PrintArray("a3", a3
);
5114 puts("*** After sorting a1");
5116 PrintArray("a1", a1
);
5118 puts("*** After sorting a1 in reverse order");
5120 PrintArray("a1", a1
);
5122 puts("*** After sorting a1 by the string length");
5123 a1
.Sort(StringLenCompare
);
5124 PrintArray("a1", a1
);
5126 TestArrayOfObjects();
5129 #endif // TEST_ARRAYS
5137 #ifdef TEST_DLLLOADER
5139 #endif // TEST_DLLLOADER
5143 #endif // TEST_ENVIRON
5147 #endif // TEST_EXECUTE
5149 #ifdef TEST_FILECONF
5151 #endif // TEST_FILECONF
5159 #endif // TEST_LOCALE
5163 for ( size_t n
= 0; n
< 8000; n
++ )
5165 s
<< (char)('A' + (n
% 26));
5169 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5171 // this one shouldn't be truncated
5174 // but this one will because log functions use fixed size buffer
5175 // (note that it doesn't need '\n' at the end neither - will be added
5177 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5189 #ifdef TEST_FILENAME
5190 TestFileNameConstruction();
5191 TestFileNameSplit();
5195 TestFileNameComparison();
5196 TestFileNameOperations();
5198 #endif // TEST_FILENAME
5200 #ifdef TEST_FILETIME
5203 #endif // TEST_FILETIME
5206 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5207 if ( TestFtpConnect() )
5218 TestFtpInteractive();
5220 //else: connecting to the FTP server failed
5227 int nCPUs
= wxThread::GetCPUCount();
5228 printf("This system has %d CPUs\n", nCPUs
);
5230 wxThread::SetConcurrency(nCPUs
);
5232 if ( argc
> 1 && argv
[1][0] == 't' )
5233 wxLog::AddTraceMask("thread");
5236 TestDetachedThreads();
5238 TestJoinableThreads();
5240 TestThreadSuspend();
5244 #endif // TEST_THREADS
5246 #ifdef TEST_LONGLONG
5247 // seed pseudo random generator
5248 srand((unsigned)time(NULL
));
5256 TestMultiplication();
5259 TestLongLongConversion();
5260 TestBitOperations();
5261 TestLongLongComparison();
5263 TestLongLongPrint();
5264 #endif // TEST_LONGLONG
5271 wxLog::AddTraceMask(_T("mime"));
5279 TestMimeAssociate();
5282 #ifdef TEST_INFO_FUNCTIONS
5289 #endif // TEST_INFO_FUNCTIONS
5291 #ifdef TEST_PATHLIST
5293 #endif // TEST_PATHLIST
5297 #endif // TEST_REGCONF
5300 // TODO: write a real test using src/regex/tests file
5305 TestRegExSubmatch();
5306 TestRegExInteractive();
5308 TestRegExReplacement();
5309 #endif // TEST_REGEX
5311 #ifdef TEST_REGISTRY
5314 TestRegistryAssociation();
5315 #endif // TEST_REGISTRY
5323 #endif // TEST_SOCKETS
5329 #endif // TEST_STREAMS
5333 #endif // TEST_TIMER
5335 #ifdef TEST_DATETIME
5348 TestTimeArithmetics();
5355 TestTimeSpanFormat();
5357 TestDateTimeInteractive();
5358 #endif // TEST_DATETIME
5361 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5363 #endif // TEST_USLEEP
5369 #endif // TEST_VCARD
5373 #endif // TEST_WCHAR
5377 TestZipStreamRead();
5378 TestZipFileSystem();
5383 TestZlibStreamWrite();
5384 TestZlibStreamRead();