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 void DumpFileName(const wxFileName
& fn
)
745 wxString full
= fn
.GetFullPath();
747 wxString vol
, path
, name
, ext
;
748 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
750 wxPrintf(_T("Filename '%s' -> vol '%s', path '%s', name '%s', ext '%s'\n"),
751 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
754 static struct FileNameInfo
756 const wxChar
*fullname
;
757 const wxChar
*volume
;
766 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
767 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
768 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
769 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
770 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
771 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
772 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
773 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
774 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
776 // Windows file names
777 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
778 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
779 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
780 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
781 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
782 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
785 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
786 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
787 { _T(":File"), _T(""), _T(""), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
788 { _T("File"), _T(""), _T(""), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
791 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
792 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
795 static void TestFileNameConstruction()
797 puts("*** testing wxFileName construction ***");
799 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
801 const FileNameInfo
& fni
= filenames
[n
];
803 wxFileName
fn(fni
.fullname
, fni
.format
);
805 wxString fullname
= fn
.GetFullPath(fni
.format
);
806 if ( fullname
!= fni
.fullname
)
808 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
811 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
812 printf("'%s' is %s (%s)\n\t",
814 isAbsolute
? "absolute" : "relative",
815 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
817 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
819 puts("ERROR (couldn't be normalized)");
823 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
830 static void TestFileNameSplit()
832 puts("*** testing wxFileName splitting ***");
834 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
836 const FileNameInfo
& fni
= filenames
[n
];
837 wxString volume
, path
, name
, ext
;
838 wxFileName::SplitPath(fni
.fullname
,
839 &volume
, &path
, &name
, &ext
, fni
.format
);
841 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
843 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
845 if ( volume
!= fni
.volume
)
846 printf(" (ERROR: volume = '%s')", fni
.volume
);
847 if ( path
!= fni
.path
)
848 printf(" (ERROR: path = '%s')", fni
.path
);
849 if ( name
!= fni
.name
)
850 printf(" (ERROR: name = '%s')", fni
.name
);
851 if ( ext
!= fni
.ext
)
852 printf(" (ERROR: ext = '%s')", fni
.ext
);
858 static void TestFileNameTemp()
860 puts("*** testing wxFileName temp file creation ***");
862 static const char *tmpprefixes
[] =
868 "/tmp/foo/bar", // this one must be an error
871 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
873 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
876 printf("Prefix '%s'\t-> temp file '%s'\n",
877 tmpprefixes
[n
], path
.c_str());
879 if ( !wxRemoveFile(path
) )
881 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
887 static void TestFileNameComparison()
892 static void TestFileNameOperations()
897 static void TestFileNameCwd()
902 #endif // TEST_FILENAME
904 // ----------------------------------------------------------------------------
905 // wxFileName time functions
906 // ----------------------------------------------------------------------------
910 #include <wx/filename.h>
911 #include <wx/datetime.h>
913 static void TestFileGetTimes()
915 wxFileName
fn(_T("testdata.fc"));
917 wxDateTime dtAccess
, dtMod
, dtChange
;
918 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
920 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
924 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
926 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
927 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
928 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
929 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
933 static void TestFileSetTimes()
935 wxFileName
fn(_T("testdata.fc"));
937 wxDateTime dtAccess
, dtMod
, dtChange
;
940 wxPrintf(_T("ERROR: Touch() failed.\n"));
944 #endif // TEST_FILETIME
946 // ----------------------------------------------------------------------------
948 // ----------------------------------------------------------------------------
956 Foo(int n_
) { n
= n_
; count
++; }
964 size_t Foo::count
= 0;
966 WX_DECLARE_LIST(Foo
, wxListFoos
);
967 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
969 #include "wx/listimpl.cpp"
971 WX_DEFINE_LIST(wxListFoos
);
973 static void TestHash()
975 puts("*** Testing wxHashTable ***\n");
979 hash
.DeleteContents(TRUE
);
981 printf("Hash created: %u foos in hash, %u foos totally\n",
982 hash
.GetCount(), Foo::count
);
984 static const int hashTestData
[] =
986 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
990 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
992 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
995 printf("Hash filled: %u foos in hash, %u foos totally\n",
996 hash
.GetCount(), Foo::count
);
998 puts("Hash access test:");
999 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1001 printf("\tGetting element with key %d, value %d: ",
1002 hashTestData
[n
], n
);
1003 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1006 printf("ERROR, not found.\n");
1010 printf("%d (%s)\n", foo
->n
,
1011 (size_t)foo
->n
== n
? "ok" : "ERROR");
1015 printf("\nTrying to get an element not in hash: ");
1017 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1019 puts("ERROR: found!");
1023 puts("ok (not found)");
1027 printf("Hash destroyed: %u foos left\n", Foo::count
);
1032 // ----------------------------------------------------------------------------
1034 // ----------------------------------------------------------------------------
1038 #include "wx/list.h"
1040 WX_DECLARE_LIST(Bar
, wxListBars
);
1041 #include "wx/listimpl.cpp"
1042 WX_DEFINE_LIST(wxListBars
);
1044 static void TestListCtor()
1046 puts("*** Testing wxList construction ***\n");
1050 list1
.Append(new Bar(_T("first")));
1051 list1
.Append(new Bar(_T("second")));
1053 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1054 list1
.GetCount(), Bar::GetNumber());
1059 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1060 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1062 list1
.DeleteContents(TRUE
);
1065 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1070 // ----------------------------------------------------------------------------
1072 // ----------------------------------------------------------------------------
1076 #include "wx/intl.h"
1077 #include "wx/utils.h" // for wxSetEnv
1079 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1081 // find the name of the language from its value
1082 static const char *GetLangName(int lang
)
1084 static const char *languageNames
[] =
1105 "ARABIC_SAUDI_ARABIA",
1130 "CHINESE_SIMPLIFIED",
1131 "CHINESE_TRADITIONAL",
1134 "CHINESE_SINGAPORE",
1145 "ENGLISH_AUSTRALIA",
1149 "ENGLISH_CARIBBEAN",
1153 "ENGLISH_NEW_ZEALAND",
1154 "ENGLISH_PHILIPPINES",
1155 "ENGLISH_SOUTH_AFRICA",
1167 "FRENCH_LUXEMBOURG",
1176 "GERMAN_LIECHTENSTEIN",
1177 "GERMAN_LUXEMBOURG",
1218 "MALAY_BRUNEI_DARUSSALAM",
1230 "NORWEGIAN_NYNORSK",
1237 "PORTUGUESE_BRAZILIAN",
1262 "SPANISH_ARGENTINA",
1266 "SPANISH_COSTA_RICA",
1267 "SPANISH_DOMINICAN_REPUBLIC",
1269 "SPANISH_EL_SALVADOR",
1270 "SPANISH_GUATEMALA",
1274 "SPANISH_NICARAGUA",
1278 "SPANISH_PUERTO_RICO",
1281 "SPANISH_VENEZUELA",
1318 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1319 return languageNames
[lang
];
1324 static void TestDefaultLang()
1326 puts("*** Testing wxLocale::GetSystemLanguage ***");
1328 static const wxChar
*langStrings
[] =
1330 NULL
, // system default
1337 _T("de_DE.iso88591"),
1339 _T("?"), // invalid lang spec
1340 _T("klingonese"), // I bet on some systems it does exist...
1343 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1344 wxLocale::GetSystemEncodingName().c_str(),
1345 wxLocale::GetSystemEncoding());
1347 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1349 const char *langStr
= langStrings
[n
];
1352 // FIXME: this doesn't do anything at all under Windows, we need
1353 // to create a new wxLocale!
1354 wxSetEnv(_T("LC_ALL"), langStr
);
1357 int lang
= gs_localeDefault
.GetSystemLanguage();
1358 printf("Locale for '%s' is %s.\n",
1359 langStr
? langStr
: "system default", GetLangName(lang
));
1363 #endif // TEST_LOCALE
1365 // ----------------------------------------------------------------------------
1367 // ----------------------------------------------------------------------------
1371 #include "wx/mimetype.h"
1373 static void TestMimeEnum()
1375 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1377 wxArrayString mimetypes
;
1379 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1381 printf("*** All %u known filetypes: ***\n", count
);
1386 for ( size_t n
= 0; n
< count
; n
++ )
1388 wxFileType
*filetype
=
1389 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1392 printf("nothing known about the filetype '%s'!\n",
1393 mimetypes
[n
].c_str());
1397 filetype
->GetDescription(&desc
);
1398 filetype
->GetExtensions(exts
);
1400 filetype
->GetIcon(NULL
);
1403 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1406 extsAll
<< _T(", ");
1410 printf("\t%s: %s (%s)\n",
1411 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1417 static void TestMimeOverride()
1419 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1421 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1422 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1424 if ( wxFile::Exists(mailcap
) )
1425 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1427 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1429 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1432 if ( wxFile::Exists(mimetypes
) )
1433 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1435 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1437 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1443 static void TestMimeFilename()
1445 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1447 static const wxChar
*filenames
[] =
1454 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1456 const wxString fname
= filenames
[n
];
1457 wxString ext
= fname
.AfterLast(_T('.'));
1458 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1461 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1466 if ( !ft
->GetDescription(&desc
) )
1467 desc
= _T("<no description>");
1470 if ( !ft
->GetOpenCommand(&cmd
,
1471 wxFileType::MessageParameters(fname
, _T(""))) )
1472 cmd
= _T("<no command available>");
1474 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1475 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1484 static void TestMimeAssociate()
1486 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1488 wxFileTypeInfo
ftInfo(
1489 _T("application/x-xyz"),
1490 _T("xyzview '%s'"), // open cmd
1491 _T(""), // print cmd
1492 _T("XYZ File") // description
1493 _T(".xyz"), // extensions
1494 NULL
// end of extensions
1496 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1498 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1501 wxPuts(_T("ERROR: failed to create association!"));
1505 // TODO: read it back
1514 // ----------------------------------------------------------------------------
1515 // misc information functions
1516 // ----------------------------------------------------------------------------
1518 #ifdef TEST_INFO_FUNCTIONS
1520 #include "wx/utils.h"
1522 static void TestDiskInfo()
1524 puts("*** Testing wxGetDiskSpace() ***");
1529 printf("\nEnter a directory name: ");
1530 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1533 // kill the last '\n'
1534 pathname
[strlen(pathname
) - 1] = 0;
1536 wxLongLong total
, free
;
1537 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1539 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1543 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1544 (total
/ 1024).ToString().c_str(),
1545 (free
/ 1024).ToString().c_str(),
1551 static void TestOsInfo()
1553 puts("*** Testing OS info functions ***\n");
1556 wxGetOsVersion(&major
, &minor
);
1557 printf("Running under: %s, version %d.%d\n",
1558 wxGetOsDescription().c_str(), major
, minor
);
1560 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1562 printf("Host name is %s (%s).\n",
1563 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1568 static void TestUserInfo()
1570 puts("*** Testing user info functions ***\n");
1572 printf("User id is:\t%s\n", wxGetUserId().c_str());
1573 printf("User name is:\t%s\n", wxGetUserName().c_str());
1574 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1575 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1580 #endif // TEST_INFO_FUNCTIONS
1582 // ----------------------------------------------------------------------------
1584 // ----------------------------------------------------------------------------
1586 #ifdef TEST_LONGLONG
1588 #include "wx/longlong.h"
1589 #include "wx/timer.h"
1591 // make a 64 bit number from 4 16 bit ones
1592 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1594 // get a random 64 bit number
1595 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1597 static const long testLongs
[] =
1608 #if wxUSE_LONGLONG_WX
1609 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1610 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1611 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1612 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1613 #endif // wxUSE_LONGLONG_WX
1615 static void TestSpeed()
1617 static const long max
= 100000000;
1624 for ( n
= 0; n
< max
; n
++ )
1629 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1632 #if wxUSE_LONGLONG_NATIVE
1637 for ( n
= 0; n
< max
; n
++ )
1642 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1644 #endif // wxUSE_LONGLONG_NATIVE
1650 for ( n
= 0; n
< max
; n
++ )
1655 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1659 static void TestLongLongConversion()
1661 puts("*** Testing wxLongLong conversions ***\n");
1665 for ( size_t n
= 0; n
< 100000; n
++ )
1669 #if wxUSE_LONGLONG_NATIVE
1670 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1672 wxASSERT_MSG( a
== b
, "conversions failure" );
1674 puts("Can't do it without native long long type, test skipped.");
1677 #endif // wxUSE_LONGLONG_NATIVE
1679 if ( !(nTested
% 1000) )
1691 static void TestMultiplication()
1693 puts("*** Testing wxLongLong multiplication ***\n");
1697 for ( size_t n
= 0; n
< 100000; n
++ )
1702 #if wxUSE_LONGLONG_NATIVE
1703 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1704 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1706 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1707 #else // !wxUSE_LONGLONG_NATIVE
1708 puts("Can't do it without native long long type, test skipped.");
1711 #endif // wxUSE_LONGLONG_NATIVE
1713 if ( !(nTested
% 1000) )
1725 static void TestDivision()
1727 puts("*** Testing wxLongLong division ***\n");
1731 for ( size_t n
= 0; n
< 100000; n
++ )
1733 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1734 // multiplication will not overflow)
1735 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1737 // get a random long (not wxLongLong for now) to divide it with
1742 #if wxUSE_LONGLONG_NATIVE
1743 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1745 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1746 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1747 #else // !wxUSE_LONGLONG_NATIVE
1748 // verify the result
1749 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1750 #endif // wxUSE_LONGLONG_NATIVE
1752 if ( !(nTested
% 1000) )
1764 static void TestAddition()
1766 puts("*** Testing wxLongLong addition ***\n");
1770 for ( size_t n
= 0; n
< 100000; n
++ )
1776 #if wxUSE_LONGLONG_NATIVE
1777 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1778 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1779 "addition failure" );
1780 #else // !wxUSE_LONGLONG_NATIVE
1781 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1782 #endif // wxUSE_LONGLONG_NATIVE
1784 if ( !(nTested
% 1000) )
1796 static void TestBitOperations()
1798 puts("*** Testing wxLongLong bit operation ***\n");
1802 for ( size_t n
= 0; n
< 100000; n
++ )
1806 #if wxUSE_LONGLONG_NATIVE
1807 for ( size_t n
= 0; n
< 33; n
++ )
1810 #else // !wxUSE_LONGLONG_NATIVE
1811 puts("Can't do it without native long long type, test skipped.");
1814 #endif // wxUSE_LONGLONG_NATIVE
1816 if ( !(nTested
% 1000) )
1828 static void TestLongLongComparison()
1830 #if wxUSE_LONGLONG_WX
1831 puts("*** Testing wxLongLong comparison ***\n");
1833 static const long ls
[2] =
1839 wxLongLongWx lls
[2];
1843 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1847 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1849 res
= lls
[m
] > testLongs
[n
];
1850 printf("0x%lx > 0x%lx is %s (%s)\n",
1851 ls
[m
], testLongs
[n
], res
? "true" : "false",
1852 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1854 res
= lls
[m
] < testLongs
[n
];
1855 printf("0x%lx < 0x%lx is %s (%s)\n",
1856 ls
[m
], testLongs
[n
], res
? "true" : "false",
1857 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1859 res
= lls
[m
] == testLongs
[n
];
1860 printf("0x%lx == 0x%lx is %s (%s)\n",
1861 ls
[m
], testLongs
[n
], res
? "true" : "false",
1862 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1865 #endif // wxUSE_LONGLONG_WX
1868 static void TestLongLongPrint()
1870 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1872 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1874 wxLongLong ll
= testLongs
[n
];
1875 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1878 wxLongLong
ll(0x12345678, 0x87654321);
1879 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1882 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1888 #endif // TEST_LONGLONG
1890 // ----------------------------------------------------------------------------
1892 // ----------------------------------------------------------------------------
1894 #ifdef TEST_PATHLIST
1896 static void TestPathList()
1898 puts("*** Testing wxPathList ***\n");
1900 wxPathList pathlist
;
1901 pathlist
.AddEnvList("PATH");
1902 wxString path
= pathlist
.FindValidPath("ls");
1905 printf("ERROR: command not found in the path.\n");
1909 printf("Command found in the path as '%s'.\n", path
.c_str());
1913 #endif // TEST_PATHLIST
1915 // ----------------------------------------------------------------------------
1916 // regular expressions
1917 // ----------------------------------------------------------------------------
1921 #include "wx/regex.h"
1923 static void TestRegExCompile()
1925 wxPuts(_T("*** Testing RE compilation ***\n"));
1927 static struct RegExCompTestData
1929 const wxChar
*pattern
;
1931 } regExCompTestData
[] =
1933 { _T("foo"), TRUE
},
1934 { _T("foo("), FALSE
},
1935 { _T("foo(bar"), FALSE
},
1936 { _T("foo(bar)"), TRUE
},
1937 { _T("foo["), FALSE
},
1938 { _T("foo[bar"), FALSE
},
1939 { _T("foo[bar]"), TRUE
},
1940 { _T("foo{"), TRUE
},
1941 { _T("foo{1"), FALSE
},
1942 { _T("foo{bar"), TRUE
},
1943 { _T("foo{1}"), TRUE
},
1944 { _T("foo{1,2}"), TRUE
},
1945 { _T("foo{bar}"), TRUE
},
1946 { _T("foo*"), TRUE
},
1947 { _T("foo**"), FALSE
},
1948 { _T("foo+"), TRUE
},
1949 { _T("foo++"), FALSE
},
1950 { _T("foo?"), TRUE
},
1951 { _T("foo??"), FALSE
},
1952 { _T("foo?+"), FALSE
},
1956 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1958 const RegExCompTestData
& data
= regExCompTestData
[n
];
1959 bool ok
= re
.Compile(data
.pattern
);
1961 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1963 ok
? _T("") : _T("not "),
1964 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1968 static void TestRegExMatch()
1970 wxPuts(_T("*** Testing RE matching ***\n"));
1972 static struct RegExMatchTestData
1974 const wxChar
*pattern
;
1977 } regExMatchTestData
[] =
1979 { _T("foo"), _T("bar"), FALSE
},
1980 { _T("foo"), _T("foobar"), TRUE
},
1981 { _T("^foo"), _T("foobar"), TRUE
},
1982 { _T("^foo"), _T("barfoo"), FALSE
},
1983 { _T("bar$"), _T("barbar"), TRUE
},
1984 { _T("bar$"), _T("barbar "), FALSE
},
1987 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1989 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1991 wxRegEx
re(data
.pattern
);
1992 bool ok
= re
.Matches(data
.text
);
1994 wxPrintf(_T("'%s' %s %s (%s)\n"),
1996 ok
? _T("matches") : _T("doesn't match"),
1998 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2002 static void TestRegExSubmatch()
2004 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2006 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2007 if ( !re
.IsValid() )
2009 wxPuts(_T("ERROR: compilation failed."));
2013 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2015 if ( !re
.Matches(text
) )
2017 wxPuts(_T("ERROR: match expected."));
2021 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2023 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2024 re
.GetMatch(text
, 3).c_str(),
2025 re
.GetMatch(text
, 2).c_str(),
2026 re
.GetMatch(text
, 4).c_str(),
2027 re
.GetMatch(text
, 1).c_str());
2031 static void TestRegExReplacement()
2033 wxPuts(_T("*** Testing RE replacement ***"));
2035 static struct RegExReplTestData
2039 const wxChar
*result
;
2041 } regExReplTestData
[] =
2043 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2044 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2045 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2046 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2047 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2048 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2049 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2052 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2053 wxRegEx re
= pattern
;
2055 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2057 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2059 const RegExReplTestData
& data
= regExReplTestData
[n
];
2061 wxString text
= data
.text
;
2062 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2064 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2065 data
.text
, data
.repl
,
2066 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2068 if ( text
== data
.result
&& nRepl
== data
.count
)
2074 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2075 data
.count
, data
.result
);
2080 static void TestRegExInteractive()
2082 wxPuts(_T("*** Testing RE interactively ***"));
2087 printf("\nEnter a pattern: ");
2088 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2091 // kill the last '\n'
2092 pattern
[strlen(pattern
) - 1] = 0;
2095 if ( !re
.Compile(pattern
) )
2103 printf("Enter text to match: ");
2104 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2107 // kill the last '\n'
2108 text
[strlen(text
) - 1] = 0;
2110 if ( !re
.Matches(text
) )
2112 printf("No match.\n");
2116 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2119 for ( size_t n
= 1; ; n
++ )
2121 if ( !re
.GetMatch(&start
, &len
, n
) )
2126 printf("Subexpr %u matched '%s'\n",
2127 n
, wxString(text
+ start
, len
).c_str());
2134 #endif // TEST_REGEX
2136 // ----------------------------------------------------------------------------
2137 // registry and related stuff
2138 // ----------------------------------------------------------------------------
2140 // this is for MSW only
2143 #undef TEST_REGISTRY
2148 #include "wx/confbase.h"
2149 #include "wx/msw/regconf.h"
2151 static void TestRegConfWrite()
2153 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2154 regconf
.Write(_T("Hello"), wxString(_T("world")));
2157 #endif // TEST_REGCONF
2159 #ifdef TEST_REGISTRY
2161 #include "wx/msw/registry.h"
2163 // I chose this one because I liked its name, but it probably only exists under
2165 static const wxChar
*TESTKEY
=
2166 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2168 static void TestRegistryRead()
2170 puts("*** testing registry reading ***");
2172 wxRegKey
key(TESTKEY
);
2173 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2176 puts("ERROR: test key can't be opened, aborting test.");
2181 size_t nSubKeys
, nValues
;
2182 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2184 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2187 printf("Enumerating values:\n");
2191 bool cont
= key
.GetFirstValue(value
, dummy
);
2194 printf("Value '%s': type ", value
.c_str());
2195 switch ( key
.GetValueType(value
) )
2197 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2198 case wxRegKey::Type_String
: printf("SZ"); break;
2199 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2200 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2201 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2202 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2203 default: printf("other (unknown)"); break;
2206 printf(", value = ");
2207 if ( key
.IsNumericValue(value
) )
2210 key
.QueryValue(value
, &val
);
2216 key
.QueryValue(value
, val
);
2217 printf("'%s'", val
.c_str());
2219 key
.QueryRawValue(value
, val
);
2220 printf(" (raw value '%s')", val
.c_str());
2225 cont
= key
.GetNextValue(value
, dummy
);
2229 static void TestRegistryAssociation()
2232 The second call to deleteself genertaes an error message, with a
2233 messagebox saying .flo is crucial to system operation, while the .ddf
2234 call also fails, but with no error message
2239 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2241 key
= "ddxf_auto_file" ;
2242 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2244 key
= "ddxf_auto_file" ;
2245 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2248 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2250 key
= "program \"%1\"" ;
2252 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2254 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2256 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2258 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2262 #endif // TEST_REGISTRY
2264 // ----------------------------------------------------------------------------
2266 // ----------------------------------------------------------------------------
2270 #include "wx/socket.h"
2271 #include "wx/protocol/protocol.h"
2272 #include "wx/protocol/http.h"
2274 static void TestSocketServer()
2276 puts("*** Testing wxSocketServer ***\n");
2278 static const int PORT
= 3000;
2283 wxSocketServer
*server
= new wxSocketServer(addr
);
2284 if ( !server
->Ok() )
2286 puts("ERROR: failed to bind");
2293 printf("Server: waiting for connection on port %d...\n", PORT
);
2295 wxSocketBase
*socket
= server
->Accept();
2298 puts("ERROR: wxSocketServer::Accept() failed.");
2302 puts("Server: got a client.");
2304 server
->SetTimeout(60); // 1 min
2306 while ( socket
->IsConnected() )
2312 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2314 // don't log error if the client just close the connection
2315 if ( socket
->IsConnected() )
2317 puts("ERROR: in wxSocket::Read.");
2337 printf("Server: got '%s'.\n", s
.c_str());
2338 if ( s
== _T("bye") )
2345 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2346 socket
->Write("\r\n", 2);
2347 printf("Server: wrote '%s'.\n", s
.c_str());
2350 puts("Server: lost a client.");
2355 // same as "delete server" but is consistent with GUI programs
2359 static void TestSocketClient()
2361 puts("*** Testing wxSocketClient ***\n");
2363 static const char *hostname
= "www.wxwindows.org";
2366 addr
.Hostname(hostname
);
2369 printf("--- Attempting to connect to %s:80...\n", hostname
);
2371 wxSocketClient client
;
2372 if ( !client
.Connect(addr
) )
2374 printf("ERROR: failed to connect to %s\n", hostname
);
2378 printf("--- Connected to %s:%u...\n",
2379 addr
.Hostname().c_str(), addr
.Service());
2383 // could use simply "GET" here I suppose
2385 wxString::Format("GET http://%s/\r\n", hostname
);
2386 client
.Write(cmdGet
, cmdGet
.length());
2387 printf("--- Sent command '%s' to the server\n",
2388 MakePrintable(cmdGet
).c_str());
2389 client
.Read(buf
, WXSIZEOF(buf
));
2390 printf("--- Server replied:\n%s", buf
);
2394 #endif // TEST_SOCKETS
2396 // ----------------------------------------------------------------------------
2398 // ----------------------------------------------------------------------------
2402 #include "wx/protocol/ftp.h"
2406 #define FTP_ANONYMOUS
2408 #ifdef FTP_ANONYMOUS
2409 static const char *directory
= "/pub";
2410 static const char *filename
= "welcome.msg";
2412 static const char *directory
= "/etc";
2413 static const char *filename
= "issue";
2416 static bool TestFtpConnect()
2418 puts("*** Testing FTP connect ***");
2420 #ifdef FTP_ANONYMOUS
2421 static const char *hostname
= "ftp.wxwindows.org";
2423 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2424 #else // !FTP_ANONYMOUS
2425 static const char *hostname
= "localhost";
2428 fgets(user
, WXSIZEOF(user
), stdin
);
2429 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2433 printf("Password for %s: ", password
);
2434 fgets(password
, WXSIZEOF(password
), stdin
);
2435 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2436 ftp
.SetPassword(password
);
2438 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2439 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2441 if ( !ftp
.Connect(hostname
) )
2443 printf("ERROR: failed to connect to %s\n", hostname
);
2449 printf("--- Connected to %s, current directory is '%s'\n",
2450 hostname
, ftp
.Pwd().c_str());
2456 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2457 static void TestFtpWuFtpd()
2460 static const char *hostname
= "ftp.eudora.com";
2461 if ( !ftp
.Connect(hostname
) )
2463 printf("ERROR: failed to connect to %s\n", hostname
);
2467 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2468 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2471 printf("ERROR: couldn't get input stream for %s\n", filename
);
2475 size_t size
= in
->StreamSize();
2476 printf("Reading file %s (%u bytes)...", filename
, size
);
2478 char *data
= new char[size
];
2479 if ( !in
->Read(data
, size
) )
2481 puts("ERROR: read error");
2485 printf("Successfully retrieved the file.\n");
2494 static void TestFtpList()
2496 puts("*** Testing wxFTP file listing ***\n");
2499 if ( !ftp
.ChDir(directory
) )
2501 printf("ERROR: failed to cd to %s\n", directory
);
2504 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2506 // test NLIST and LIST
2507 wxArrayString files
;
2508 if ( !ftp
.GetFilesList(files
) )
2510 puts("ERROR: failed to get NLIST of files");
2514 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2515 size_t count
= files
.GetCount();
2516 for ( size_t n
= 0; n
< count
; n
++ )
2518 printf("\t%s\n", files
[n
].c_str());
2520 puts("End of the file list");
2523 if ( !ftp
.GetDirList(files
) )
2525 puts("ERROR: failed to get LIST of files");
2529 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2530 size_t count
= files
.GetCount();
2531 for ( size_t n
= 0; n
< count
; n
++ )
2533 printf("\t%s\n", files
[n
].c_str());
2535 puts("End of the file list");
2538 if ( !ftp
.ChDir(_T("..")) )
2540 puts("ERROR: failed to cd to ..");
2543 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2546 static void TestFtpDownload()
2548 puts("*** Testing wxFTP download ***\n");
2551 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2554 printf("ERROR: couldn't get input stream for %s\n", filename
);
2558 size_t size
= in
->StreamSize();
2559 printf("Reading file %s (%u bytes)...", filename
, size
);
2562 char *data
= new char[size
];
2563 if ( !in
->Read(data
, size
) )
2565 puts("ERROR: read error");
2569 printf("\nContents of %s:\n%s\n", filename
, data
);
2577 static void TestFtpFileSize()
2579 puts("*** Testing FTP SIZE command ***");
2581 if ( !ftp
.ChDir(directory
) )
2583 printf("ERROR: failed to cd to %s\n", directory
);
2586 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2588 if ( ftp
.FileExists(filename
) )
2590 int size
= ftp
.GetFileSize(filename
);
2592 printf("ERROR: couldn't get size of '%s'\n", filename
);
2594 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2598 printf("ERROR: '%s' doesn't exist\n", filename
);
2602 static void TestFtpMisc()
2604 puts("*** Testing miscellaneous wxFTP functions ***");
2606 if ( ftp
.SendCommand("STAT") != '2' )
2608 puts("ERROR: STAT failed");
2612 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2615 if ( ftp
.SendCommand("HELP SITE") != '2' )
2617 puts("ERROR: HELP SITE failed");
2621 printf("The list of site-specific commands:\n\n%s\n",
2622 ftp
.GetLastResult().c_str());
2626 static void TestFtpInteractive()
2628 puts("\n*** Interactive wxFTP test ***");
2634 printf("Enter FTP command: ");
2635 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2638 // kill the last '\n'
2639 buf
[strlen(buf
) - 1] = 0;
2641 // special handling of LIST and NLST as they require data connection
2642 wxString
start(buf
, 4);
2644 if ( start
== "LIST" || start
== "NLST" )
2647 if ( strlen(buf
) > 4 )
2650 wxArrayString files
;
2651 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2653 printf("ERROR: failed to get %s of files\n", start
.c_str());
2657 printf("--- %s of '%s' under '%s':\n",
2658 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2659 size_t count
= files
.GetCount();
2660 for ( size_t n
= 0; n
< count
; n
++ )
2662 printf("\t%s\n", files
[n
].c_str());
2664 puts("--- End of the file list");
2669 char ch
= ftp
.SendCommand(buf
);
2670 printf("Command %s", ch
? "succeeded" : "failed");
2673 printf(" (return code %c)", ch
);
2676 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2680 puts("\n*** done ***");
2683 static void TestFtpUpload()
2685 puts("*** Testing wxFTP uploading ***\n");
2688 static const char *file1
= "test1";
2689 static const char *file2
= "test2";
2690 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2693 printf("--- Uploading to %s ---\n", file1
);
2694 out
->Write("First hello", 11);
2698 // send a command to check the remote file
2699 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2701 printf("ERROR: STAT %s failed\n", file1
);
2705 printf("STAT %s returned:\n\n%s\n",
2706 file1
, ftp
.GetLastResult().c_str());
2709 out
= ftp
.GetOutputStream(file2
);
2712 printf("--- Uploading to %s ---\n", file1
);
2713 out
->Write("Second hello", 12);
2720 // ----------------------------------------------------------------------------
2722 // ----------------------------------------------------------------------------
2726 #include "wx/wfstream.h"
2727 #include "wx/mstream.h"
2729 static void TestFileStream()
2731 puts("*** Testing wxFileInputStream ***");
2733 static const wxChar
*filename
= _T("testdata.fs");
2735 wxFileOutputStream
fsOut(filename
);
2736 fsOut
.Write("foo", 3);
2739 wxFileInputStream
fsIn(filename
);
2740 printf("File stream size: %u\n", fsIn
.GetSize());
2741 while ( !fsIn
.Eof() )
2743 putchar(fsIn
.GetC());
2746 if ( !wxRemoveFile(filename
) )
2748 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2751 puts("\n*** wxFileInputStream test done ***");
2754 static void TestMemoryStream()
2756 puts("*** Testing wxMemoryInputStream ***");
2759 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2761 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2762 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2763 while ( !memInpStream
.Eof() )
2765 putchar(memInpStream
.GetC());
2768 puts("\n*** wxMemoryInputStream test done ***");
2771 #endif // TEST_STREAMS
2773 // ----------------------------------------------------------------------------
2775 // ----------------------------------------------------------------------------
2779 #include "wx/timer.h"
2780 #include "wx/utils.h"
2782 static void TestStopWatch()
2784 puts("*** Testing wxStopWatch ***\n");
2787 printf("Sleeping 3 seconds...");
2789 printf("\telapsed time: %ldms\n", sw
.Time());
2792 printf("Sleeping 2 more seconds...");
2794 printf("\telapsed time: %ldms\n", sw
.Time());
2797 printf("And 3 more seconds...");
2799 printf("\telapsed time: %ldms\n", sw
.Time());
2802 puts("\nChecking for 'backwards clock' bug...");
2803 for ( size_t n
= 0; n
< 70; n
++ )
2807 for ( size_t m
= 0; m
< 100000; m
++ )
2809 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2811 puts("\ntime is negative - ERROR!");
2821 #endif // TEST_TIMER
2823 // ----------------------------------------------------------------------------
2825 // ----------------------------------------------------------------------------
2829 #include "wx/vcard.h"
2831 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2834 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2838 wxString(_T('\t'), level
).c_str(),
2839 vcObj
->GetName().c_str());
2842 switch ( vcObj
->GetType() )
2844 case wxVCardObject::String
:
2845 case wxVCardObject::UString
:
2848 vcObj
->GetValue(&val
);
2849 value
<< _T('"') << val
<< _T('"');
2853 case wxVCardObject::Int
:
2856 vcObj
->GetValue(&i
);
2857 value
.Printf(_T("%u"), i
);
2861 case wxVCardObject::Long
:
2864 vcObj
->GetValue(&l
);
2865 value
.Printf(_T("%lu"), l
);
2869 case wxVCardObject::None
:
2872 case wxVCardObject::Object
:
2873 value
= _T("<node>");
2877 value
= _T("<unknown value type>");
2881 printf(" = %s", value
.c_str());
2884 DumpVObject(level
+ 1, *vcObj
);
2887 vcObj
= vcard
.GetNextProp(&cookie
);
2891 static void DumpVCardAddresses(const wxVCard
& vcard
)
2893 puts("\nShowing all addresses from vCard:\n");
2897 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2901 int flags
= addr
->GetFlags();
2902 if ( flags
& wxVCardAddress::Domestic
)
2904 flagsStr
<< _T("domestic ");
2906 if ( flags
& wxVCardAddress::Intl
)
2908 flagsStr
<< _T("international ");
2910 if ( flags
& wxVCardAddress::Postal
)
2912 flagsStr
<< _T("postal ");
2914 if ( flags
& wxVCardAddress::Parcel
)
2916 flagsStr
<< _T("parcel ");
2918 if ( flags
& wxVCardAddress::Home
)
2920 flagsStr
<< _T("home ");
2922 if ( flags
& wxVCardAddress::Work
)
2924 flagsStr
<< _T("work ");
2927 printf("Address %u:\n"
2929 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2932 addr
->GetPostOffice().c_str(),
2933 addr
->GetExtAddress().c_str(),
2934 addr
->GetStreet().c_str(),
2935 addr
->GetLocality().c_str(),
2936 addr
->GetRegion().c_str(),
2937 addr
->GetPostalCode().c_str(),
2938 addr
->GetCountry().c_str()
2942 addr
= vcard
.GetNextAddress(&cookie
);
2946 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2948 puts("\nShowing all phone numbers from vCard:\n");
2952 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2956 int flags
= phone
->GetFlags();
2957 if ( flags
& wxVCardPhoneNumber::Voice
)
2959 flagsStr
<< _T("voice ");
2961 if ( flags
& wxVCardPhoneNumber::Fax
)
2963 flagsStr
<< _T("fax ");
2965 if ( flags
& wxVCardPhoneNumber::Cellular
)
2967 flagsStr
<< _T("cellular ");
2969 if ( flags
& wxVCardPhoneNumber::Modem
)
2971 flagsStr
<< _T("modem ");
2973 if ( flags
& wxVCardPhoneNumber::Home
)
2975 flagsStr
<< _T("home ");
2977 if ( flags
& wxVCardPhoneNumber::Work
)
2979 flagsStr
<< _T("work ");
2982 printf("Phone number %u:\n"
2987 phone
->GetNumber().c_str()
2991 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2995 static void TestVCardRead()
2997 puts("*** Testing wxVCard reading ***\n");
2999 wxVCard
vcard(_T("vcard.vcf"));
3000 if ( !vcard
.IsOk() )
3002 puts("ERROR: couldn't load vCard.");
3006 // read individual vCard properties
3007 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3011 vcObj
->GetValue(&value
);
3016 value
= _T("<none>");
3019 printf("Full name retrieved directly: %s\n", value
.c_str());
3022 if ( !vcard
.GetFullName(&value
) )
3024 value
= _T("<none>");
3027 printf("Full name from wxVCard API: %s\n", value
.c_str());
3029 // now show how to deal with multiply occuring properties
3030 DumpVCardAddresses(vcard
);
3031 DumpVCardPhoneNumbers(vcard
);
3033 // and finally show all
3034 puts("\nNow dumping the entire vCard:\n"
3035 "-----------------------------\n");
3037 DumpVObject(0, vcard
);
3041 static void TestVCardWrite()
3043 puts("*** Testing wxVCard writing ***\n");
3046 if ( !vcard
.IsOk() )
3048 puts("ERROR: couldn't create vCard.");
3053 vcard
.SetName("Zeitlin", "Vadim");
3054 vcard
.SetFullName("Vadim Zeitlin");
3055 vcard
.SetOrganization("wxWindows", "R&D");
3057 // just dump the vCard back
3058 puts("Entire vCard follows:\n");
3059 puts(vcard
.Write());
3063 #endif // TEST_VCARD
3065 // ----------------------------------------------------------------------------
3066 // wide char (Unicode) support
3067 // ----------------------------------------------------------------------------
3071 #include "wx/strconv.h"
3072 #include "wx/fontenc.h"
3073 #include "wx/encconv.h"
3074 #include "wx/buffer.h"
3076 static void TestUtf8()
3078 puts("*** Testing UTF8 support ***\n");
3080 static const char textInUtf8
[] =
3082 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3083 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3084 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3085 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3086 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3087 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3088 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3093 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3095 puts("ERROR: UTF-8 decoding failed.");
3099 // using wxEncodingConverter
3101 wxEncodingConverter ec
;
3102 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3103 ec
.Convert(wbuf
, buf
);
3104 #else // using wxCSConv
3105 wxCSConv
conv(_T("koi8-r"));
3106 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3108 puts("ERROR: conversion to KOI8-R failed.");
3113 printf("The resulting string (in koi8-r): %s\n", buf
);
3117 #endif // TEST_WCHAR
3119 // ----------------------------------------------------------------------------
3121 // ----------------------------------------------------------------------------
3125 #include "wx/filesys.h"
3126 #include "wx/fs_zip.h"
3127 #include "wx/zipstrm.h"
3129 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3131 static void TestZipStreamRead()
3133 puts("*** Testing ZIP reading ***\n");
3135 static const wxChar
*filename
= _T("foo");
3136 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3137 printf("Archive size: %u\n", istr
.GetSize());
3139 printf("Dumping the file '%s':\n", filename
);
3140 while ( !istr
.Eof() )
3142 putchar(istr
.GetC());
3146 puts("\n----- done ------");
3149 static void DumpZipDirectory(wxFileSystem
& fs
,
3150 const wxString
& dir
,
3151 const wxString
& indent
)
3153 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3154 TESTFILE_ZIP
, dir
.c_str());
3155 wxString wildcard
= prefix
+ _T("/*");
3157 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3158 while ( !dirname
.empty() )
3160 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3162 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3167 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3169 DumpZipDirectory(fs
, dirname
,
3170 indent
+ wxString(_T(' '), 4));
3172 dirname
= fs
.FindNext();
3175 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3176 while ( !filename
.empty() )
3178 if ( !filename
.StartsWith(prefix
, &filename
) )
3180 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3185 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3187 filename
= fs
.FindNext();
3191 static void TestZipFileSystem()
3193 puts("*** Testing ZIP file system ***\n");
3195 wxFileSystem::AddHandler(new wxZipFSHandler
);
3197 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3199 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3204 // ----------------------------------------------------------------------------
3206 // ----------------------------------------------------------------------------
3210 #include "wx/zstream.h"
3211 #include "wx/wfstream.h"
3213 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3214 static const char *TEST_DATA
= "hello and hello again";
3216 static void TestZlibStreamWrite()
3218 puts("*** Testing Zlib stream reading ***\n");
3220 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3221 wxZlibOutputStream
ostr(fileOutStream
, 0);
3222 printf("Compressing the test string... ");
3223 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3226 puts("(ERROR: failed)");
3233 puts("\n----- done ------");
3236 static void TestZlibStreamRead()
3238 puts("*** Testing Zlib stream reading ***\n");
3240 wxFileInputStream
fileInStream(FILENAME_GZ
);
3241 wxZlibInputStream
istr(fileInStream
);
3242 printf("Archive size: %u\n", istr
.GetSize());
3244 puts("Dumping the file:");
3245 while ( !istr
.Eof() )
3247 putchar(istr
.GetC());
3251 puts("\n----- done ------");
3256 // ----------------------------------------------------------------------------
3258 // ----------------------------------------------------------------------------
3260 #ifdef TEST_DATETIME
3264 #include "wx/date.h"
3265 #include "wx/datetime.h"
3270 wxDateTime::wxDateTime_t day
;
3271 wxDateTime::Month month
;
3273 wxDateTime::wxDateTime_t hour
, min
, sec
;
3275 wxDateTime::WeekDay wday
;
3276 time_t gmticks
, ticks
;
3278 void Init(const wxDateTime::Tm
& tm
)
3287 gmticks
= ticks
= -1;
3290 wxDateTime
DT() const
3291 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3293 bool SameDay(const wxDateTime::Tm
& tm
) const
3295 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3298 wxString
Format() const
3301 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3303 wxDateTime::GetMonthName(month
).c_str(),
3305 abs(wxDateTime::ConvertYearToBC(year
)),
3306 year
> 0 ? "AD" : "BC");
3310 wxString
FormatDate() const
3313 s
.Printf("%02d-%s-%4d%s",
3315 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3316 abs(wxDateTime::ConvertYearToBC(year
)),
3317 year
> 0 ? "AD" : "BC");
3322 static const Date testDates
[] =
3324 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3325 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3326 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3327 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3328 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3329 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3330 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3331 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3332 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3333 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3334 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3335 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3336 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3337 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3338 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3341 // this test miscellaneous static wxDateTime functions
3342 static void TestTimeStatic()
3344 puts("\n*** wxDateTime static methods test ***");
3346 // some info about the current date
3347 int year
= wxDateTime::GetCurrentYear();
3348 printf("Current year %d is %sa leap one and has %d days.\n",
3350 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3351 wxDateTime::GetNumberOfDays(year
));
3353 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3354 printf("Current month is '%s' ('%s') and it has %d days\n",
3355 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3356 wxDateTime::GetMonthName(month
).c_str(),
3357 wxDateTime::GetNumberOfDays(month
));
3360 static const size_t nYears
= 5;
3361 static const size_t years
[2][nYears
] =
3363 // first line: the years to test
3364 { 1990, 1976, 2000, 2030, 1984, },
3366 // second line: TRUE if leap, FALSE otherwise
3367 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3370 for ( size_t n
= 0; n
< nYears
; n
++ )
3372 int year
= years
[0][n
];
3373 bool should
= years
[1][n
] != 0,
3374 is
= wxDateTime::IsLeapYear(year
);
3376 printf("Year %d is %sa leap year (%s)\n",
3379 should
== is
? "ok" : "ERROR");
3381 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3385 // test constructing wxDateTime objects
3386 static void TestTimeSet()
3388 puts("\n*** wxDateTime construction test ***");
3390 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3392 const Date
& d1
= testDates
[n
];
3393 wxDateTime dt
= d1
.DT();
3396 d2
.Init(dt
.GetTm());
3398 wxString s1
= d1
.Format(),
3401 printf("Date: %s == %s (%s)\n",
3402 s1
.c_str(), s2
.c_str(),
3403 s1
== s2
? "ok" : "ERROR");
3407 // test time zones stuff
3408 static void TestTimeZones()
3410 puts("\n*** wxDateTime timezone test ***");
3412 wxDateTime now
= wxDateTime::Now();
3414 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3415 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3416 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3417 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3418 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3419 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3421 wxDateTime::Tm tm
= now
.GetTm();
3422 if ( wxDateTime(tm
) != now
)
3424 printf("ERROR: got %s instead of %s\n",
3425 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3429 // test some minimal support for the dates outside the standard range
3430 static void TestTimeRange()
3432 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3434 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3436 printf("Unix epoch:\t%s\n",
3437 wxDateTime(2440587.5).Format(fmt
).c_str());
3438 printf("Feb 29, 0: \t%s\n",
3439 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3440 printf("JDN 0: \t%s\n",
3441 wxDateTime(0.0).Format(fmt
).c_str());
3442 printf("Jan 1, 1AD:\t%s\n",
3443 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3444 printf("May 29, 2099:\t%s\n",
3445 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3448 static void TestTimeTicks()
3450 puts("\n*** wxDateTime ticks test ***");
3452 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3454 const Date
& d
= testDates
[n
];
3455 if ( d
.ticks
== -1 )
3458 wxDateTime dt
= d
.DT();
3459 long ticks
= (dt
.GetValue() / 1000).ToLong();
3460 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3461 if ( ticks
== d
.ticks
)
3467 printf(" (ERROR: should be %ld, delta = %ld)\n",
3468 d
.ticks
, ticks
- d
.ticks
);
3471 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3472 ticks
= (dt
.GetValue() / 1000).ToLong();
3473 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3474 if ( ticks
== d
.gmticks
)
3480 printf(" (ERROR: should be %ld, delta = %ld)\n",
3481 d
.gmticks
, ticks
- d
.gmticks
);
3488 // test conversions to JDN &c
3489 static void TestTimeJDN()
3491 puts("\n*** wxDateTime to JDN test ***");
3493 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3495 const Date
& d
= testDates
[n
];
3496 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3497 double jdn
= dt
.GetJulianDayNumber();
3499 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3506 printf(" (ERROR: should be %f, delta = %f)\n",
3507 d
.jdn
, jdn
- d
.jdn
);
3512 // test week days computation
3513 static void TestTimeWDays()
3515 puts("\n*** wxDateTime weekday test ***");
3517 // test GetWeekDay()
3519 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3521 const Date
& d
= testDates
[n
];
3522 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3524 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3527 wxDateTime::GetWeekDayName(wday
).c_str());
3528 if ( wday
== d
.wday
)
3534 printf(" (ERROR: should be %s)\n",
3535 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3541 // test SetToWeekDay()
3542 struct WeekDateTestData
3544 Date date
; // the real date (precomputed)
3545 int nWeek
; // its week index in the month
3546 wxDateTime::WeekDay wday
; // the weekday
3547 wxDateTime::Month month
; // the month
3548 int year
; // and the year
3550 wxString
Format() const
3553 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3555 case 1: which
= "first"; break;
3556 case 2: which
= "second"; break;
3557 case 3: which
= "third"; break;
3558 case 4: which
= "fourth"; break;
3559 case 5: which
= "fifth"; break;
3561 case -1: which
= "last"; break;
3566 which
+= " from end";
3569 s
.Printf("The %s %s of %s in %d",
3571 wxDateTime::GetWeekDayName(wday
).c_str(),
3572 wxDateTime::GetMonthName(month
).c_str(),
3579 // the array data was generated by the following python program
3581 from DateTime import *
3582 from whrandom import *
3583 from string import *
3585 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3586 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3588 week = DateTimeDelta(7)
3591 year = randint(1900, 2100)
3592 month = randint(1, 12)
3593 day = randint(1, 28)
3594 dt = DateTime(year, month, day)
3595 wday = dt.day_of_week
3597 countFromEnd = choice([-1, 1])
3600 while dt.month is month:
3601 dt = dt - countFromEnd * week
3602 weekNum = weekNum + countFromEnd
3604 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3606 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3607 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3610 static const WeekDateTestData weekDatesTestData
[] =
3612 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3613 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3614 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3615 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3616 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3617 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3618 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3619 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3620 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3621 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3622 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3623 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3624 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3625 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3626 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3627 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3628 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3629 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3630 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3631 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3634 static const char *fmt
= "%d-%b-%Y";
3637 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3639 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3641 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3643 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3645 const Date
& d
= wd
.date
;
3646 if ( d
.SameDay(dt
.GetTm()) )
3652 dt
.Set(d
.day
, d
.month
, d
.year
);
3654 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3659 // test the computation of (ISO) week numbers
3660 static void TestTimeWNumber()
3662 puts("\n*** wxDateTime week number test ***");
3664 struct WeekNumberTestData
3666 Date date
; // the date
3667 wxDateTime::wxDateTime_t week
; // the week number in the year
3668 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3669 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3670 wxDateTime::wxDateTime_t dnum
; // day number in the year
3673 // data generated with the following python script:
3675 from DateTime import *
3676 from whrandom import *
3677 from string import *
3679 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3680 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3682 def GetMonthWeek(dt):
3683 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3684 if weekNumMonth < 0:
3685 weekNumMonth = weekNumMonth + 53
3688 def GetLastSundayBefore(dt):
3689 if dt.iso_week[2] == 7:
3692 return dt - DateTimeDelta(dt.iso_week[2])
3695 year = randint(1900, 2100)
3696 month = randint(1, 12)
3697 day = randint(1, 28)
3698 dt = DateTime(year, month, day)
3699 dayNum = dt.day_of_year
3700 weekNum = dt.iso_week[1]
3701 weekNumMonth = GetMonthWeek(dt)
3704 dtSunday = GetLastSundayBefore(dt)
3706 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3707 weekNumMonth2 = weekNumMonth2 + 1
3708 dtSunday = dtSunday - DateTimeDelta(7)
3710 data = { 'day': rjust(`day`, 2), \
3711 'month': monthNames[month - 1], \
3713 'weekNum': rjust(`weekNum`, 2), \
3714 'weekNumMonth': weekNumMonth, \
3715 'weekNumMonth2': weekNumMonth2, \
3716 'dayNum': rjust(`dayNum`, 3) }
3718 print " { { %(day)s, "\
3719 "wxDateTime::%(month)s, "\
3722 "%(weekNumMonth)s, "\
3723 "%(weekNumMonth2)s, "\
3724 "%(dayNum)s }," % data
3727 static const WeekNumberTestData weekNumberTestDates
[] =
3729 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3730 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3731 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3732 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3733 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3734 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3735 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3736 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3737 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3738 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3739 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3740 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3741 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3742 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3743 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3744 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3745 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3746 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3747 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3748 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3751 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3753 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3754 const Date
& d
= wn
.date
;
3756 wxDateTime dt
= d
.DT();
3758 wxDateTime::wxDateTime_t
3759 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3760 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3761 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3762 dnum
= dt
.GetDayOfYear();
3764 printf("%s: the day number is %d",
3765 d
.FormatDate().c_str(), dnum
);
3766 if ( dnum
== wn
.dnum
)
3772 printf(" (ERROR: should be %d)", wn
.dnum
);
3775 printf(", week in month is %d", wmon
);
3776 if ( wmon
== wn
.wmon
)
3782 printf(" (ERROR: should be %d)", wn
.wmon
);
3785 printf(" or %d", wmon2
);
3786 if ( wmon2
== wn
.wmon2
)
3792 printf(" (ERROR: should be %d)", wn
.wmon2
);
3795 printf(", week in year is %d", week
);
3796 if ( week
== wn
.week
)
3802 printf(" (ERROR: should be %d)\n", wn
.week
);
3807 // test DST calculations
3808 static void TestTimeDST()
3810 puts("\n*** wxDateTime DST test ***");
3812 printf("DST is%s in effect now.\n\n",
3813 wxDateTime::Now().IsDST() ? "" : " not");
3815 // taken from http://www.energy.ca.gov/daylightsaving.html
3816 static const Date datesDST
[2][2004 - 1900 + 1] =
3819 { 1, wxDateTime::Apr
, 1990 },
3820 { 7, wxDateTime::Apr
, 1991 },
3821 { 5, wxDateTime::Apr
, 1992 },
3822 { 4, wxDateTime::Apr
, 1993 },
3823 { 3, wxDateTime::Apr
, 1994 },
3824 { 2, wxDateTime::Apr
, 1995 },
3825 { 7, wxDateTime::Apr
, 1996 },
3826 { 6, wxDateTime::Apr
, 1997 },
3827 { 5, wxDateTime::Apr
, 1998 },
3828 { 4, wxDateTime::Apr
, 1999 },
3829 { 2, wxDateTime::Apr
, 2000 },
3830 { 1, wxDateTime::Apr
, 2001 },
3831 { 7, wxDateTime::Apr
, 2002 },
3832 { 6, wxDateTime::Apr
, 2003 },
3833 { 4, wxDateTime::Apr
, 2004 },
3836 { 28, wxDateTime::Oct
, 1990 },
3837 { 27, wxDateTime::Oct
, 1991 },
3838 { 25, wxDateTime::Oct
, 1992 },
3839 { 31, wxDateTime::Oct
, 1993 },
3840 { 30, wxDateTime::Oct
, 1994 },
3841 { 29, wxDateTime::Oct
, 1995 },
3842 { 27, wxDateTime::Oct
, 1996 },
3843 { 26, wxDateTime::Oct
, 1997 },
3844 { 25, wxDateTime::Oct
, 1998 },
3845 { 31, wxDateTime::Oct
, 1999 },
3846 { 29, wxDateTime::Oct
, 2000 },
3847 { 28, wxDateTime::Oct
, 2001 },
3848 { 27, wxDateTime::Oct
, 2002 },
3849 { 26, wxDateTime::Oct
, 2003 },
3850 { 31, wxDateTime::Oct
, 2004 },
3855 for ( year
= 1990; year
< 2005; year
++ )
3857 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3858 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3860 printf("DST period in the US for year %d: from %s to %s",
3861 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3863 size_t n
= year
- 1990;
3864 const Date
& dBegin
= datesDST
[0][n
];
3865 const Date
& dEnd
= datesDST
[1][n
];
3867 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3873 printf(" (ERROR: should be %s %d to %s %d)\n",
3874 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3875 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3881 for ( year
= 1990; year
< 2005; year
++ )
3883 printf("DST period in Europe for year %d: from %s to %s\n",
3885 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3886 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3890 // test wxDateTime -> text conversion
3891 static void TestTimeFormat()
3893 puts("\n*** wxDateTime formatting test ***");
3895 // some information may be lost during conversion, so store what kind
3896 // of info should we recover after a round trip
3899 CompareNone
, // don't try comparing
3900 CompareBoth
, // dates and times should be identical
3901 CompareDate
, // dates only
3902 CompareTime
// time only
3907 CompareKind compareKind
;
3909 } formatTestFormats
[] =
3911 { CompareBoth
, "---> %c" },
3912 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3913 { CompareBoth
, "Date is %x, time is %X" },
3914 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3915 { CompareNone
, "The day of year: %j, the week of year: %W" },
3916 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3919 static const Date formatTestDates
[] =
3921 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3922 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3924 // this test can't work for other centuries because it uses two digit
3925 // years in formats, so don't even try it
3926 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3927 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3928 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3932 // an extra test (as it doesn't depend on date, don't do it in the loop)
3933 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3935 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3939 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3940 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3942 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3943 printf("%s", s
.c_str());
3945 // what can we recover?
3946 int kind
= formatTestFormats
[n
].compareKind
;
3950 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3953 // converion failed - should it have?
3954 if ( kind
== CompareNone
)
3957 puts(" (ERROR: conversion back failed)");
3961 // should have parsed the entire string
3962 puts(" (ERROR: conversion back stopped too soon)");
3966 bool equal
= FALSE
; // suppress compilaer warning
3974 equal
= dt
.IsSameDate(dt2
);
3978 equal
= dt
.IsSameTime(dt2
);
3984 printf(" (ERROR: got back '%s' instead of '%s')\n",
3985 dt2
.Format().c_str(), dt
.Format().c_str());
3996 // test text -> wxDateTime conversion
3997 static void TestTimeParse()
3999 puts("\n*** wxDateTime parse test ***");
4001 struct ParseTestData
4008 static const ParseTestData parseTestDates
[] =
4010 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4011 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4014 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4016 const char *format
= parseTestDates
[n
].format
;
4018 printf("%s => ", format
);
4021 if ( dt
.ParseRfc822Date(format
) )
4023 printf("%s ", dt
.Format().c_str());
4025 if ( parseTestDates
[n
].good
)
4027 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4034 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4039 puts("(ERROR: bad format)");
4044 printf("bad format (%s)\n",
4045 parseTestDates
[n
].good
? "ERROR" : "ok");
4050 static void TestDateTimeInteractive()
4052 puts("\n*** interactive wxDateTime tests ***");
4058 printf("Enter a date: ");
4059 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4062 // kill the last '\n'
4063 buf
[strlen(buf
) - 1] = 0;
4066 const char *p
= dt
.ParseDate(buf
);
4069 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4075 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4078 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4079 dt
.Format("%b %d, %Y").c_str(),
4081 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4082 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4083 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4086 puts("\n*** done ***");
4089 static void TestTimeMS()
4091 puts("*** testing millisecond-resolution support in wxDateTime ***");
4093 wxDateTime dt1
= wxDateTime::Now(),
4094 dt2
= wxDateTime::UNow();
4096 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4097 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4098 printf("Dummy loop: ");
4099 for ( int i
= 0; i
< 6000; i
++ )
4101 //for ( int j = 0; j < 10; j++ )
4104 s
.Printf("%g", sqrt(i
));
4113 dt2
= wxDateTime::UNow();
4114 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4116 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4118 puts("\n*** done ***");
4121 static void TestTimeArithmetics()
4123 puts("\n*** testing arithmetic operations on wxDateTime ***");
4125 static const struct ArithmData
4127 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4128 : span(sp
), name(nam
) { }
4132 } testArithmData
[] =
4134 ArithmData(wxDateSpan::Day(), "day"),
4135 ArithmData(wxDateSpan::Week(), "week"),
4136 ArithmData(wxDateSpan::Month(), "month"),
4137 ArithmData(wxDateSpan::Year(), "year"),
4138 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4141 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4143 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4145 wxDateSpan span
= testArithmData
[n
].span
;
4149 const char *name
= testArithmData
[n
].name
;
4150 printf("%s + %s = %s, %s - %s = %s\n",
4151 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4152 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4154 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4155 if ( dt1
- span
== dt
)
4161 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4164 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4165 if ( dt2
+ span
== dt
)
4171 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4174 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4175 if ( dt2
+ 2*span
== dt1
)
4181 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4188 static void TestTimeHolidays()
4190 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4192 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4193 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4194 dtEnd
= dtStart
.GetLastMonthDay();
4196 wxDateTimeArray hol
;
4197 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4199 const wxChar
*format
= "%d-%b-%Y (%a)";
4201 printf("All holidays between %s and %s:\n",
4202 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4204 size_t count
= hol
.GetCount();
4205 for ( size_t n
= 0; n
< count
; n
++ )
4207 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4213 static void TestTimeZoneBug()
4215 puts("\n*** testing for DST/timezone bug ***\n");
4217 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4218 for ( int i
= 0; i
< 31; i
++ )
4220 printf("Date %s: week day %s.\n",
4221 date
.Format(_T("%d-%m-%Y")).c_str(),
4222 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4224 date
+= wxDateSpan::Day();
4230 static void TestTimeSpanFormat()
4232 puts("\n*** wxTimeSpan tests ***");
4234 static const char *formats
[] =
4236 _T("(default) %H:%M:%S"),
4237 _T("%E weeks and %D days"),
4238 _T("%l milliseconds"),
4239 _T("(with ms) %H:%M:%S:%l"),
4240 _T("100%% of minutes is %M"), // test "%%"
4241 _T("%D days and %H hours"),
4242 _T("or also %S seconds"),
4245 wxTimeSpan
ts1(1, 2, 3, 4),
4247 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4249 printf("ts1 = %s\tts2 = %s\n",
4250 ts1
.Format(formats
[n
]).c_str(),
4251 ts2
.Format(formats
[n
]).c_str());
4259 // test compatibility with the old wxDate/wxTime classes
4260 static void TestTimeCompatibility()
4262 puts("\n*** wxDateTime compatibility test ***");
4264 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4265 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4267 double jdnNow
= wxDateTime::Now().GetJDN();
4268 long jdnMidnight
= (long)(jdnNow
- 0.5);
4269 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4271 jdnMidnight
= wxDate().Set().GetJulianDate();
4272 printf("wxDateTime for today: %s\n",
4273 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4275 int flags
= wxEUROPEAN
;//wxFULL;
4278 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4279 for ( int n
= 0; n
< 7; n
++ )
4281 printf("Previous %s is %s\n",
4282 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4283 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4289 #endif // TEST_DATETIME
4291 // ----------------------------------------------------------------------------
4293 // ----------------------------------------------------------------------------
4297 #include "wx/thread.h"
4299 static size_t gs_counter
= (size_t)-1;
4300 static wxCriticalSection gs_critsect
;
4301 static wxCondition gs_cond
;
4303 class MyJoinableThread
: public wxThread
4306 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4307 { m_n
= n
; Create(); }
4309 // thread execution starts here
4310 virtual ExitCode
Entry();
4316 wxThread::ExitCode
MyJoinableThread::Entry()
4318 unsigned long res
= 1;
4319 for ( size_t n
= 1; n
< m_n
; n
++ )
4323 // it's a loooong calculation :-)
4327 return (ExitCode
)res
;
4330 class MyDetachedThread
: public wxThread
4333 MyDetachedThread(size_t n
, char ch
)
4337 m_cancelled
= FALSE
;
4342 // thread execution starts here
4343 virtual ExitCode
Entry();
4346 virtual void OnExit();
4349 size_t m_n
; // number of characters to write
4350 char m_ch
; // character to write
4352 bool m_cancelled
; // FALSE if we exit normally
4355 wxThread::ExitCode
MyDetachedThread::Entry()
4358 wxCriticalSectionLocker
lock(gs_critsect
);
4359 if ( gs_counter
== (size_t)-1 )
4365 for ( size_t n
= 0; n
< m_n
; n
++ )
4367 if ( TestDestroy() )
4377 wxThread::Sleep(100);
4383 void MyDetachedThread::OnExit()
4385 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4387 wxCriticalSectionLocker
lock(gs_critsect
);
4388 if ( !--gs_counter
&& !m_cancelled
)
4392 void TestDetachedThreads()
4394 puts("\n*** Testing detached threads ***");
4396 static const size_t nThreads
= 3;
4397 MyDetachedThread
*threads
[nThreads
];
4399 for ( n
= 0; n
< nThreads
; n
++ )
4401 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4404 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4405 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4407 for ( n
= 0; n
< nThreads
; n
++ )
4412 // wait until all threads terminate
4418 void TestJoinableThreads()
4420 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4422 // calc 10! in the background
4423 MyJoinableThread
thread(10);
4426 printf("\nThread terminated with exit code %lu.\n",
4427 (unsigned long)thread
.Wait());
4430 void TestThreadSuspend()
4432 puts("\n*** Testing thread suspend/resume functions ***");
4434 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4438 // this is for this demo only, in a real life program we'd use another
4439 // condition variable which would be signaled from wxThread::Entry() to
4440 // tell us that the thread really started running - but here just wait a
4441 // bit and hope that it will be enough (the problem is, of course, that
4442 // the thread might still not run when we call Pause() which will result
4444 wxThread::Sleep(300);
4446 for ( size_t n
= 0; n
< 3; n
++ )
4450 puts("\nThread suspended");
4453 // don't sleep but resume immediately the first time
4454 wxThread::Sleep(300);
4456 puts("Going to resume the thread");
4461 puts("Waiting until it terminates now");
4463 // wait until the thread terminates
4469 void TestThreadDelete()
4471 // As above, using Sleep() is only for testing here - we must use some
4472 // synchronisation object instead to ensure that the thread is still
4473 // running when we delete it - deleting a detached thread which already
4474 // terminated will lead to a crash!
4476 puts("\n*** Testing thread delete function ***");
4478 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4482 puts("\nDeleted a thread which didn't start to run yet.");
4484 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4488 wxThread::Sleep(300);
4492 puts("\nDeleted a running thread.");
4494 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4498 wxThread::Sleep(300);
4504 puts("\nDeleted a sleeping thread.");
4506 MyJoinableThread
thread3(20);
4511 puts("\nDeleted a joinable thread.");
4513 MyJoinableThread
thread4(2);
4516 wxThread::Sleep(300);
4520 puts("\nDeleted a joinable thread which already terminated.");
4525 #endif // TEST_THREADS
4527 // ----------------------------------------------------------------------------
4529 // ----------------------------------------------------------------------------
4533 static void PrintArray(const char* name
, const wxArrayString
& 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] = '%s'\n", name
, n
, array
[n
].c_str());
4544 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4546 printf("Dump of the array '%s'\n", name
);
4548 size_t nCount
= array
.GetCount();
4549 for ( size_t n
= 0; n
< nCount
; n
++ )
4551 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4555 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4556 const wxString
& second
)
4558 return first
.length() - second
.length();
4561 int wxCMPFUNC_CONV
IntCompare(int *first
,
4564 return *first
- *second
;
4567 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4570 return *second
- *first
;
4573 static void TestArrayOfInts()
4575 puts("*** Testing wxArrayInt ***\n");
4586 puts("After sort:");
4590 puts("After reverse sort:");
4591 a
.Sort(IntRevCompare
);
4595 #include "wx/dynarray.h"
4597 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4598 #include "wx/arrimpl.cpp"
4599 WX_DEFINE_OBJARRAY(ArrayBars
);
4601 static void TestArrayOfObjects()
4603 puts("*** Testing wxObjArray ***\n");
4607 Bar
bar("second bar");
4609 printf("Initially: %u objects in the array, %u objects total.\n",
4610 bars
.GetCount(), Bar::GetNumber());
4612 bars
.Add(new Bar("first bar"));
4615 printf("Now: %u objects in the array, %u objects total.\n",
4616 bars
.GetCount(), Bar::GetNumber());
4620 printf("After Empty(): %u objects in the array, %u objects total.\n",
4621 bars
.GetCount(), Bar::GetNumber());
4624 printf("Finally: no more objects in the array, %u objects total.\n",
4628 #endif // TEST_ARRAYS
4630 // ----------------------------------------------------------------------------
4632 // ----------------------------------------------------------------------------
4636 #include "wx/timer.h"
4637 #include "wx/tokenzr.h"
4639 static void TestStringConstruction()
4641 puts("*** Testing wxString constructores ***");
4643 #define TEST_CTOR(args, res) \
4646 printf("wxString%s = %s ", #args, s.c_str()); \
4653 printf("(ERROR: should be %s)\n", res); \
4657 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4658 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4659 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4660 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4662 static const wxChar
*s
= _T("?really!");
4663 const wxChar
*start
= wxStrchr(s
, _T('r'));
4664 const wxChar
*end
= wxStrchr(s
, _T('!'));
4665 TEST_CTOR((start
, end
), _T("really"));
4670 static void TestString()
4680 for (int i
= 0; i
< 1000000; ++i
)
4684 c
= "! How'ya doin'?";
4687 c
= "Hello world! What's up?";
4692 printf ("TestString elapsed time: %ld\n", sw
.Time());
4695 static void TestPChar()
4703 for (int i
= 0; i
< 1000000; ++i
)
4705 strcpy (a
, "Hello");
4706 strcpy (b
, " world");
4707 strcpy (c
, "! How'ya doin'?");
4710 strcpy (c
, "Hello world! What's up?");
4711 if (strcmp (c
, a
) == 0)
4715 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4718 static void TestStringSub()
4720 wxString
s("Hello, world!");
4722 puts("*** Testing wxString substring extraction ***");
4724 printf("String = '%s'\n", s
.c_str());
4725 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4726 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4727 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4728 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4729 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4730 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4732 static const wxChar
*prefixes
[] =
4736 _T("Hello, world!"),
4737 _T("Hello, world!!!"),
4743 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4745 wxString prefix
= prefixes
[n
], rest
;
4746 bool rc
= s
.StartsWith(prefix
, &rest
);
4747 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4750 printf(" (the rest is '%s')\n", rest
.c_str());
4761 static void TestStringFormat()
4763 puts("*** Testing wxString formatting ***");
4766 s
.Printf("%03d", 18);
4768 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4769 printf("Number 18: %s\n", s
.c_str());
4774 // returns "not found" for npos, value for all others
4775 static wxString
PosToString(size_t res
)
4777 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4778 : wxString::Format(_T("%u"), res
);
4782 static void TestStringFind()
4784 puts("*** Testing wxString find() functions ***");
4786 static const wxChar
*strToFind
= _T("ell");
4787 static const struct StringFindTest
4791 result
; // of searching "ell" in str
4794 { _T("Well, hello world"), 0, 1 },
4795 { _T("Well, hello world"), 6, 7 },
4796 { _T("Well, hello world"), 9, wxString::npos
},
4799 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4801 const StringFindTest
& ft
= findTestData
[n
];
4802 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4804 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4805 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4807 size_t resTrue
= ft
.result
;
4808 if ( res
== resTrue
)
4814 printf(_T("(ERROR: should be %s)\n"),
4815 PosToString(resTrue
).c_str());
4822 static void TestStringTokenizer()
4824 puts("*** Testing wxStringTokenizer ***");
4826 static const wxChar
*modeNames
[] =
4830 _T("return all empty"),
4835 static const struct StringTokenizerTest
4837 const wxChar
*str
; // string to tokenize
4838 const wxChar
*delims
; // delimiters to use
4839 size_t count
; // count of token
4840 wxStringTokenizerMode mode
; // how should we tokenize it
4841 } tokenizerTestData
[] =
4843 { _T(""), _T(" "), 0 },
4844 { _T("Hello, world"), _T(" "), 2 },
4845 { _T("Hello, world "), _T(" "), 2 },
4846 { _T("Hello, world"), _T(","), 2 },
4847 { _T("Hello, world!"), _T(",!"), 2 },
4848 { _T("Hello,, world!"), _T(",!"), 3 },
4849 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4850 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4851 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4852 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4853 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4854 { _T("01/02/99"), _T("/-"), 3 },
4855 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4858 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4860 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4861 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4863 size_t count
= tkz
.CountTokens();
4864 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4865 MakePrintable(tt
.str
).c_str(),
4867 MakePrintable(tt
.delims
).c_str(),
4868 modeNames
[tkz
.GetMode()]);
4869 if ( count
== tt
.count
)
4875 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4880 // if we emulate strtok(), check that we do it correctly
4881 wxChar
*buf
, *s
= NULL
, *last
;
4883 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4885 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4886 wxStrcpy(buf
, tt
.str
);
4888 s
= wxStrtok(buf
, tt
.delims
, &last
);
4895 // now show the tokens themselves
4897 while ( tkz
.HasMoreTokens() )
4899 wxString token
= tkz
.GetNextToken();
4901 printf(_T("\ttoken %u: '%s'"),
4903 MakePrintable(token
).c_str());
4913 printf(" (ERROR: should be %s)\n", s
);
4916 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4920 // nothing to compare with
4925 if ( count2
!= count
)
4927 puts(_T("\tERROR: token count mismatch"));
4936 static void TestStringReplace()
4938 puts("*** Testing wxString::replace ***");
4940 static const struct StringReplaceTestData
4942 const wxChar
*original
; // original test string
4943 size_t start
, len
; // the part to replace
4944 const wxChar
*replacement
; // the replacement string
4945 const wxChar
*result
; // and the expected result
4946 } stringReplaceTestData
[] =
4948 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4949 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4950 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4951 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4952 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4955 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4957 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4959 wxString original
= data
.original
;
4960 original
.replace(data
.start
, data
.len
, data
.replacement
);
4962 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4963 data
.original
, data
.start
, data
.len
, data
.replacement
,
4966 if ( original
== data
.result
)
4972 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4979 static void TestStringMatch()
4981 wxPuts(_T("*** Testing wxString::Matches() ***"));
4983 static const struct StringMatchTestData
4986 const wxChar
*wildcard
;
4988 } stringMatchTestData
[] =
4990 { _T("foobar"), _T("foo*"), 1 },
4991 { _T("foobar"), _T("*oo*"), 1 },
4992 { _T("foobar"), _T("*bar"), 1 },
4993 { _T("foobar"), _T("??????"), 1 },
4994 { _T("foobar"), _T("f??b*"), 1 },
4995 { _T("foobar"), _T("f?b*"), 0 },
4996 { _T("foobar"), _T("*goo*"), 0 },
4997 { _T("foobar"), _T("*foo"), 0 },
4998 { _T("foobarfoo"), _T("*foo"), 1 },
4999 { _T(""), _T("*"), 1 },
5000 { _T(""), _T("?"), 0 },
5003 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5005 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5006 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5007 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5009 matches
? _T("matches") : _T("doesn't match"),
5011 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5017 #endif // TEST_STRINGS
5019 // ----------------------------------------------------------------------------
5021 // ----------------------------------------------------------------------------
5023 int main(int argc
, char **argv
)
5025 wxInitializer initializer
;
5028 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5033 #ifdef TEST_SNGLINST
5034 wxSingleInstanceChecker checker
;
5035 if ( checker
.Create(_T(".wxconsole.lock")) )
5037 if ( checker
.IsAnotherRunning() )
5039 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5044 // wait some time to give time to launch another instance
5045 wxPrintf(_T("Press \"Enter\" to continue..."));
5048 else // failed to create
5050 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5052 #endif // TEST_SNGLINST
5056 #endif // TEST_CHARSET
5059 TestCmdLineConvert();
5061 #if wxUSE_CMDLINE_PARSER
5062 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5064 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5065 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5066 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5067 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5069 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5070 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5071 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5072 wxCMD_LINE_VAL_NUMBER
},
5073 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5074 wxCMD_LINE_VAL_DATE
},
5076 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5077 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5082 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5084 parser
.AddOption("project_name", "", "full path to project file",
5085 wxCMD_LINE_VAL_STRING
,
5086 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5088 switch ( parser
.Parse() )
5091 wxLogMessage("Help was given, terminating.");
5095 ShowCmdLine(parser
);
5099 wxLogMessage("Syntax error detected, aborting.");
5102 #endif // wxUSE_CMDLINE_PARSER
5104 #endif // TEST_CMDLINE
5112 TestStringConstruction();
5115 TestStringTokenizer();
5116 TestStringReplace();
5119 #endif // TEST_STRINGS
5132 puts("*** Initially:");
5134 PrintArray("a1", a1
);
5136 wxArrayString
a2(a1
);
5137 PrintArray("a2", a2
);
5139 wxSortedArrayString
a3(a1
);
5140 PrintArray("a3", a3
);
5142 puts("*** After deleting a string from a1");
5145 PrintArray("a1", a1
);
5146 PrintArray("a2", a2
);
5147 PrintArray("a3", a3
);
5149 puts("*** After reassigning a1 to a2 and a3");
5151 PrintArray("a2", a2
);
5152 PrintArray("a3", a3
);
5154 puts("*** After sorting a1");
5156 PrintArray("a1", a1
);
5158 puts("*** After sorting a1 in reverse order");
5160 PrintArray("a1", a1
);
5162 puts("*** After sorting a1 by the string length");
5163 a1
.Sort(StringLenCompare
);
5164 PrintArray("a1", a1
);
5166 TestArrayOfObjects();
5169 #endif // TEST_ARRAYS
5177 #ifdef TEST_DLLLOADER
5179 #endif // TEST_DLLLOADER
5183 #endif // TEST_ENVIRON
5187 #endif // TEST_EXECUTE
5189 #ifdef TEST_FILECONF
5191 #endif // TEST_FILECONF
5199 #endif // TEST_LOCALE
5203 for ( size_t n
= 0; n
< 8000; n
++ )
5205 s
<< (char)('A' + (n
% 26));
5209 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5211 // this one shouldn't be truncated
5214 // but this one will because log functions use fixed size buffer
5215 // (note that it doesn't need '\n' at the end neither - will be added
5217 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5229 #ifdef TEST_FILENAME
5233 fn
.Assign("c:\\foo", "bar.baz");
5240 TestFileNameConstruction();
5241 TestFileNameSplit();
5244 TestFileNameComparison();
5245 TestFileNameOperations();
5247 #endif // TEST_FILENAME
5249 #ifdef TEST_FILETIME
5252 #endif // TEST_FILETIME
5255 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5256 if ( TestFtpConnect() )
5267 TestFtpInteractive();
5269 //else: connecting to the FTP server failed
5276 int nCPUs
= wxThread::GetCPUCount();
5277 printf("This system has %d CPUs\n", nCPUs
);
5279 wxThread::SetConcurrency(nCPUs
);
5281 if ( argc
> 1 && argv
[1][0] == 't' )
5282 wxLog::AddTraceMask("thread");
5285 TestDetachedThreads();
5287 TestJoinableThreads();
5289 TestThreadSuspend();
5293 #endif // TEST_THREADS
5295 #ifdef TEST_LONGLONG
5296 // seed pseudo random generator
5297 srand((unsigned)time(NULL
));
5305 TestMultiplication();
5308 TestLongLongConversion();
5309 TestBitOperations();
5310 TestLongLongComparison();
5312 TestLongLongPrint();
5313 #endif // TEST_LONGLONG
5320 wxLog::AddTraceMask(_T("mime"));
5328 TestMimeAssociate();
5331 #ifdef TEST_INFO_FUNCTIONS
5338 #endif // TEST_INFO_FUNCTIONS
5340 #ifdef TEST_PATHLIST
5342 #endif // TEST_PATHLIST
5346 #endif // TEST_REGCONF
5349 // TODO: write a real test using src/regex/tests file
5354 TestRegExSubmatch();
5355 TestRegExInteractive();
5357 TestRegExReplacement();
5358 #endif // TEST_REGEX
5360 #ifdef TEST_REGISTRY
5363 TestRegistryAssociation();
5364 #endif // TEST_REGISTRY
5372 #endif // TEST_SOCKETS
5378 #endif // TEST_STREAMS
5382 #endif // TEST_TIMER
5384 #ifdef TEST_DATETIME
5397 TestTimeArithmetics();
5404 TestTimeSpanFormat();
5406 TestDateTimeInteractive();
5407 #endif // TEST_DATETIME
5410 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5412 #endif // TEST_USLEEP
5418 #endif // TEST_VCARD
5422 #endif // TEST_WCHAR
5426 TestZipStreamRead();
5427 TestZipFileSystem();
5432 TestZlibStreamWrite();
5433 TestZlibStreamRead();