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 TestFileNameTemp()
849 puts("*** testing wxFileName temp file creation ***");
851 static const char *tmpprefixes
[] =
857 "/tmp/foo/bar", // this one must be an error
860 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
862 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
865 printf("Prefix '%s'\t-> temp file '%s'\n",
866 tmpprefixes
[n
], path
.c_str());
868 if ( !wxRemoveFile(path
) )
870 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
876 static void TestFileNameComparison()
881 static void TestFileNameOperations()
886 static void TestFileNameCwd()
891 #endif // TEST_FILENAME
893 // ----------------------------------------------------------------------------
894 // wxFileName time functions
895 // ----------------------------------------------------------------------------
899 #include <wx/filename.h>
900 #include <wx/datetime.h>
902 static void TestFileGetTimes()
904 wxFileName
fn(_T("testdata.fc"));
906 wxDateTime dtAccess
, dtMod
, dtChange
;
907 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
909 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
913 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
915 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
916 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
917 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
918 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
922 static void TestFileSetTimes()
924 wxFileName
fn(_T("testdata.fc"));
926 wxDateTime dtAccess
, dtMod
, dtChange
;
929 wxPrintf(_T("ERROR: Touch() failed.\n"));
933 #endif // TEST_FILETIME
935 // ----------------------------------------------------------------------------
937 // ----------------------------------------------------------------------------
945 Foo(int n_
) { n
= n_
; count
++; }
953 size_t Foo::count
= 0;
955 WX_DECLARE_LIST(Foo
, wxListFoos
);
956 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
958 #include "wx/listimpl.cpp"
960 WX_DEFINE_LIST(wxListFoos
);
962 static void TestHash()
964 puts("*** Testing wxHashTable ***\n");
968 hash
.DeleteContents(TRUE
);
970 printf("Hash created: %u foos in hash, %u foos totally\n",
971 hash
.GetCount(), Foo::count
);
973 static const int hashTestData
[] =
975 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
979 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
981 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
984 printf("Hash filled: %u foos in hash, %u foos totally\n",
985 hash
.GetCount(), Foo::count
);
987 puts("Hash access test:");
988 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
990 printf("\tGetting element with key %d, value %d: ",
992 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
995 printf("ERROR, not found.\n");
999 printf("%d (%s)\n", foo
->n
,
1000 (size_t)foo
->n
== n
? "ok" : "ERROR");
1004 printf("\nTrying to get an element not in hash: ");
1006 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1008 puts("ERROR: found!");
1012 puts("ok (not found)");
1016 printf("Hash destroyed: %u foos left\n", Foo::count
);
1021 // ----------------------------------------------------------------------------
1023 // ----------------------------------------------------------------------------
1027 #include "wx/list.h"
1029 WX_DECLARE_LIST(Bar
, wxListBars
);
1030 #include "wx/listimpl.cpp"
1031 WX_DEFINE_LIST(wxListBars
);
1033 static void TestListCtor()
1035 puts("*** Testing wxList construction ***\n");
1039 list1
.Append(new Bar(_T("first")));
1040 list1
.Append(new Bar(_T("second")));
1042 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1043 list1
.GetCount(), Bar::GetNumber());
1048 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1049 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1051 list1
.DeleteContents(TRUE
);
1054 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1059 // ----------------------------------------------------------------------------
1061 // ----------------------------------------------------------------------------
1065 #include "wx/intl.h"
1066 #include "wx/utils.h" // for wxSetEnv
1068 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1070 // find the name of the language from its value
1071 static const char *GetLangName(int lang
)
1073 static const char *languageNames
[] =
1094 "ARABIC_SAUDI_ARABIA",
1119 "CHINESE_SIMPLIFIED",
1120 "CHINESE_TRADITIONAL",
1123 "CHINESE_SINGAPORE",
1134 "ENGLISH_AUSTRALIA",
1138 "ENGLISH_CARIBBEAN",
1142 "ENGLISH_NEW_ZEALAND",
1143 "ENGLISH_PHILIPPINES",
1144 "ENGLISH_SOUTH_AFRICA",
1156 "FRENCH_LUXEMBOURG",
1165 "GERMAN_LIECHTENSTEIN",
1166 "GERMAN_LUXEMBOURG",
1207 "MALAY_BRUNEI_DARUSSALAM",
1219 "NORWEGIAN_NYNORSK",
1226 "PORTUGUESE_BRAZILIAN",
1251 "SPANISH_ARGENTINA",
1255 "SPANISH_COSTA_RICA",
1256 "SPANISH_DOMINICAN_REPUBLIC",
1258 "SPANISH_EL_SALVADOR",
1259 "SPANISH_GUATEMALA",
1263 "SPANISH_NICARAGUA",
1267 "SPANISH_PUERTO_RICO",
1270 "SPANISH_VENEZUELA",
1307 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1308 return languageNames
[lang
];
1313 static void TestDefaultLang()
1315 puts("*** Testing wxLocale::GetSystemLanguage ***");
1317 static const wxChar
*langStrings
[] =
1319 NULL
, // system default
1326 _T("de_DE.iso88591"),
1328 _T("?"), // invalid lang spec
1329 _T("klingonese"), // I bet on some systems it does exist...
1332 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1333 wxLocale::GetSystemEncodingName().c_str(),
1334 wxLocale::GetSystemEncoding());
1336 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1338 const char *langStr
= langStrings
[n
];
1341 // FIXME: this doesn't do anything at all under Windows, we need
1342 // to create a new wxLocale!
1343 wxSetEnv(_T("LC_ALL"), langStr
);
1346 int lang
= gs_localeDefault
.GetSystemLanguage();
1347 printf("Locale for '%s' is %s.\n",
1348 langStr
? langStr
: "system default", GetLangName(lang
));
1352 #endif // TEST_LOCALE
1354 // ----------------------------------------------------------------------------
1356 // ----------------------------------------------------------------------------
1360 #include "wx/mimetype.h"
1362 static void TestMimeEnum()
1364 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1366 wxArrayString mimetypes
;
1368 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1370 printf("*** All %u known filetypes: ***\n", count
);
1375 for ( size_t n
= 0; n
< count
; n
++ )
1377 wxFileType
*filetype
=
1378 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1381 printf("nothing known about the filetype '%s'!\n",
1382 mimetypes
[n
].c_str());
1386 filetype
->GetDescription(&desc
);
1387 filetype
->GetExtensions(exts
);
1389 filetype
->GetIcon(NULL
);
1392 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1395 extsAll
<< _T(", ");
1399 printf("\t%s: %s (%s)\n",
1400 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1406 static void TestMimeOverride()
1408 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1410 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1411 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1413 if ( wxFile::Exists(mailcap
) )
1414 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1416 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1418 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1421 if ( wxFile::Exists(mimetypes
) )
1422 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1424 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1426 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1432 static void TestMimeFilename()
1434 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1436 static const wxChar
*filenames
[] =
1443 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1445 const wxString fname
= filenames
[n
];
1446 wxString ext
= fname
.AfterLast(_T('.'));
1447 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1450 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1455 if ( !ft
->GetDescription(&desc
) )
1456 desc
= _T("<no description>");
1459 if ( !ft
->GetOpenCommand(&cmd
,
1460 wxFileType::MessageParameters(fname
, _T(""))) )
1461 cmd
= _T("<no command available>");
1463 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1464 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1473 static void TestMimeAssociate()
1475 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1477 wxFileTypeInfo
ftInfo(
1478 _T("application/x-xyz"),
1479 _T("xyzview '%s'"), // open cmd
1480 _T(""), // print cmd
1481 _T("XYZ File") // description
1482 _T(".xyz"), // extensions
1483 NULL
// end of extensions
1485 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1487 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1490 wxPuts(_T("ERROR: failed to create association!"));
1494 // TODO: read it back
1503 // ----------------------------------------------------------------------------
1504 // misc information functions
1505 // ----------------------------------------------------------------------------
1507 #ifdef TEST_INFO_FUNCTIONS
1509 #include "wx/utils.h"
1511 static void TestDiskInfo()
1513 puts("*** Testing wxGetDiskSpace() ***");
1518 printf("\nEnter a directory name: ");
1519 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1522 // kill the last '\n'
1523 pathname
[strlen(pathname
) - 1] = 0;
1525 wxLongLong total
, free
;
1526 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1528 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1532 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1533 (total
/ 1024).ToString().c_str(),
1534 (free
/ 1024).ToString().c_str(),
1540 static void TestOsInfo()
1542 puts("*** Testing OS info functions ***\n");
1545 wxGetOsVersion(&major
, &minor
);
1546 printf("Running under: %s, version %d.%d\n",
1547 wxGetOsDescription().c_str(), major
, minor
);
1549 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1551 printf("Host name is %s (%s).\n",
1552 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1557 static void TestUserInfo()
1559 puts("*** Testing user info functions ***\n");
1561 printf("User id is:\t%s\n", wxGetUserId().c_str());
1562 printf("User name is:\t%s\n", wxGetUserName().c_str());
1563 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1564 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1569 #endif // TEST_INFO_FUNCTIONS
1571 // ----------------------------------------------------------------------------
1573 // ----------------------------------------------------------------------------
1575 #ifdef TEST_LONGLONG
1577 #include "wx/longlong.h"
1578 #include "wx/timer.h"
1580 // make a 64 bit number from 4 16 bit ones
1581 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1583 // get a random 64 bit number
1584 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1586 static const long testLongs
[] =
1597 #if wxUSE_LONGLONG_WX
1598 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1599 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1600 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1601 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1602 #endif // wxUSE_LONGLONG_WX
1604 static void TestSpeed()
1606 static const long max
= 100000000;
1613 for ( n
= 0; n
< max
; n
++ )
1618 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1621 #if wxUSE_LONGLONG_NATIVE
1626 for ( n
= 0; n
< max
; n
++ )
1631 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1633 #endif // wxUSE_LONGLONG_NATIVE
1639 for ( n
= 0; n
< max
; n
++ )
1644 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1648 static void TestLongLongConversion()
1650 puts("*** Testing wxLongLong conversions ***\n");
1654 for ( size_t n
= 0; n
< 100000; n
++ )
1658 #if wxUSE_LONGLONG_NATIVE
1659 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1661 wxASSERT_MSG( a
== b
, "conversions failure" );
1663 puts("Can't do it without native long long type, test skipped.");
1666 #endif // wxUSE_LONGLONG_NATIVE
1668 if ( !(nTested
% 1000) )
1680 static void TestMultiplication()
1682 puts("*** Testing wxLongLong multiplication ***\n");
1686 for ( size_t n
= 0; n
< 100000; n
++ )
1691 #if wxUSE_LONGLONG_NATIVE
1692 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1693 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1695 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1696 #else // !wxUSE_LONGLONG_NATIVE
1697 puts("Can't do it without native long long type, test skipped.");
1700 #endif // wxUSE_LONGLONG_NATIVE
1702 if ( !(nTested
% 1000) )
1714 static void TestDivision()
1716 puts("*** Testing wxLongLong division ***\n");
1720 for ( size_t n
= 0; n
< 100000; n
++ )
1722 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1723 // multiplication will not overflow)
1724 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1726 // get a random long (not wxLongLong for now) to divide it with
1731 #if wxUSE_LONGLONG_NATIVE
1732 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1734 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1735 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1736 #else // !wxUSE_LONGLONG_NATIVE
1737 // verify the result
1738 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1739 #endif // wxUSE_LONGLONG_NATIVE
1741 if ( !(nTested
% 1000) )
1753 static void TestAddition()
1755 puts("*** Testing wxLongLong addition ***\n");
1759 for ( size_t n
= 0; n
< 100000; n
++ )
1765 #if wxUSE_LONGLONG_NATIVE
1766 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1767 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1768 "addition failure" );
1769 #else // !wxUSE_LONGLONG_NATIVE
1770 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1771 #endif // wxUSE_LONGLONG_NATIVE
1773 if ( !(nTested
% 1000) )
1785 static void TestBitOperations()
1787 puts("*** Testing wxLongLong bit operation ***\n");
1791 for ( size_t n
= 0; n
< 100000; n
++ )
1795 #if wxUSE_LONGLONG_NATIVE
1796 for ( size_t n
= 0; n
< 33; n
++ )
1799 #else // !wxUSE_LONGLONG_NATIVE
1800 puts("Can't do it without native long long type, test skipped.");
1803 #endif // wxUSE_LONGLONG_NATIVE
1805 if ( !(nTested
% 1000) )
1817 static void TestLongLongComparison()
1819 #if wxUSE_LONGLONG_WX
1820 puts("*** Testing wxLongLong comparison ***\n");
1822 static const long ls
[2] =
1828 wxLongLongWx lls
[2];
1832 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1836 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1838 res
= lls
[m
] > testLongs
[n
];
1839 printf("0x%lx > 0x%lx is %s (%s)\n",
1840 ls
[m
], testLongs
[n
], res
? "true" : "false",
1841 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1843 res
= lls
[m
] < testLongs
[n
];
1844 printf("0x%lx < 0x%lx is %s (%s)\n",
1845 ls
[m
], testLongs
[n
], res
? "true" : "false",
1846 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1848 res
= lls
[m
] == testLongs
[n
];
1849 printf("0x%lx == 0x%lx is %s (%s)\n",
1850 ls
[m
], testLongs
[n
], res
? "true" : "false",
1851 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1854 #endif // wxUSE_LONGLONG_WX
1857 static void TestLongLongPrint()
1859 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1861 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1863 wxLongLong ll
= testLongs
[n
];
1864 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1867 wxLongLong
ll(0x12345678, 0x87654321);
1868 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1871 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1877 #endif // TEST_LONGLONG
1879 // ----------------------------------------------------------------------------
1881 // ----------------------------------------------------------------------------
1883 #ifdef TEST_PATHLIST
1885 static void TestPathList()
1887 puts("*** Testing wxPathList ***\n");
1889 wxPathList pathlist
;
1890 pathlist
.AddEnvList("PATH");
1891 wxString path
= pathlist
.FindValidPath("ls");
1894 printf("ERROR: command not found in the path.\n");
1898 printf("Command found in the path as '%s'.\n", path
.c_str());
1902 #endif // TEST_PATHLIST
1904 // ----------------------------------------------------------------------------
1905 // regular expressions
1906 // ----------------------------------------------------------------------------
1910 #include "wx/regex.h"
1912 static void TestRegExCompile()
1914 wxPuts(_T("*** Testing RE compilation ***\n"));
1916 static struct RegExCompTestData
1918 const wxChar
*pattern
;
1920 } regExCompTestData
[] =
1922 { _T("foo"), TRUE
},
1923 { _T("foo("), FALSE
},
1924 { _T("foo(bar"), FALSE
},
1925 { _T("foo(bar)"), TRUE
},
1926 { _T("foo["), FALSE
},
1927 { _T("foo[bar"), FALSE
},
1928 { _T("foo[bar]"), TRUE
},
1929 { _T("foo{"), TRUE
},
1930 { _T("foo{1"), FALSE
},
1931 { _T("foo{bar"), TRUE
},
1932 { _T("foo{1}"), TRUE
},
1933 { _T("foo{1,2}"), TRUE
},
1934 { _T("foo{bar}"), TRUE
},
1935 { _T("foo*"), TRUE
},
1936 { _T("foo**"), FALSE
},
1937 { _T("foo+"), TRUE
},
1938 { _T("foo++"), FALSE
},
1939 { _T("foo?"), TRUE
},
1940 { _T("foo??"), FALSE
},
1941 { _T("foo?+"), FALSE
},
1945 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1947 const RegExCompTestData
& data
= regExCompTestData
[n
];
1948 bool ok
= re
.Compile(data
.pattern
);
1950 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1952 ok
? _T("") : _T("not "),
1953 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1957 static void TestRegExMatch()
1959 wxPuts(_T("*** Testing RE matching ***\n"));
1961 static struct RegExMatchTestData
1963 const wxChar
*pattern
;
1966 } regExMatchTestData
[] =
1968 { _T("foo"), _T("bar"), FALSE
},
1969 { _T("foo"), _T("foobar"), TRUE
},
1970 { _T("^foo"), _T("foobar"), TRUE
},
1971 { _T("^foo"), _T("barfoo"), FALSE
},
1972 { _T("bar$"), _T("barbar"), TRUE
},
1973 { _T("bar$"), _T("barbar "), FALSE
},
1976 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1978 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1980 wxRegEx
re(data
.pattern
);
1981 bool ok
= re
.Matches(data
.text
);
1983 wxPrintf(_T("'%s' %s %s (%s)\n"),
1985 ok
? _T("matches") : _T("doesn't match"),
1987 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1991 static void TestRegExSubmatch()
1993 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1995 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1996 if ( !re
.IsValid() )
1998 wxPuts(_T("ERROR: compilation failed."));
2002 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2004 if ( !re
.Matches(text
) )
2006 wxPuts(_T("ERROR: match expected."));
2010 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2012 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2013 re
.GetMatch(text
, 3).c_str(),
2014 re
.GetMatch(text
, 2).c_str(),
2015 re
.GetMatch(text
, 4).c_str(),
2016 re
.GetMatch(text
, 1).c_str());
2020 static void TestRegExReplacement()
2022 wxPuts(_T("*** Testing RE replacement ***"));
2024 static struct RegExReplTestData
2028 const wxChar
*result
;
2030 } regExReplTestData
[] =
2032 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2033 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2034 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2035 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2036 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2037 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2038 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2041 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2042 wxRegEx re
= pattern
;
2044 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2046 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2048 const RegExReplTestData
& data
= regExReplTestData
[n
];
2050 wxString text
= data
.text
;
2051 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2053 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2054 data
.text
, data
.repl
,
2055 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2057 if ( text
== data
.result
&& nRepl
== data
.count
)
2063 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2064 data
.count
, data
.result
);
2069 static void TestRegExInteractive()
2071 wxPuts(_T("*** Testing RE interactively ***"));
2076 printf("\nEnter a pattern: ");
2077 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2080 // kill the last '\n'
2081 pattern
[strlen(pattern
) - 1] = 0;
2084 if ( !re
.Compile(pattern
) )
2092 printf("Enter text to match: ");
2093 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2096 // kill the last '\n'
2097 text
[strlen(text
) - 1] = 0;
2099 if ( !re
.Matches(text
) )
2101 printf("No match.\n");
2105 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2108 for ( size_t n
= 1; ; n
++ )
2110 if ( !re
.GetMatch(&start
, &len
, n
) )
2115 printf("Subexpr %u matched '%s'\n",
2116 n
, wxString(text
+ start
, len
).c_str());
2123 #endif // TEST_REGEX
2125 // ----------------------------------------------------------------------------
2126 // registry and related stuff
2127 // ----------------------------------------------------------------------------
2129 // this is for MSW only
2132 #undef TEST_REGISTRY
2137 #include "wx/confbase.h"
2138 #include "wx/msw/regconf.h"
2140 static void TestRegConfWrite()
2142 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2143 regconf
.Write(_T("Hello"), wxString(_T("world")));
2146 #endif // TEST_REGCONF
2148 #ifdef TEST_REGISTRY
2150 #include "wx/msw/registry.h"
2152 // I chose this one because I liked its name, but it probably only exists under
2154 static const wxChar
*TESTKEY
=
2155 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2157 static void TestRegistryRead()
2159 puts("*** testing registry reading ***");
2161 wxRegKey
key(TESTKEY
);
2162 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2165 puts("ERROR: test key can't be opened, aborting test.");
2170 size_t nSubKeys
, nValues
;
2171 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2173 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2176 printf("Enumerating values:\n");
2180 bool cont
= key
.GetFirstValue(value
, dummy
);
2183 printf("Value '%s': type ", value
.c_str());
2184 switch ( key
.GetValueType(value
) )
2186 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2187 case wxRegKey::Type_String
: printf("SZ"); break;
2188 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2189 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2190 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2191 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2192 default: printf("other (unknown)"); break;
2195 printf(", value = ");
2196 if ( key
.IsNumericValue(value
) )
2199 key
.QueryValue(value
, &val
);
2205 key
.QueryValue(value
, val
);
2206 printf("'%s'", val
.c_str());
2208 key
.QueryRawValue(value
, val
);
2209 printf(" (raw value '%s')", val
.c_str());
2214 cont
= key
.GetNextValue(value
, dummy
);
2218 static void TestRegistryAssociation()
2221 The second call to deleteself genertaes an error message, with a
2222 messagebox saying .flo is crucial to system operation, while the .ddf
2223 call also fails, but with no error message
2228 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2230 key
= "ddxf_auto_file" ;
2231 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2233 key
= "ddxf_auto_file" ;
2234 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2237 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2239 key
= "program \"%1\"" ;
2241 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2243 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2245 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2247 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2251 #endif // TEST_REGISTRY
2253 // ----------------------------------------------------------------------------
2255 // ----------------------------------------------------------------------------
2259 #include "wx/socket.h"
2260 #include "wx/protocol/protocol.h"
2261 #include "wx/protocol/http.h"
2263 static void TestSocketServer()
2265 puts("*** Testing wxSocketServer ***\n");
2267 static const int PORT
= 3000;
2272 wxSocketServer
*server
= new wxSocketServer(addr
);
2273 if ( !server
->Ok() )
2275 puts("ERROR: failed to bind");
2282 printf("Server: waiting for connection on port %d...\n", PORT
);
2284 wxSocketBase
*socket
= server
->Accept();
2287 puts("ERROR: wxSocketServer::Accept() failed.");
2291 puts("Server: got a client.");
2293 server
->SetTimeout(60); // 1 min
2295 while ( socket
->IsConnected() )
2301 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2303 // don't log error if the client just close the connection
2304 if ( socket
->IsConnected() )
2306 puts("ERROR: in wxSocket::Read.");
2326 printf("Server: got '%s'.\n", s
.c_str());
2327 if ( s
== _T("bye") )
2334 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2335 socket
->Write("\r\n", 2);
2336 printf("Server: wrote '%s'.\n", s
.c_str());
2339 puts("Server: lost a client.");
2344 // same as "delete server" but is consistent with GUI programs
2348 static void TestSocketClient()
2350 puts("*** Testing wxSocketClient ***\n");
2352 static const char *hostname
= "www.wxwindows.org";
2355 addr
.Hostname(hostname
);
2358 printf("--- Attempting to connect to %s:80...\n", hostname
);
2360 wxSocketClient client
;
2361 if ( !client
.Connect(addr
) )
2363 printf("ERROR: failed to connect to %s\n", hostname
);
2367 printf("--- Connected to %s:%u...\n",
2368 addr
.Hostname().c_str(), addr
.Service());
2372 // could use simply "GET" here I suppose
2374 wxString::Format("GET http://%s/\r\n", hostname
);
2375 client
.Write(cmdGet
, cmdGet
.length());
2376 printf("--- Sent command '%s' to the server\n",
2377 MakePrintable(cmdGet
).c_str());
2378 client
.Read(buf
, WXSIZEOF(buf
));
2379 printf("--- Server replied:\n%s", buf
);
2383 #endif // TEST_SOCKETS
2385 // ----------------------------------------------------------------------------
2387 // ----------------------------------------------------------------------------
2391 #include "wx/protocol/ftp.h"
2395 #define FTP_ANONYMOUS
2397 #ifdef FTP_ANONYMOUS
2398 static const char *directory
= "/pub";
2399 static const char *filename
= "welcome.msg";
2401 static const char *directory
= "/etc";
2402 static const char *filename
= "issue";
2405 static bool TestFtpConnect()
2407 puts("*** Testing FTP connect ***");
2409 #ifdef FTP_ANONYMOUS
2410 static const char *hostname
= "ftp.wxwindows.org";
2412 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2413 #else // !FTP_ANONYMOUS
2414 static const char *hostname
= "localhost";
2417 fgets(user
, WXSIZEOF(user
), stdin
);
2418 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2422 printf("Password for %s: ", password
);
2423 fgets(password
, WXSIZEOF(password
), stdin
);
2424 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2425 ftp
.SetPassword(password
);
2427 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2428 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2430 if ( !ftp
.Connect(hostname
) )
2432 printf("ERROR: failed to connect to %s\n", hostname
);
2438 printf("--- Connected to %s, current directory is '%s'\n",
2439 hostname
, ftp
.Pwd().c_str());
2445 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2446 static void TestFtpWuFtpd()
2449 static const char *hostname
= "ftp.eudora.com";
2450 if ( !ftp
.Connect(hostname
) )
2452 printf("ERROR: failed to connect to %s\n", hostname
);
2456 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2457 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2460 printf("ERROR: couldn't get input stream for %s\n", filename
);
2464 size_t size
= in
->StreamSize();
2465 printf("Reading file %s (%u bytes)...", filename
, size
);
2467 char *data
= new char[size
];
2468 if ( !in
->Read(data
, size
) )
2470 puts("ERROR: read error");
2474 printf("Successfully retrieved the file.\n");
2483 static void TestFtpList()
2485 puts("*** Testing wxFTP file listing ***\n");
2488 if ( !ftp
.ChDir(directory
) )
2490 printf("ERROR: failed to cd to %s\n", directory
);
2493 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2495 // test NLIST and LIST
2496 wxArrayString files
;
2497 if ( !ftp
.GetFilesList(files
) )
2499 puts("ERROR: failed to get NLIST of files");
2503 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2504 size_t count
= files
.GetCount();
2505 for ( size_t n
= 0; n
< count
; n
++ )
2507 printf("\t%s\n", files
[n
].c_str());
2509 puts("End of the file list");
2512 if ( !ftp
.GetDirList(files
) )
2514 puts("ERROR: failed to get LIST of files");
2518 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2519 size_t count
= files
.GetCount();
2520 for ( size_t n
= 0; n
< count
; n
++ )
2522 printf("\t%s\n", files
[n
].c_str());
2524 puts("End of the file list");
2527 if ( !ftp
.ChDir(_T("..")) )
2529 puts("ERROR: failed to cd to ..");
2532 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2535 static void TestFtpDownload()
2537 puts("*** Testing wxFTP download ***\n");
2540 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2543 printf("ERROR: couldn't get input stream for %s\n", filename
);
2547 size_t size
= in
->StreamSize();
2548 printf("Reading file %s (%u bytes)...", filename
, size
);
2551 char *data
= new char[size
];
2552 if ( !in
->Read(data
, size
) )
2554 puts("ERROR: read error");
2558 printf("\nContents of %s:\n%s\n", filename
, data
);
2566 static void TestFtpFileSize()
2568 puts("*** Testing FTP SIZE command ***");
2570 if ( !ftp
.ChDir(directory
) )
2572 printf("ERROR: failed to cd to %s\n", directory
);
2575 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2577 if ( ftp
.FileExists(filename
) )
2579 int size
= ftp
.GetFileSize(filename
);
2581 printf("ERROR: couldn't get size of '%s'\n", filename
);
2583 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2587 printf("ERROR: '%s' doesn't exist\n", filename
);
2591 static void TestFtpMisc()
2593 puts("*** Testing miscellaneous wxFTP functions ***");
2595 if ( ftp
.SendCommand("STAT") != '2' )
2597 puts("ERROR: STAT failed");
2601 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2604 if ( ftp
.SendCommand("HELP SITE") != '2' )
2606 puts("ERROR: HELP SITE failed");
2610 printf("The list of site-specific commands:\n\n%s\n",
2611 ftp
.GetLastResult().c_str());
2615 static void TestFtpInteractive()
2617 puts("\n*** Interactive wxFTP test ***");
2623 printf("Enter FTP command: ");
2624 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2627 // kill the last '\n'
2628 buf
[strlen(buf
) - 1] = 0;
2630 // special handling of LIST and NLST as they require data connection
2631 wxString
start(buf
, 4);
2633 if ( start
== "LIST" || start
== "NLST" )
2636 if ( strlen(buf
) > 4 )
2639 wxArrayString files
;
2640 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2642 printf("ERROR: failed to get %s of files\n", start
.c_str());
2646 printf("--- %s of '%s' under '%s':\n",
2647 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2648 size_t count
= files
.GetCount();
2649 for ( size_t n
= 0; n
< count
; n
++ )
2651 printf("\t%s\n", files
[n
].c_str());
2653 puts("--- End of the file list");
2658 char ch
= ftp
.SendCommand(buf
);
2659 printf("Command %s", ch
? "succeeded" : "failed");
2662 printf(" (return code %c)", ch
);
2665 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2669 puts("\n*** done ***");
2672 static void TestFtpUpload()
2674 puts("*** Testing wxFTP uploading ***\n");
2677 static const char *file1
= "test1";
2678 static const char *file2
= "test2";
2679 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2682 printf("--- Uploading to %s ---\n", file1
);
2683 out
->Write("First hello", 11);
2687 // send a command to check the remote file
2688 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2690 printf("ERROR: STAT %s failed\n", file1
);
2694 printf("STAT %s returned:\n\n%s\n",
2695 file1
, ftp
.GetLastResult().c_str());
2698 out
= ftp
.GetOutputStream(file2
);
2701 printf("--- Uploading to %s ---\n", file1
);
2702 out
->Write("Second hello", 12);
2709 // ----------------------------------------------------------------------------
2711 // ----------------------------------------------------------------------------
2715 #include "wx/wfstream.h"
2716 #include "wx/mstream.h"
2718 static void TestFileStream()
2720 puts("*** Testing wxFileInputStream ***");
2722 static const wxChar
*filename
= _T("testdata.fs");
2724 wxFileOutputStream
fsOut(filename
);
2725 fsOut
.Write("foo", 3);
2728 wxFileInputStream
fsIn(filename
);
2729 printf("File stream size: %u\n", fsIn
.GetSize());
2730 while ( !fsIn
.Eof() )
2732 putchar(fsIn
.GetC());
2735 if ( !wxRemoveFile(filename
) )
2737 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2740 puts("\n*** wxFileInputStream test done ***");
2743 static void TestMemoryStream()
2745 puts("*** Testing wxMemoryInputStream ***");
2748 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2750 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2751 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2752 while ( !memInpStream
.Eof() )
2754 putchar(memInpStream
.GetC());
2757 puts("\n*** wxMemoryInputStream test done ***");
2760 #endif // TEST_STREAMS
2762 // ----------------------------------------------------------------------------
2764 // ----------------------------------------------------------------------------
2768 #include "wx/timer.h"
2769 #include "wx/utils.h"
2771 static void TestStopWatch()
2773 puts("*** Testing wxStopWatch ***\n");
2776 printf("Sleeping 3 seconds...");
2778 printf("\telapsed time: %ldms\n", sw
.Time());
2781 printf("Sleeping 2 more seconds...");
2783 printf("\telapsed time: %ldms\n", sw
.Time());
2786 printf("And 3 more seconds...");
2788 printf("\telapsed time: %ldms\n", sw
.Time());
2791 puts("\nChecking for 'backwards clock' bug...");
2792 for ( size_t n
= 0; n
< 70; n
++ )
2796 for ( size_t m
= 0; m
< 100000; m
++ )
2798 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2800 puts("\ntime is negative - ERROR!");
2810 #endif // TEST_TIMER
2812 // ----------------------------------------------------------------------------
2814 // ----------------------------------------------------------------------------
2818 #include "wx/vcard.h"
2820 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2823 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2827 wxString(_T('\t'), level
).c_str(),
2828 vcObj
->GetName().c_str());
2831 switch ( vcObj
->GetType() )
2833 case wxVCardObject::String
:
2834 case wxVCardObject::UString
:
2837 vcObj
->GetValue(&val
);
2838 value
<< _T('"') << val
<< _T('"');
2842 case wxVCardObject::Int
:
2845 vcObj
->GetValue(&i
);
2846 value
.Printf(_T("%u"), i
);
2850 case wxVCardObject::Long
:
2853 vcObj
->GetValue(&l
);
2854 value
.Printf(_T("%lu"), l
);
2858 case wxVCardObject::None
:
2861 case wxVCardObject::Object
:
2862 value
= _T("<node>");
2866 value
= _T("<unknown value type>");
2870 printf(" = %s", value
.c_str());
2873 DumpVObject(level
+ 1, *vcObj
);
2876 vcObj
= vcard
.GetNextProp(&cookie
);
2880 static void DumpVCardAddresses(const wxVCard
& vcard
)
2882 puts("\nShowing all addresses from vCard:\n");
2886 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2890 int flags
= addr
->GetFlags();
2891 if ( flags
& wxVCardAddress::Domestic
)
2893 flagsStr
<< _T("domestic ");
2895 if ( flags
& wxVCardAddress::Intl
)
2897 flagsStr
<< _T("international ");
2899 if ( flags
& wxVCardAddress::Postal
)
2901 flagsStr
<< _T("postal ");
2903 if ( flags
& wxVCardAddress::Parcel
)
2905 flagsStr
<< _T("parcel ");
2907 if ( flags
& wxVCardAddress::Home
)
2909 flagsStr
<< _T("home ");
2911 if ( flags
& wxVCardAddress::Work
)
2913 flagsStr
<< _T("work ");
2916 printf("Address %u:\n"
2918 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2921 addr
->GetPostOffice().c_str(),
2922 addr
->GetExtAddress().c_str(),
2923 addr
->GetStreet().c_str(),
2924 addr
->GetLocality().c_str(),
2925 addr
->GetRegion().c_str(),
2926 addr
->GetPostalCode().c_str(),
2927 addr
->GetCountry().c_str()
2931 addr
= vcard
.GetNextAddress(&cookie
);
2935 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2937 puts("\nShowing all phone numbers from vCard:\n");
2941 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2945 int flags
= phone
->GetFlags();
2946 if ( flags
& wxVCardPhoneNumber::Voice
)
2948 flagsStr
<< _T("voice ");
2950 if ( flags
& wxVCardPhoneNumber::Fax
)
2952 flagsStr
<< _T("fax ");
2954 if ( flags
& wxVCardPhoneNumber::Cellular
)
2956 flagsStr
<< _T("cellular ");
2958 if ( flags
& wxVCardPhoneNumber::Modem
)
2960 flagsStr
<< _T("modem ");
2962 if ( flags
& wxVCardPhoneNumber::Home
)
2964 flagsStr
<< _T("home ");
2966 if ( flags
& wxVCardPhoneNumber::Work
)
2968 flagsStr
<< _T("work ");
2971 printf("Phone number %u:\n"
2976 phone
->GetNumber().c_str()
2980 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2984 static void TestVCardRead()
2986 puts("*** Testing wxVCard reading ***\n");
2988 wxVCard
vcard(_T("vcard.vcf"));
2989 if ( !vcard
.IsOk() )
2991 puts("ERROR: couldn't load vCard.");
2995 // read individual vCard properties
2996 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3000 vcObj
->GetValue(&value
);
3005 value
= _T("<none>");
3008 printf("Full name retrieved directly: %s\n", value
.c_str());
3011 if ( !vcard
.GetFullName(&value
) )
3013 value
= _T("<none>");
3016 printf("Full name from wxVCard API: %s\n", value
.c_str());
3018 // now show how to deal with multiply occuring properties
3019 DumpVCardAddresses(vcard
);
3020 DumpVCardPhoneNumbers(vcard
);
3022 // and finally show all
3023 puts("\nNow dumping the entire vCard:\n"
3024 "-----------------------------\n");
3026 DumpVObject(0, vcard
);
3030 static void TestVCardWrite()
3032 puts("*** Testing wxVCard writing ***\n");
3035 if ( !vcard
.IsOk() )
3037 puts("ERROR: couldn't create vCard.");
3042 vcard
.SetName("Zeitlin", "Vadim");
3043 vcard
.SetFullName("Vadim Zeitlin");
3044 vcard
.SetOrganization("wxWindows", "R&D");
3046 // just dump the vCard back
3047 puts("Entire vCard follows:\n");
3048 puts(vcard
.Write());
3052 #endif // TEST_VCARD
3054 // ----------------------------------------------------------------------------
3055 // wide char (Unicode) support
3056 // ----------------------------------------------------------------------------
3060 #include "wx/strconv.h"
3061 #include "wx/fontenc.h"
3062 #include "wx/encconv.h"
3063 #include "wx/buffer.h"
3065 static void TestUtf8()
3067 puts("*** Testing UTF8 support ***\n");
3069 static const char textInUtf8
[] =
3071 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3072 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3073 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3074 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3075 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3076 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3077 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3082 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3084 puts("ERROR: UTF-8 decoding failed.");
3088 // using wxEncodingConverter
3090 wxEncodingConverter ec
;
3091 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3092 ec
.Convert(wbuf
, buf
);
3093 #else // using wxCSConv
3094 wxCSConv
conv(_T("koi8-r"));
3095 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3097 puts("ERROR: conversion to KOI8-R failed.");
3102 printf("The resulting string (in koi8-r): %s\n", buf
);
3106 #endif // TEST_WCHAR
3108 // ----------------------------------------------------------------------------
3110 // ----------------------------------------------------------------------------
3114 #include "wx/filesys.h"
3115 #include "wx/fs_zip.h"
3116 #include "wx/zipstrm.h"
3118 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3120 static void TestZipStreamRead()
3122 puts("*** Testing ZIP reading ***\n");
3124 static const wxChar
*filename
= _T("foo");
3125 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3126 printf("Archive size: %u\n", istr
.GetSize());
3128 printf("Dumping the file '%s':\n", filename
);
3129 while ( !istr
.Eof() )
3131 putchar(istr
.GetC());
3135 puts("\n----- done ------");
3138 static void DumpZipDirectory(wxFileSystem
& fs
,
3139 const wxString
& dir
,
3140 const wxString
& indent
)
3142 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3143 TESTFILE_ZIP
, dir
.c_str());
3144 wxString wildcard
= prefix
+ _T("/*");
3146 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3147 while ( !dirname
.empty() )
3149 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3151 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3156 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3158 DumpZipDirectory(fs
, dirname
,
3159 indent
+ wxString(_T(' '), 4));
3161 dirname
= fs
.FindNext();
3164 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3165 while ( !filename
.empty() )
3167 if ( !filename
.StartsWith(prefix
, &filename
) )
3169 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3174 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3176 filename
= fs
.FindNext();
3180 static void TestZipFileSystem()
3182 puts("*** Testing ZIP file system ***\n");
3184 wxFileSystem::AddHandler(new wxZipFSHandler
);
3186 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3188 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3193 // ----------------------------------------------------------------------------
3195 // ----------------------------------------------------------------------------
3199 #include "wx/zstream.h"
3200 #include "wx/wfstream.h"
3202 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3203 static const char *TEST_DATA
= "hello and hello again";
3205 static void TestZlibStreamWrite()
3207 puts("*** Testing Zlib stream reading ***\n");
3209 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3210 wxZlibOutputStream
ostr(fileOutStream
, 0);
3211 printf("Compressing the test string... ");
3212 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3215 puts("(ERROR: failed)");
3222 puts("\n----- done ------");
3225 static void TestZlibStreamRead()
3227 puts("*** Testing Zlib stream reading ***\n");
3229 wxFileInputStream
fileInStream(FILENAME_GZ
);
3230 wxZlibInputStream
istr(fileInStream
);
3231 printf("Archive size: %u\n", istr
.GetSize());
3233 puts("Dumping the file:");
3234 while ( !istr
.Eof() )
3236 putchar(istr
.GetC());
3240 puts("\n----- done ------");
3245 // ----------------------------------------------------------------------------
3247 // ----------------------------------------------------------------------------
3249 #ifdef TEST_DATETIME
3253 #include "wx/date.h"
3254 #include "wx/datetime.h"
3259 wxDateTime::wxDateTime_t day
;
3260 wxDateTime::Month month
;
3262 wxDateTime::wxDateTime_t hour
, min
, sec
;
3264 wxDateTime::WeekDay wday
;
3265 time_t gmticks
, ticks
;
3267 void Init(const wxDateTime::Tm
& tm
)
3276 gmticks
= ticks
= -1;
3279 wxDateTime
DT() const
3280 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3282 bool SameDay(const wxDateTime::Tm
& tm
) const
3284 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3287 wxString
Format() const
3290 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3292 wxDateTime::GetMonthName(month
).c_str(),
3294 abs(wxDateTime::ConvertYearToBC(year
)),
3295 year
> 0 ? "AD" : "BC");
3299 wxString
FormatDate() const
3302 s
.Printf("%02d-%s-%4d%s",
3304 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3305 abs(wxDateTime::ConvertYearToBC(year
)),
3306 year
> 0 ? "AD" : "BC");
3311 static const Date testDates
[] =
3313 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3314 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3315 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3316 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3317 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3318 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3319 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3320 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3321 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3322 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3323 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3324 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3325 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3326 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3327 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3330 // this test miscellaneous static wxDateTime functions
3331 static void TestTimeStatic()
3333 puts("\n*** wxDateTime static methods test ***");
3335 // some info about the current date
3336 int year
= wxDateTime::GetCurrentYear();
3337 printf("Current year %d is %sa leap one and has %d days.\n",
3339 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3340 wxDateTime::GetNumberOfDays(year
));
3342 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3343 printf("Current month is '%s' ('%s') and it has %d days\n",
3344 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3345 wxDateTime::GetMonthName(month
).c_str(),
3346 wxDateTime::GetNumberOfDays(month
));
3349 static const size_t nYears
= 5;
3350 static const size_t years
[2][nYears
] =
3352 // first line: the years to test
3353 { 1990, 1976, 2000, 2030, 1984, },
3355 // second line: TRUE if leap, FALSE otherwise
3356 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3359 for ( size_t n
= 0; n
< nYears
; n
++ )
3361 int year
= years
[0][n
];
3362 bool should
= years
[1][n
] != 0,
3363 is
= wxDateTime::IsLeapYear(year
);
3365 printf("Year %d is %sa leap year (%s)\n",
3368 should
== is
? "ok" : "ERROR");
3370 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3374 // test constructing wxDateTime objects
3375 static void TestTimeSet()
3377 puts("\n*** wxDateTime construction test ***");
3379 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3381 const Date
& d1
= testDates
[n
];
3382 wxDateTime dt
= d1
.DT();
3385 d2
.Init(dt
.GetTm());
3387 wxString s1
= d1
.Format(),
3390 printf("Date: %s == %s (%s)\n",
3391 s1
.c_str(), s2
.c_str(),
3392 s1
== s2
? "ok" : "ERROR");
3396 // test time zones stuff
3397 static void TestTimeZones()
3399 puts("\n*** wxDateTime timezone test ***");
3401 wxDateTime now
= wxDateTime::Now();
3403 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3404 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3405 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3406 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3407 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3408 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3410 wxDateTime::Tm tm
= now
.GetTm();
3411 if ( wxDateTime(tm
) != now
)
3413 printf("ERROR: got %s instead of %s\n",
3414 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3418 // test some minimal support for the dates outside the standard range
3419 static void TestTimeRange()
3421 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3423 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3425 printf("Unix epoch:\t%s\n",
3426 wxDateTime(2440587.5).Format(fmt
).c_str());
3427 printf("Feb 29, 0: \t%s\n",
3428 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3429 printf("JDN 0: \t%s\n",
3430 wxDateTime(0.0).Format(fmt
).c_str());
3431 printf("Jan 1, 1AD:\t%s\n",
3432 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3433 printf("May 29, 2099:\t%s\n",
3434 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3437 static void TestTimeTicks()
3439 puts("\n*** wxDateTime ticks test ***");
3441 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3443 const Date
& d
= testDates
[n
];
3444 if ( d
.ticks
== -1 )
3447 wxDateTime dt
= d
.DT();
3448 long ticks
= (dt
.GetValue() / 1000).ToLong();
3449 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3450 if ( ticks
== d
.ticks
)
3456 printf(" (ERROR: should be %ld, delta = %ld)\n",
3457 d
.ticks
, ticks
- d
.ticks
);
3460 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3461 ticks
= (dt
.GetValue() / 1000).ToLong();
3462 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3463 if ( ticks
== d
.gmticks
)
3469 printf(" (ERROR: should be %ld, delta = %ld)\n",
3470 d
.gmticks
, ticks
- d
.gmticks
);
3477 // test conversions to JDN &c
3478 static void TestTimeJDN()
3480 puts("\n*** wxDateTime to JDN test ***");
3482 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3484 const Date
& d
= testDates
[n
];
3485 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3486 double jdn
= dt
.GetJulianDayNumber();
3488 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3495 printf(" (ERROR: should be %f, delta = %f)\n",
3496 d
.jdn
, jdn
- d
.jdn
);
3501 // test week days computation
3502 static void TestTimeWDays()
3504 puts("\n*** wxDateTime weekday test ***");
3506 // test GetWeekDay()
3508 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3510 const Date
& d
= testDates
[n
];
3511 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3513 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3516 wxDateTime::GetWeekDayName(wday
).c_str());
3517 if ( wday
== d
.wday
)
3523 printf(" (ERROR: should be %s)\n",
3524 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3530 // test SetToWeekDay()
3531 struct WeekDateTestData
3533 Date date
; // the real date (precomputed)
3534 int nWeek
; // its week index in the month
3535 wxDateTime::WeekDay wday
; // the weekday
3536 wxDateTime::Month month
; // the month
3537 int year
; // and the year
3539 wxString
Format() const
3542 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3544 case 1: which
= "first"; break;
3545 case 2: which
= "second"; break;
3546 case 3: which
= "third"; break;
3547 case 4: which
= "fourth"; break;
3548 case 5: which
= "fifth"; break;
3550 case -1: which
= "last"; break;
3555 which
+= " from end";
3558 s
.Printf("The %s %s of %s in %d",
3560 wxDateTime::GetWeekDayName(wday
).c_str(),
3561 wxDateTime::GetMonthName(month
).c_str(),
3568 // the array data was generated by the following python program
3570 from DateTime import *
3571 from whrandom import *
3572 from string import *
3574 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3575 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3577 week = DateTimeDelta(7)
3580 year = randint(1900, 2100)
3581 month = randint(1, 12)
3582 day = randint(1, 28)
3583 dt = DateTime(year, month, day)
3584 wday = dt.day_of_week
3586 countFromEnd = choice([-1, 1])
3589 while dt.month is month:
3590 dt = dt - countFromEnd * week
3591 weekNum = weekNum + countFromEnd
3593 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3595 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3596 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3599 static const WeekDateTestData weekDatesTestData
[] =
3601 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3602 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3603 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3604 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3605 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3606 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3607 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3608 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3609 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3610 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3611 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3612 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3613 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3614 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3615 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3616 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3617 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3618 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3619 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3620 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3623 static const char *fmt
= "%d-%b-%Y";
3626 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3628 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3630 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3632 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3634 const Date
& d
= wd
.date
;
3635 if ( d
.SameDay(dt
.GetTm()) )
3641 dt
.Set(d
.day
, d
.month
, d
.year
);
3643 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3648 // test the computation of (ISO) week numbers
3649 static void TestTimeWNumber()
3651 puts("\n*** wxDateTime week number test ***");
3653 struct WeekNumberTestData
3655 Date date
; // the date
3656 wxDateTime::wxDateTime_t week
; // the week number in the year
3657 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3658 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3659 wxDateTime::wxDateTime_t dnum
; // day number in the year
3662 // data generated with the following python script:
3664 from DateTime import *
3665 from whrandom import *
3666 from string import *
3668 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3669 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3671 def GetMonthWeek(dt):
3672 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3673 if weekNumMonth < 0:
3674 weekNumMonth = weekNumMonth + 53
3677 def GetLastSundayBefore(dt):
3678 if dt.iso_week[2] == 7:
3681 return dt - DateTimeDelta(dt.iso_week[2])
3684 year = randint(1900, 2100)
3685 month = randint(1, 12)
3686 day = randint(1, 28)
3687 dt = DateTime(year, month, day)
3688 dayNum = dt.day_of_year
3689 weekNum = dt.iso_week[1]
3690 weekNumMonth = GetMonthWeek(dt)
3693 dtSunday = GetLastSundayBefore(dt)
3695 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3696 weekNumMonth2 = weekNumMonth2 + 1
3697 dtSunday = dtSunday - DateTimeDelta(7)
3699 data = { 'day': rjust(`day`, 2), \
3700 'month': monthNames[month - 1], \
3702 'weekNum': rjust(`weekNum`, 2), \
3703 'weekNumMonth': weekNumMonth, \
3704 'weekNumMonth2': weekNumMonth2, \
3705 'dayNum': rjust(`dayNum`, 3) }
3707 print " { { %(day)s, "\
3708 "wxDateTime::%(month)s, "\
3711 "%(weekNumMonth)s, "\
3712 "%(weekNumMonth2)s, "\
3713 "%(dayNum)s }," % data
3716 static const WeekNumberTestData weekNumberTestDates
[] =
3718 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3719 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3720 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3721 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3722 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3723 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3724 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3725 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3726 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3727 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3728 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3729 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3730 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3731 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3732 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3733 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3734 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3735 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3736 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3737 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3740 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3742 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3743 const Date
& d
= wn
.date
;
3745 wxDateTime dt
= d
.DT();
3747 wxDateTime::wxDateTime_t
3748 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3749 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3750 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3751 dnum
= dt
.GetDayOfYear();
3753 printf("%s: the day number is %d",
3754 d
.FormatDate().c_str(), dnum
);
3755 if ( dnum
== wn
.dnum
)
3761 printf(" (ERROR: should be %d)", wn
.dnum
);
3764 printf(", week in month is %d", wmon
);
3765 if ( wmon
== wn
.wmon
)
3771 printf(" (ERROR: should be %d)", wn
.wmon
);
3774 printf(" or %d", wmon2
);
3775 if ( wmon2
== wn
.wmon2
)
3781 printf(" (ERROR: should be %d)", wn
.wmon2
);
3784 printf(", week in year is %d", week
);
3785 if ( week
== wn
.week
)
3791 printf(" (ERROR: should be %d)\n", wn
.week
);
3796 // test DST calculations
3797 static void TestTimeDST()
3799 puts("\n*** wxDateTime DST test ***");
3801 printf("DST is%s in effect now.\n\n",
3802 wxDateTime::Now().IsDST() ? "" : " not");
3804 // taken from http://www.energy.ca.gov/daylightsaving.html
3805 static const Date datesDST
[2][2004 - 1900 + 1] =
3808 { 1, wxDateTime::Apr
, 1990 },
3809 { 7, wxDateTime::Apr
, 1991 },
3810 { 5, wxDateTime::Apr
, 1992 },
3811 { 4, wxDateTime::Apr
, 1993 },
3812 { 3, wxDateTime::Apr
, 1994 },
3813 { 2, wxDateTime::Apr
, 1995 },
3814 { 7, wxDateTime::Apr
, 1996 },
3815 { 6, wxDateTime::Apr
, 1997 },
3816 { 5, wxDateTime::Apr
, 1998 },
3817 { 4, wxDateTime::Apr
, 1999 },
3818 { 2, wxDateTime::Apr
, 2000 },
3819 { 1, wxDateTime::Apr
, 2001 },
3820 { 7, wxDateTime::Apr
, 2002 },
3821 { 6, wxDateTime::Apr
, 2003 },
3822 { 4, wxDateTime::Apr
, 2004 },
3825 { 28, wxDateTime::Oct
, 1990 },
3826 { 27, wxDateTime::Oct
, 1991 },
3827 { 25, wxDateTime::Oct
, 1992 },
3828 { 31, wxDateTime::Oct
, 1993 },
3829 { 30, wxDateTime::Oct
, 1994 },
3830 { 29, wxDateTime::Oct
, 1995 },
3831 { 27, wxDateTime::Oct
, 1996 },
3832 { 26, wxDateTime::Oct
, 1997 },
3833 { 25, wxDateTime::Oct
, 1998 },
3834 { 31, wxDateTime::Oct
, 1999 },
3835 { 29, wxDateTime::Oct
, 2000 },
3836 { 28, wxDateTime::Oct
, 2001 },
3837 { 27, wxDateTime::Oct
, 2002 },
3838 { 26, wxDateTime::Oct
, 2003 },
3839 { 31, wxDateTime::Oct
, 2004 },
3844 for ( year
= 1990; year
< 2005; year
++ )
3846 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3847 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3849 printf("DST period in the US for year %d: from %s to %s",
3850 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3852 size_t n
= year
- 1990;
3853 const Date
& dBegin
= datesDST
[0][n
];
3854 const Date
& dEnd
= datesDST
[1][n
];
3856 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3862 printf(" (ERROR: should be %s %d to %s %d)\n",
3863 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3864 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3870 for ( year
= 1990; year
< 2005; year
++ )
3872 printf("DST period in Europe for year %d: from %s to %s\n",
3874 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3875 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3879 // test wxDateTime -> text conversion
3880 static void TestTimeFormat()
3882 puts("\n*** wxDateTime formatting test ***");
3884 // some information may be lost during conversion, so store what kind
3885 // of info should we recover after a round trip
3888 CompareNone
, // don't try comparing
3889 CompareBoth
, // dates and times should be identical
3890 CompareDate
, // dates only
3891 CompareTime
// time only
3896 CompareKind compareKind
;
3898 } formatTestFormats
[] =
3900 { CompareBoth
, "---> %c" },
3901 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3902 { CompareBoth
, "Date is %x, time is %X" },
3903 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3904 { CompareNone
, "The day of year: %j, the week of year: %W" },
3905 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3908 static const Date formatTestDates
[] =
3910 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3911 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3913 // this test can't work for other centuries because it uses two digit
3914 // years in formats, so don't even try it
3915 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3916 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3917 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3921 // an extra test (as it doesn't depend on date, don't do it in the loop)
3922 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3924 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3928 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3929 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3931 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3932 printf("%s", s
.c_str());
3934 // what can we recover?
3935 int kind
= formatTestFormats
[n
].compareKind
;
3939 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3942 // converion failed - should it have?
3943 if ( kind
== CompareNone
)
3946 puts(" (ERROR: conversion back failed)");
3950 // should have parsed the entire string
3951 puts(" (ERROR: conversion back stopped too soon)");
3955 bool equal
= FALSE
; // suppress compilaer warning
3963 equal
= dt
.IsSameDate(dt2
);
3967 equal
= dt
.IsSameTime(dt2
);
3973 printf(" (ERROR: got back '%s' instead of '%s')\n",
3974 dt2
.Format().c_str(), dt
.Format().c_str());
3985 // test text -> wxDateTime conversion
3986 static void TestTimeParse()
3988 puts("\n*** wxDateTime parse test ***");
3990 struct ParseTestData
3997 static const ParseTestData parseTestDates
[] =
3999 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4000 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4003 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4005 const char *format
= parseTestDates
[n
].format
;
4007 printf("%s => ", format
);
4010 if ( dt
.ParseRfc822Date(format
) )
4012 printf("%s ", dt
.Format().c_str());
4014 if ( parseTestDates
[n
].good
)
4016 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4023 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4028 puts("(ERROR: bad format)");
4033 printf("bad format (%s)\n",
4034 parseTestDates
[n
].good
? "ERROR" : "ok");
4039 static void TestDateTimeInteractive()
4041 puts("\n*** interactive wxDateTime tests ***");
4047 printf("Enter a date: ");
4048 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4051 // kill the last '\n'
4052 buf
[strlen(buf
) - 1] = 0;
4055 const char *p
= dt
.ParseDate(buf
);
4058 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4064 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4067 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4068 dt
.Format("%b %d, %Y").c_str(),
4070 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4071 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4072 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4075 puts("\n*** done ***");
4078 static void TestTimeMS()
4080 puts("*** testing millisecond-resolution support in wxDateTime ***");
4082 wxDateTime dt1
= wxDateTime::Now(),
4083 dt2
= wxDateTime::UNow();
4085 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4086 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4087 printf("Dummy loop: ");
4088 for ( int i
= 0; i
< 6000; i
++ )
4090 //for ( int j = 0; j < 10; j++ )
4093 s
.Printf("%g", sqrt(i
));
4102 dt2
= wxDateTime::UNow();
4103 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4105 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4107 puts("\n*** done ***");
4110 static void TestTimeArithmetics()
4112 puts("\n*** testing arithmetic operations on wxDateTime ***");
4114 static const struct ArithmData
4116 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4117 : span(sp
), name(nam
) { }
4121 } testArithmData
[] =
4123 ArithmData(wxDateSpan::Day(), "day"),
4124 ArithmData(wxDateSpan::Week(), "week"),
4125 ArithmData(wxDateSpan::Month(), "month"),
4126 ArithmData(wxDateSpan::Year(), "year"),
4127 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4130 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4132 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4134 wxDateSpan span
= testArithmData
[n
].span
;
4138 const char *name
= testArithmData
[n
].name
;
4139 printf("%s + %s = %s, %s - %s = %s\n",
4140 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4141 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4143 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4144 if ( dt1
- span
== dt
)
4150 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4153 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4154 if ( dt2
+ span
== dt
)
4160 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4163 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4164 if ( dt2
+ 2*span
== dt1
)
4170 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4177 static void TestTimeHolidays()
4179 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4181 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4182 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4183 dtEnd
= dtStart
.GetLastMonthDay();
4185 wxDateTimeArray hol
;
4186 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4188 const wxChar
*format
= "%d-%b-%Y (%a)";
4190 printf("All holidays between %s and %s:\n",
4191 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4193 size_t count
= hol
.GetCount();
4194 for ( size_t n
= 0; n
< count
; n
++ )
4196 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4202 static void TestTimeZoneBug()
4204 puts("\n*** testing for DST/timezone bug ***\n");
4206 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4207 for ( int i
= 0; i
< 31; i
++ )
4209 printf("Date %s: week day %s.\n",
4210 date
.Format(_T("%d-%m-%Y")).c_str(),
4211 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4213 date
+= wxDateSpan::Day();
4219 static void TestTimeSpanFormat()
4221 puts("\n*** wxTimeSpan tests ***");
4223 static const char *formats
[] =
4225 _T("(default) %H:%M:%S"),
4226 _T("%E weeks and %D days"),
4227 _T("%l milliseconds"),
4228 _T("(with ms) %H:%M:%S:%l"),
4229 _T("100%% of minutes is %M"), // test "%%"
4230 _T("%D days and %H hours"),
4231 _T("or also %S seconds"),
4234 wxTimeSpan
ts1(1, 2, 3, 4),
4236 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4238 printf("ts1 = %s\tts2 = %s\n",
4239 ts1
.Format(formats
[n
]).c_str(),
4240 ts2
.Format(formats
[n
]).c_str());
4248 // test compatibility with the old wxDate/wxTime classes
4249 static void TestTimeCompatibility()
4251 puts("\n*** wxDateTime compatibility test ***");
4253 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4254 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4256 double jdnNow
= wxDateTime::Now().GetJDN();
4257 long jdnMidnight
= (long)(jdnNow
- 0.5);
4258 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4260 jdnMidnight
= wxDate().Set().GetJulianDate();
4261 printf("wxDateTime for today: %s\n",
4262 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4264 int flags
= wxEUROPEAN
;//wxFULL;
4267 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4268 for ( int n
= 0; n
< 7; n
++ )
4270 printf("Previous %s is %s\n",
4271 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4272 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4278 #endif // TEST_DATETIME
4280 // ----------------------------------------------------------------------------
4282 // ----------------------------------------------------------------------------
4286 #include "wx/thread.h"
4288 static size_t gs_counter
= (size_t)-1;
4289 static wxCriticalSection gs_critsect
;
4290 static wxCondition gs_cond
;
4292 class MyJoinableThread
: public wxThread
4295 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4296 { m_n
= n
; Create(); }
4298 // thread execution starts here
4299 virtual ExitCode
Entry();
4305 wxThread::ExitCode
MyJoinableThread::Entry()
4307 unsigned long res
= 1;
4308 for ( size_t n
= 1; n
< m_n
; n
++ )
4312 // it's a loooong calculation :-)
4316 return (ExitCode
)res
;
4319 class MyDetachedThread
: public wxThread
4322 MyDetachedThread(size_t n
, char ch
)
4326 m_cancelled
= FALSE
;
4331 // thread execution starts here
4332 virtual ExitCode
Entry();
4335 virtual void OnExit();
4338 size_t m_n
; // number of characters to write
4339 char m_ch
; // character to write
4341 bool m_cancelled
; // FALSE if we exit normally
4344 wxThread::ExitCode
MyDetachedThread::Entry()
4347 wxCriticalSectionLocker
lock(gs_critsect
);
4348 if ( gs_counter
== (size_t)-1 )
4354 for ( size_t n
= 0; n
< m_n
; n
++ )
4356 if ( TestDestroy() )
4366 wxThread::Sleep(100);
4372 void MyDetachedThread::OnExit()
4374 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4376 wxCriticalSectionLocker
lock(gs_critsect
);
4377 if ( !--gs_counter
&& !m_cancelled
)
4381 void TestDetachedThreads()
4383 puts("\n*** Testing detached threads ***");
4385 static const size_t nThreads
= 3;
4386 MyDetachedThread
*threads
[nThreads
];
4388 for ( n
= 0; n
< nThreads
; n
++ )
4390 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4393 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4394 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4396 for ( n
= 0; n
< nThreads
; n
++ )
4401 // wait until all threads terminate
4407 void TestJoinableThreads()
4409 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4411 // calc 10! in the background
4412 MyJoinableThread
thread(10);
4415 printf("\nThread terminated with exit code %lu.\n",
4416 (unsigned long)thread
.Wait());
4419 void TestThreadSuspend()
4421 puts("\n*** Testing thread suspend/resume functions ***");
4423 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4427 // this is for this demo only, in a real life program we'd use another
4428 // condition variable which would be signaled from wxThread::Entry() to
4429 // tell us that the thread really started running - but here just wait a
4430 // bit and hope that it will be enough (the problem is, of course, that
4431 // the thread might still not run when we call Pause() which will result
4433 wxThread::Sleep(300);
4435 for ( size_t n
= 0; n
< 3; n
++ )
4439 puts("\nThread suspended");
4442 // don't sleep but resume immediately the first time
4443 wxThread::Sleep(300);
4445 puts("Going to resume the thread");
4450 puts("Waiting until it terminates now");
4452 // wait until the thread terminates
4458 void TestThreadDelete()
4460 // As above, using Sleep() is only for testing here - we must use some
4461 // synchronisation object instead to ensure that the thread is still
4462 // running when we delete it - deleting a detached thread which already
4463 // terminated will lead to a crash!
4465 puts("\n*** Testing thread delete function ***");
4467 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4471 puts("\nDeleted a thread which didn't start to run yet.");
4473 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4477 wxThread::Sleep(300);
4481 puts("\nDeleted a running thread.");
4483 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4487 wxThread::Sleep(300);
4493 puts("\nDeleted a sleeping thread.");
4495 MyJoinableThread
thread3(20);
4500 puts("\nDeleted a joinable thread.");
4502 MyJoinableThread
thread4(2);
4505 wxThread::Sleep(300);
4509 puts("\nDeleted a joinable thread which already terminated.");
4514 #endif // TEST_THREADS
4516 // ----------------------------------------------------------------------------
4518 // ----------------------------------------------------------------------------
4522 static void PrintArray(const char* name
, const wxArrayString
& array
)
4524 printf("Dump of the array '%s'\n", name
);
4526 size_t nCount
= array
.GetCount();
4527 for ( size_t n
= 0; n
< nCount
; n
++ )
4529 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4533 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4535 printf("Dump of the array '%s'\n", name
);
4537 size_t nCount
= array
.GetCount();
4538 for ( size_t n
= 0; n
< nCount
; n
++ )
4540 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4544 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4545 const wxString
& second
)
4547 return first
.length() - second
.length();
4550 int wxCMPFUNC_CONV
IntCompare(int *first
,
4553 return *first
- *second
;
4556 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4559 return *second
- *first
;
4562 static void TestArrayOfInts()
4564 puts("*** Testing wxArrayInt ***\n");
4575 puts("After sort:");
4579 puts("After reverse sort:");
4580 a
.Sort(IntRevCompare
);
4584 #include "wx/dynarray.h"
4586 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4587 #include "wx/arrimpl.cpp"
4588 WX_DEFINE_OBJARRAY(ArrayBars
);
4590 static void TestArrayOfObjects()
4592 puts("*** Testing wxObjArray ***\n");
4596 Bar
bar("second bar");
4598 printf("Initially: %u objects in the array, %u objects total.\n",
4599 bars
.GetCount(), Bar::GetNumber());
4601 bars
.Add(new Bar("first bar"));
4604 printf("Now: %u objects in the array, %u objects total.\n",
4605 bars
.GetCount(), Bar::GetNumber());
4609 printf("After Empty(): %u objects in the array, %u objects total.\n",
4610 bars
.GetCount(), Bar::GetNumber());
4613 printf("Finally: no more objects in the array, %u objects total.\n",
4617 #endif // TEST_ARRAYS
4619 // ----------------------------------------------------------------------------
4621 // ----------------------------------------------------------------------------
4625 #include "wx/timer.h"
4626 #include "wx/tokenzr.h"
4628 static void TestStringConstruction()
4630 puts("*** Testing wxString constructores ***");
4632 #define TEST_CTOR(args, res) \
4635 printf("wxString%s = %s ", #args, s.c_str()); \
4642 printf("(ERROR: should be %s)\n", res); \
4646 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4647 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4648 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4649 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4651 static const wxChar
*s
= _T("?really!");
4652 const wxChar
*start
= wxStrchr(s
, _T('r'));
4653 const wxChar
*end
= wxStrchr(s
, _T('!'));
4654 TEST_CTOR((start
, end
), _T("really"));
4659 static void TestString()
4669 for (int i
= 0; i
< 1000000; ++i
)
4673 c
= "! How'ya doin'?";
4676 c
= "Hello world! What's up?";
4681 printf ("TestString elapsed time: %ld\n", sw
.Time());
4684 static void TestPChar()
4692 for (int i
= 0; i
< 1000000; ++i
)
4694 strcpy (a
, "Hello");
4695 strcpy (b
, " world");
4696 strcpy (c
, "! How'ya doin'?");
4699 strcpy (c
, "Hello world! What's up?");
4700 if (strcmp (c
, a
) == 0)
4704 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4707 static void TestStringSub()
4709 wxString
s("Hello, world!");
4711 puts("*** Testing wxString substring extraction ***");
4713 printf("String = '%s'\n", s
.c_str());
4714 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4715 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4716 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4717 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4718 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4719 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4721 static const wxChar
*prefixes
[] =
4725 _T("Hello, world!"),
4726 _T("Hello, world!!!"),
4732 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4734 wxString prefix
= prefixes
[n
], rest
;
4735 bool rc
= s
.StartsWith(prefix
, &rest
);
4736 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4739 printf(" (the rest is '%s')\n", rest
.c_str());
4750 static void TestStringFormat()
4752 puts("*** Testing wxString formatting ***");
4755 s
.Printf("%03d", 18);
4757 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4758 printf("Number 18: %s\n", s
.c_str());
4763 // returns "not found" for npos, value for all others
4764 static wxString
PosToString(size_t res
)
4766 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4767 : wxString::Format(_T("%u"), res
);
4771 static void TestStringFind()
4773 puts("*** Testing wxString find() functions ***");
4775 static const wxChar
*strToFind
= _T("ell");
4776 static const struct StringFindTest
4780 result
; // of searching "ell" in str
4783 { _T("Well, hello world"), 0, 1 },
4784 { _T("Well, hello world"), 6, 7 },
4785 { _T("Well, hello world"), 9, wxString::npos
},
4788 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4790 const StringFindTest
& ft
= findTestData
[n
];
4791 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4793 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4794 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4796 size_t resTrue
= ft
.result
;
4797 if ( res
== resTrue
)
4803 printf(_T("(ERROR: should be %s)\n"),
4804 PosToString(resTrue
).c_str());
4811 static void TestStringTokenizer()
4813 puts("*** Testing wxStringTokenizer ***");
4815 static const wxChar
*modeNames
[] =
4819 _T("return all empty"),
4824 static const struct StringTokenizerTest
4826 const wxChar
*str
; // string to tokenize
4827 const wxChar
*delims
; // delimiters to use
4828 size_t count
; // count of token
4829 wxStringTokenizerMode mode
; // how should we tokenize it
4830 } tokenizerTestData
[] =
4832 { _T(""), _T(" "), 0 },
4833 { _T("Hello, world"), _T(" "), 2 },
4834 { _T("Hello, world "), _T(" "), 2 },
4835 { _T("Hello, world"), _T(","), 2 },
4836 { _T("Hello, world!"), _T(",!"), 2 },
4837 { _T("Hello,, world!"), _T(",!"), 3 },
4838 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4839 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4840 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4841 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4842 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4843 { _T("01/02/99"), _T("/-"), 3 },
4844 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4847 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4849 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4850 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4852 size_t count
= tkz
.CountTokens();
4853 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4854 MakePrintable(tt
.str
).c_str(),
4856 MakePrintable(tt
.delims
).c_str(),
4857 modeNames
[tkz
.GetMode()]);
4858 if ( count
== tt
.count
)
4864 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4869 // if we emulate strtok(), check that we do it correctly
4870 wxChar
*buf
, *s
= NULL
, *last
;
4872 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4874 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4875 wxStrcpy(buf
, tt
.str
);
4877 s
= wxStrtok(buf
, tt
.delims
, &last
);
4884 // now show the tokens themselves
4886 while ( tkz
.HasMoreTokens() )
4888 wxString token
= tkz
.GetNextToken();
4890 printf(_T("\ttoken %u: '%s'"),
4892 MakePrintable(token
).c_str());
4902 printf(" (ERROR: should be %s)\n", s
);
4905 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4909 // nothing to compare with
4914 if ( count2
!= count
)
4916 puts(_T("\tERROR: token count mismatch"));
4925 static void TestStringReplace()
4927 puts("*** Testing wxString::replace ***");
4929 static const struct StringReplaceTestData
4931 const wxChar
*original
; // original test string
4932 size_t start
, len
; // the part to replace
4933 const wxChar
*replacement
; // the replacement string
4934 const wxChar
*result
; // and the expected result
4935 } stringReplaceTestData
[] =
4937 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4938 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4939 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4940 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4941 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4944 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4946 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4948 wxString original
= data
.original
;
4949 original
.replace(data
.start
, data
.len
, data
.replacement
);
4951 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4952 data
.original
, data
.start
, data
.len
, data
.replacement
,
4955 if ( original
== data
.result
)
4961 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4968 static void TestStringMatch()
4970 wxPuts(_T("*** Testing wxString::Matches() ***"));
4972 static const struct StringMatchTestData
4975 const wxChar
*wildcard
;
4977 } stringMatchTestData
[] =
4979 { _T("foobar"), _T("foo*"), 1 },
4980 { _T("foobar"), _T("*oo*"), 1 },
4981 { _T("foobar"), _T("*bar"), 1 },
4982 { _T("foobar"), _T("??????"), 1 },
4983 { _T("foobar"), _T("f??b*"), 1 },
4984 { _T("foobar"), _T("f?b*"), 0 },
4985 { _T("foobar"), _T("*goo*"), 0 },
4986 { _T("foobar"), _T("*foo"), 0 },
4987 { _T("foobarfoo"), _T("*foo"), 1 },
4988 { _T(""), _T("*"), 1 },
4989 { _T(""), _T("?"), 0 },
4992 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4994 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4995 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4996 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4998 matches
? _T("matches") : _T("doesn't match"),
5000 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5006 #endif // TEST_STRINGS
5008 // ----------------------------------------------------------------------------
5010 // ----------------------------------------------------------------------------
5012 int main(int argc
, char **argv
)
5014 wxInitializer initializer
;
5017 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5022 #ifdef TEST_SNGLINST
5023 wxSingleInstanceChecker checker
;
5024 if ( checker
.Create(_T(".wxconsole.lock")) )
5026 if ( checker
.IsAnotherRunning() )
5028 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5033 // wait some time to give time to launch another instance
5034 wxPrintf(_T("Press \"Enter\" to continue..."));
5037 else // failed to create
5039 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5041 #endif // TEST_SNGLINST
5045 #endif // TEST_CHARSET
5048 TestCmdLineConvert();
5050 #if wxUSE_CMDLINE_PARSER
5051 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5053 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5054 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5055 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5056 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5058 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5059 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5060 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5061 wxCMD_LINE_VAL_NUMBER
},
5062 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5063 wxCMD_LINE_VAL_DATE
},
5065 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5066 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5071 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5073 parser
.AddOption("project_name", "", "full path to project file",
5074 wxCMD_LINE_VAL_STRING
,
5075 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5077 switch ( parser
.Parse() )
5080 wxLogMessage("Help was given, terminating.");
5084 ShowCmdLine(parser
);
5088 wxLogMessage("Syntax error detected, aborting.");
5091 #endif // wxUSE_CMDLINE_PARSER
5093 #endif // TEST_CMDLINE
5101 TestStringConstruction();
5104 TestStringTokenizer();
5105 TestStringReplace();
5108 #endif // TEST_STRINGS
5121 puts("*** Initially:");
5123 PrintArray("a1", a1
);
5125 wxArrayString
a2(a1
);
5126 PrintArray("a2", a2
);
5128 wxSortedArrayString
a3(a1
);
5129 PrintArray("a3", a3
);
5131 puts("*** After deleting a string from a1");
5134 PrintArray("a1", a1
);
5135 PrintArray("a2", a2
);
5136 PrintArray("a3", a3
);
5138 puts("*** After reassigning a1 to a2 and a3");
5140 PrintArray("a2", a2
);
5141 PrintArray("a3", a3
);
5143 puts("*** After sorting a1");
5145 PrintArray("a1", a1
);
5147 puts("*** After sorting a1 in reverse order");
5149 PrintArray("a1", a1
);
5151 puts("*** After sorting a1 by the string length");
5152 a1
.Sort(StringLenCompare
);
5153 PrintArray("a1", a1
);
5155 TestArrayOfObjects();
5158 #endif // TEST_ARRAYS
5166 #ifdef TEST_DLLLOADER
5168 #endif // TEST_DLLLOADER
5172 #endif // TEST_ENVIRON
5176 #endif // TEST_EXECUTE
5178 #ifdef TEST_FILECONF
5180 #endif // TEST_FILECONF
5188 #endif // TEST_LOCALE
5192 for ( size_t n
= 0; n
< 8000; n
++ )
5194 s
<< (char)('A' + (n
% 26));
5198 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5200 // this one shouldn't be truncated
5203 // but this one will because log functions use fixed size buffer
5204 // (note that it doesn't need '\n' at the end neither - will be added
5206 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5218 #ifdef TEST_FILENAME
5222 TestFileNameConstruction();
5223 TestFileNameSplit();
5225 TestFileNameComparison();
5226 TestFileNameOperations();
5228 #endif // TEST_FILENAME
5230 #ifdef TEST_FILETIME
5233 #endif // TEST_FILETIME
5236 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5237 if ( TestFtpConnect() )
5248 TestFtpInteractive();
5250 //else: connecting to the FTP server failed
5257 int nCPUs
= wxThread::GetCPUCount();
5258 printf("This system has %d CPUs\n", nCPUs
);
5260 wxThread::SetConcurrency(nCPUs
);
5262 if ( argc
> 1 && argv
[1][0] == 't' )
5263 wxLog::AddTraceMask("thread");
5266 TestDetachedThreads();
5268 TestJoinableThreads();
5270 TestThreadSuspend();
5274 #endif // TEST_THREADS
5276 #ifdef TEST_LONGLONG
5277 // seed pseudo random generator
5278 srand((unsigned)time(NULL
));
5286 TestMultiplication();
5289 TestLongLongConversion();
5290 TestBitOperations();
5291 TestLongLongComparison();
5293 TestLongLongPrint();
5294 #endif // TEST_LONGLONG
5301 wxLog::AddTraceMask(_T("mime"));
5309 TestMimeAssociate();
5312 #ifdef TEST_INFO_FUNCTIONS
5319 #endif // TEST_INFO_FUNCTIONS
5321 #ifdef TEST_PATHLIST
5323 #endif // TEST_PATHLIST
5327 #endif // TEST_REGCONF
5330 // TODO: write a real test using src/regex/tests file
5335 TestRegExSubmatch();
5336 TestRegExInteractive();
5338 TestRegExReplacement();
5339 #endif // TEST_REGEX
5341 #ifdef TEST_REGISTRY
5344 TestRegistryAssociation();
5345 #endif // TEST_REGISTRY
5353 #endif // TEST_SOCKETS
5359 #endif // TEST_STREAMS
5363 #endif // TEST_TIMER
5365 #ifdef TEST_DATETIME
5378 TestTimeArithmetics();
5385 TestTimeSpanFormat();
5387 TestDateTimeInteractive();
5388 #endif // TEST_DATETIME
5391 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5393 #endif // TEST_USLEEP
5399 #endif // TEST_VCARD
5403 #endif // TEST_WCHAR
5407 TestZipStreamRead();
5408 TestZipFileSystem();
5413 TestZlibStreamWrite();
5414 TestZlibStreamRead();