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)?
45 //#define TEST_CHARSET
46 //#define TEST_CMDLINE
47 //#define TEST_DATETIME
49 //#define TEST_DLLLOADER
50 //#define TEST_ENVIRON
51 //#define TEST_EXECUTE
53 //#define TEST_FILECONF
54 //#define TEST_FILENAME
57 //#define TEST_INFO_FUNCTIONS
61 //#define TEST_LONGLONG
63 //#define TEST_PATHLIST
64 //#define TEST_REGCONF
66 //#define TEST_REGISTRY
67 //#define TEST_SNGLINST
68 //#define TEST_SOCKETS
69 //#define TEST_STREAMS
70 //#define TEST_STRINGS
71 //#define TEST_THREADS
73 //#define TEST_VCARD -- don't enable this (VZ)
79 #include <wx/snglinst.h>
80 #endif // TEST_SNGLINST
82 // ----------------------------------------------------------------------------
83 // test class for container objects
84 // ----------------------------------------------------------------------------
86 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
88 class Bar
// Foo is already taken in the hash test
91 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
94 static size_t GetNumber() { return ms_bars
; }
96 const char *GetName() const { return m_name
; }
101 static size_t ms_bars
;
104 size_t Bar::ms_bars
= 0;
106 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
108 // ============================================================================
110 // ============================================================================
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
118 // replace TABs with \t and CRs with \n
119 static wxString
MakePrintable(const wxChar
*s
)
122 (void)str
.Replace(_T("\t"), _T("\\t"));
123 (void)str
.Replace(_T("\n"), _T("\\n"));
124 (void)str
.Replace(_T("\r"), _T("\\r"));
129 #endif // MakePrintable() is used
131 // ----------------------------------------------------------------------------
132 // wxFontMapper::CharsetToEncoding
133 // ----------------------------------------------------------------------------
137 #include <wx/fontmap.h>
139 static void TestCharset()
141 static const wxChar
*charsets
[] =
143 // some vali charsets
152 // and now some bogus ones
159 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
161 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
162 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
164 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
165 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
169 #endif // TEST_CHARSET
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
177 #include <wx/cmdline.h>
178 #include <wx/datetime.h>
180 static void ShowCmdLine(const wxCmdLineParser
& parser
)
182 wxString s
= "Input files: ";
184 size_t count
= parser
.GetParamCount();
185 for ( size_t param
= 0; param
< count
; param
++ )
187 s
<< parser
.GetParam(param
) << ' ';
191 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
192 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
197 if ( parser
.Found("o", &strVal
) )
198 s
<< "Output file:\t" << strVal
<< '\n';
199 if ( parser
.Found("i", &strVal
) )
200 s
<< "Input dir:\t" << strVal
<< '\n';
201 if ( parser
.Found("s", &lVal
) )
202 s
<< "Size:\t" << lVal
<< '\n';
203 if ( parser
.Found("d", &dt
) )
204 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
205 if ( parser
.Found("project_name", &strVal
) )
206 s
<< "Project:\t" << strVal
<< '\n';
211 #endif // TEST_CMDLINE
213 // ----------------------------------------------------------------------------
215 // ----------------------------------------------------------------------------
222 static const wxChar
*ROOTDIR
= _T("/");
223 static const wxChar
*TESTDIR
= _T("/usr");
224 #elif defined(__WXMSW__)
225 static const wxChar
*ROOTDIR
= _T("c:\\");
226 static const wxChar
*TESTDIR
= _T("d:\\");
228 #error "don't know where the root directory is"
231 static void TestDirEnumHelper(wxDir
& dir
,
232 int flags
= wxDIR_DEFAULT
,
233 const wxString
& filespec
= wxEmptyString
)
237 if ( !dir
.IsOpened() )
240 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
243 printf("\t%s\n", filename
.c_str());
245 cont
= dir
.GetNext(&filename
);
251 static void TestDirEnum()
253 puts("*** Testing wxDir::GetFirst/GetNext ***");
255 wxDir
dir(wxGetCwd());
257 puts("Enumerating everything in current directory:");
258 TestDirEnumHelper(dir
);
260 puts("Enumerating really everything in current directory:");
261 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
263 puts("Enumerating object files in current directory:");
264 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
266 puts("Enumerating directories in current directory:");
267 TestDirEnumHelper(dir
, wxDIR_DIRS
);
269 puts("Enumerating files in current directory:");
270 TestDirEnumHelper(dir
, wxDIR_FILES
);
272 puts("Enumerating files including hidden in current directory:");
273 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
277 puts("Enumerating everything in root directory:");
278 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
280 puts("Enumerating directories in root directory:");
281 TestDirEnumHelper(dir
, wxDIR_DIRS
);
283 puts("Enumerating files in root directory:");
284 TestDirEnumHelper(dir
, wxDIR_FILES
);
286 puts("Enumerating files including hidden in root directory:");
287 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
289 puts("Enumerating files in non existing directory:");
290 wxDir
dirNo("nosuchdir");
291 TestDirEnumHelper(dirNo
);
294 class DirPrintTraverser
: public wxDirTraverser
297 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
299 return wxDIR_CONTINUE
;
302 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
304 wxString path
, name
, ext
;
305 wxSplitPath(dirname
, &path
, &name
, &ext
);
308 name
<< _T('.') << ext
;
311 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
313 if ( wxIsPathSeparator(*p
) )
317 printf("%s%s\n", indent
.c_str(), name
.c_str());
319 return wxDIR_CONTINUE
;
323 static void TestDirTraverse()
325 puts("*** Testing wxDir::Traverse() ***");
329 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
330 printf("There are %u files under '%s'\n", n
, TESTDIR
);
333 printf("First one is '%s'\n", files
[0u].c_str());
334 printf(" last one is '%s'\n", files
[n
- 1].c_str());
337 // enum again with custom traverser
339 DirPrintTraverser traverser
;
340 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
345 // ----------------------------------------------------------------------------
347 // ----------------------------------------------------------------------------
349 #ifdef TEST_DLLLOADER
351 #include <wx/dynlib.h>
353 static void TestDllLoad()
355 #if defined(__WXMSW__)
356 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
357 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
358 #elif defined(__UNIX__)
359 // weird: using just libc.so does *not* work!
360 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
361 static const wxChar
*FUNC_NAME
= _T("strlen");
363 #error "don't know how to test wxDllLoader on this platform"
366 puts("*** testing wxDllLoader ***\n");
368 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
371 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
375 typedef int (*strlenType
)(char *);
376 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
379 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
380 FUNC_NAME
, LIB_NAME
);
384 if ( pfnStrlen("foo") != 3 )
386 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
394 wxDllLoader::UnloadLibrary(dllHandle
);
398 #endif // TEST_DLLLOADER
400 // ----------------------------------------------------------------------------
402 // ----------------------------------------------------------------------------
406 #include <wx/utils.h>
408 static wxString
MyGetEnv(const wxString
& var
)
411 if ( !wxGetEnv(var
, &val
) )
414 val
= wxString(_T('\'')) + val
+ _T('\'');
419 static void TestEnvironment()
421 const wxChar
*var
= _T("wxTestVar");
423 puts("*** testing environment access functions ***");
425 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
426 wxSetEnv(var
, _T("value for wxTestVar"));
427 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
428 wxSetEnv(var
, _T("another value"));
429 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
431 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
432 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
435 #endif // TEST_ENVIRON
437 // ----------------------------------------------------------------------------
439 // ----------------------------------------------------------------------------
443 #include <wx/utils.h>
445 static void TestExecute()
447 puts("*** testing wxExecute ***");
450 #define COMMAND "cat -n ../../Makefile" // "echo hi"
451 #define SHELL_COMMAND "echo hi from shell"
452 #define REDIRECT_COMMAND COMMAND // "date"
453 #elif defined(__WXMSW__)
454 #define COMMAND "command.com -c 'echo hi'"
455 #define SHELL_COMMAND "echo hi"
456 #define REDIRECT_COMMAND COMMAND
458 #error "no command to exec"
461 printf("Testing wxShell: ");
463 if ( wxShell(SHELL_COMMAND
) )
468 printf("Testing wxExecute: ");
470 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
475 #if 0 // no, it doesn't work (yet?)
476 printf("Testing async wxExecute: ");
478 if ( wxExecute(COMMAND
) != 0 )
479 puts("Ok (command launched).");
484 printf("Testing wxExecute with redirection:\n");
485 wxArrayString output
;
486 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
492 size_t count
= output
.GetCount();
493 for ( size_t n
= 0; n
< count
; n
++ )
495 printf("\t%s\n", output
[n
].c_str());
502 #endif // TEST_EXECUTE
504 // ----------------------------------------------------------------------------
506 // ----------------------------------------------------------------------------
511 #include <wx/ffile.h>
512 #include <wx/textfile.h>
514 static void TestFileRead()
516 puts("*** wxFile read test ***");
518 wxFile
file(_T("testdata.fc"));
519 if ( file
.IsOpened() )
521 printf("File length: %lu\n", file
.Length());
523 puts("File dump:\n----------");
525 static const off_t len
= 1024;
529 off_t nRead
= file
.Read(buf
, len
);
530 if ( nRead
== wxInvalidOffset
)
532 printf("Failed to read the file.");
536 fwrite(buf
, nRead
, 1, stdout
);
546 printf("ERROR: can't open test file.\n");
552 static void TestTextFileRead()
554 puts("*** wxTextFile read test ***");
556 wxTextFile
file(_T("testdata.fc"));
559 printf("Number of lines: %u\n", file
.GetLineCount());
560 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
564 puts("\nDumping the entire file:");
565 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
567 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
569 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
571 puts("\nAnd now backwards:");
572 for ( s
= file
.GetLastLine();
573 file
.GetCurrentLine() != 0;
574 s
= file
.GetPrevLine() )
576 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
578 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
582 printf("ERROR: can't open '%s'\n", file
.GetName());
588 static void TestFileCopy()
590 puts("*** Testing wxCopyFile ***");
592 static const wxChar
*filename1
= _T("testdata.fc");
593 static const wxChar
*filename2
= _T("test2");
594 if ( !wxCopyFile(filename1
, filename2
) )
596 puts("ERROR: failed to copy file");
600 wxFFile
f1(filename1
, "rb"),
603 if ( !f1
.IsOpened() || !f2
.IsOpened() )
605 puts("ERROR: failed to open file(s)");
610 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
612 puts("ERROR: failed to read file(s)");
616 if ( (s1
.length() != s2
.length()) ||
617 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
619 puts("ERROR: copy error!");
623 puts("File was copied ok.");
629 if ( !wxRemoveFile(filename2
) )
631 puts("ERROR: failed to remove the file");
639 // ----------------------------------------------------------------------------
641 // ----------------------------------------------------------------------------
645 #include <wx/confbase.h>
646 #include <wx/fileconf.h>
648 static const struct FileConfTestData
650 const wxChar
*name
; // value name
651 const wxChar
*value
; // the value from the file
654 { _T("value1"), _T("one") },
655 { _T("value2"), _T("two") },
656 { _T("novalue"), _T("default") },
659 static void TestFileConfRead()
661 puts("*** testing wxFileConfig loading/reading ***");
663 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
664 _T("testdata.fc"), wxEmptyString
,
665 wxCONFIG_USE_RELATIVE_PATH
);
667 // test simple reading
668 puts("\nReading config file:");
669 wxString
defValue(_T("default")), value
;
670 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
672 const FileConfTestData
& data
= fcTestData
[n
];
673 value
= fileconf
.Read(data
.name
, defValue
);
674 printf("\t%s = %s ", data
.name
, value
.c_str());
675 if ( value
== data
.value
)
681 printf("(ERROR: should be %s)\n", data
.value
);
685 // test enumerating the entries
686 puts("\nEnumerating all root entries:");
689 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
692 printf("\t%s = %s\n",
694 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
696 cont
= fileconf
.GetNextEntry(name
, dummy
);
700 #endif // TEST_FILECONF
702 // ----------------------------------------------------------------------------
704 // ----------------------------------------------------------------------------
708 #include <wx/filename.h>
710 static struct FileNameInfo
712 const wxChar
*fullname
;
718 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
719 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
720 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
721 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
722 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
723 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
724 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
725 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
728 static void TestFileNameConstruction()
730 puts("*** testing wxFileName construction ***");
732 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
734 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
736 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
737 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
739 puts("ERROR (couldn't be normalized)");
743 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
750 static void TestFileNameSplit()
752 puts("*** testing wxFileName splitting ***");
754 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
756 const FileNameInfo
&fni
= filenames
[n
];
757 wxString path
, name
, ext
;
758 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
760 printf("%s -> path = '%s', name = '%s', ext = '%s'",
761 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
762 if ( path
!= fni
.path
)
763 printf(" (ERROR: path = '%s')", fni
.path
);
764 if ( name
!= fni
.name
)
765 printf(" (ERROR: name = '%s')", fni
.name
);
766 if ( ext
!= fni
.ext
)
767 printf(" (ERROR: ext = '%s')", fni
.ext
);
774 static void TestFileNameComparison()
779 static void TestFileNameOperations()
784 static void TestFileNameCwd()
789 #endif // TEST_FILENAME
791 // ----------------------------------------------------------------------------
793 // ----------------------------------------------------------------------------
801 Foo(int n_
) { n
= n_
; count
++; }
809 size_t Foo::count
= 0;
811 WX_DECLARE_LIST(Foo
, wxListFoos
);
812 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
814 #include <wx/listimpl.cpp>
816 WX_DEFINE_LIST(wxListFoos
);
818 static void TestHash()
820 puts("*** Testing wxHashTable ***\n");
824 hash
.DeleteContents(TRUE
);
826 printf("Hash created: %u foos in hash, %u foos totally\n",
827 hash
.GetCount(), Foo::count
);
829 static const int hashTestData
[] =
831 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
835 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
837 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
840 printf("Hash filled: %u foos in hash, %u foos totally\n",
841 hash
.GetCount(), Foo::count
);
843 puts("Hash access test:");
844 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
846 printf("\tGetting element with key %d, value %d: ",
848 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
851 printf("ERROR, not found.\n");
855 printf("%d (%s)\n", foo
->n
,
856 (size_t)foo
->n
== n
? "ok" : "ERROR");
860 printf("\nTrying to get an element not in hash: ");
862 if ( hash
.Get(1234) || hash
.Get(1, 0) )
864 puts("ERROR: found!");
868 puts("ok (not found)");
872 printf("Hash destroyed: %u foos left\n", Foo::count
);
877 // ----------------------------------------------------------------------------
879 // ----------------------------------------------------------------------------
885 WX_DECLARE_LIST(Bar
, wxListBars
);
886 #include <wx/listimpl.cpp>
887 WX_DEFINE_LIST(wxListBars
);
889 static void TestListCtor()
891 puts("*** Testing wxList construction ***\n");
895 list1
.Append(new Bar(_T("first")));
896 list1
.Append(new Bar(_T("second")));
898 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
899 list1
.GetCount(), Bar::GetNumber());
904 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
905 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
907 list1
.DeleteContents(TRUE
);
910 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
915 // ----------------------------------------------------------------------------
917 // ----------------------------------------------------------------------------
922 #include "wx/utils.h" // for wxSetEnv
924 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
926 // find the name of the language from its value
927 static const char *GetLangName(int lang
)
929 static const char *languageNames
[] =
950 "ARABIC_SAUDI_ARABIA",
975 "CHINESE_SIMPLIFIED",
976 "CHINESE_TRADITIONAL",
998 "ENGLISH_NEW_ZEALAND",
999 "ENGLISH_PHILIPPINES",
1000 "ENGLISH_SOUTH_AFRICA",
1012 "FRENCH_LUXEMBOURG",
1021 "GERMAN_LIECHTENSTEIN",
1022 "GERMAN_LUXEMBOURG",
1063 "MALAY_BRUNEI_DARUSSALAM",
1075 "NORWEGIAN_NYNORSK",
1082 "PORTUGUESE_BRAZILIAN",
1107 "SPANISH_ARGENTINA",
1111 "SPANISH_COSTA_RICA",
1112 "SPANISH_DOMINICAN_REPUBLIC",
1114 "SPANISH_EL_SALVADOR",
1115 "SPANISH_GUATEMALA",
1119 "SPANISH_NICARAGUA",
1123 "SPANISH_PUERTO_RICO",
1126 "SPANISH_VENEZUELA",
1163 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1164 return languageNames
[lang
];
1169 static void TestDefaultLang()
1171 puts("*** Testing wxLocale::GetSystemLanguage ***");
1173 static const wxChar
*langStrings
[] =
1175 NULL
, // system default
1182 _T("de_DE.iso88591"),
1184 _T("?"), // invalid lang spec
1185 _T("klingonese"), // I bet on some systems it does exist...
1188 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1189 wxLocale::GetSystemEncodingName().c_str(),
1190 wxLocale::GetSystemEncoding());
1192 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1194 const char *langStr
= langStrings
[n
];
1197 // FIXME: this doesn't do anything at all under Windows, we need
1198 // to create a new wxLocale!
1199 wxSetEnv(_T("LC_ALL"), langStr
);
1202 int lang
= gs_localeDefault
.GetSystemLanguage();
1203 printf("Locale for '%s' is %s.\n",
1204 langStr
? langStr
: "system default", GetLangName(lang
));
1208 #endif // TEST_LOCALE
1210 // ----------------------------------------------------------------------------
1212 // ----------------------------------------------------------------------------
1216 #include <wx/mimetype.h>
1218 static void TestMimeEnum()
1220 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1222 wxArrayString mimetypes
;
1224 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1226 printf("*** All %u known filetypes: ***\n", count
);
1231 for ( size_t n
= 0; n
< count
; n
++ )
1233 wxFileType
*filetype
=
1234 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1237 printf("nothing known about the filetype '%s'!\n",
1238 mimetypes
[n
].c_str());
1242 filetype
->GetDescription(&desc
);
1243 filetype
->GetExtensions(exts
);
1245 filetype
->GetIcon(NULL
);
1248 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1251 extsAll
<< _T(", ");
1255 printf("\t%s: %s (%s)\n",
1256 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1262 static void TestMimeOverride()
1264 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1266 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1267 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1269 if ( wxFile::Exists(mailcap
) )
1270 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1272 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1274 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1277 if ( wxFile::Exists(mimetypes
) )
1278 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1280 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1282 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1288 static void TestMimeFilename()
1290 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1292 static const wxChar
*filenames
[] =
1299 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1301 const wxString fname
= filenames
[n
];
1302 wxString ext
= fname
.AfterLast(_T('.'));
1303 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1306 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1311 if ( !ft
->GetDescription(&desc
) )
1312 desc
= _T("<no description>");
1315 if ( !ft
->GetOpenCommand(&cmd
,
1316 wxFileType::MessageParameters(fname
, _T(""))) )
1317 cmd
= _T("<no command available>");
1319 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1320 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1329 static void TestMimeAssociate()
1331 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1333 wxFileTypeInfo
ftInfo(
1334 _T("application/x-xyz"),
1335 _T("xyzview '%s'"), // open cmd
1336 _T(""), // print cmd
1337 _T("XYZ File") // description
1338 _T(".xyz"), // extensions
1339 NULL
// end of extensions
1341 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1343 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1346 wxPuts(_T("ERROR: failed to create association!"));
1350 // TODO: read it back
1359 // ----------------------------------------------------------------------------
1360 // misc information functions
1361 // ----------------------------------------------------------------------------
1363 #ifdef TEST_INFO_FUNCTIONS
1365 #include <wx/utils.h>
1367 static void TestOsInfo()
1369 puts("*** Testing OS info functions ***\n");
1372 wxGetOsVersion(&major
, &minor
);
1373 printf("Running under: %s, version %d.%d\n",
1374 wxGetOsDescription().c_str(), major
, minor
);
1376 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1378 printf("Host name is %s (%s).\n",
1379 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1384 static void TestUserInfo()
1386 puts("*** Testing user info functions ***\n");
1388 printf("User id is:\t%s\n", wxGetUserId().c_str());
1389 printf("User name is:\t%s\n", wxGetUserName().c_str());
1390 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1391 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1396 #endif // TEST_INFO_FUNCTIONS
1398 // ----------------------------------------------------------------------------
1400 // ----------------------------------------------------------------------------
1402 #ifdef TEST_LONGLONG
1404 #include <wx/longlong.h>
1405 #include <wx/timer.h>
1407 // make a 64 bit number from 4 16 bit ones
1408 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1410 // get a random 64 bit number
1411 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1413 #if wxUSE_LONGLONG_WX
1414 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1415 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1416 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1417 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1418 #endif // wxUSE_LONGLONG_WX
1420 static void TestSpeed()
1422 static const long max
= 100000000;
1429 for ( n
= 0; n
< max
; n
++ )
1434 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1437 #if wxUSE_LONGLONG_NATIVE
1442 for ( n
= 0; n
< max
; n
++ )
1447 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1449 #endif // wxUSE_LONGLONG_NATIVE
1455 for ( n
= 0; n
< max
; n
++ )
1460 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1464 static void TestLongLongConversion()
1466 puts("*** Testing wxLongLong conversions ***\n");
1470 for ( size_t n
= 0; n
< 100000; n
++ )
1474 #if wxUSE_LONGLONG_NATIVE
1475 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1477 wxASSERT_MSG( a
== b
, "conversions failure" );
1479 puts("Can't do it without native long long type, test skipped.");
1482 #endif // wxUSE_LONGLONG_NATIVE
1484 if ( !(nTested
% 1000) )
1496 static void TestMultiplication()
1498 puts("*** Testing wxLongLong multiplication ***\n");
1502 for ( size_t n
= 0; n
< 100000; n
++ )
1507 #if wxUSE_LONGLONG_NATIVE
1508 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1509 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1511 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1512 #else // !wxUSE_LONGLONG_NATIVE
1513 puts("Can't do it without native long long type, test skipped.");
1516 #endif // wxUSE_LONGLONG_NATIVE
1518 if ( !(nTested
% 1000) )
1530 static void TestDivision()
1532 puts("*** Testing wxLongLong division ***\n");
1536 for ( size_t n
= 0; n
< 100000; n
++ )
1538 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1539 // multiplication will not overflow)
1540 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1542 // get a random long (not wxLongLong for now) to divide it with
1547 #if wxUSE_LONGLONG_NATIVE
1548 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1550 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1551 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1552 #else // !wxUSE_LONGLONG_NATIVE
1553 // verify the result
1554 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1555 #endif // wxUSE_LONGLONG_NATIVE
1557 if ( !(nTested
% 1000) )
1569 static void TestAddition()
1571 puts("*** Testing wxLongLong addition ***\n");
1575 for ( size_t n
= 0; n
< 100000; n
++ )
1581 #if wxUSE_LONGLONG_NATIVE
1582 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1583 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1584 "addition failure" );
1585 #else // !wxUSE_LONGLONG_NATIVE
1586 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1587 #endif // wxUSE_LONGLONG_NATIVE
1589 if ( !(nTested
% 1000) )
1601 static void TestBitOperations()
1603 puts("*** Testing wxLongLong bit operation ***\n");
1607 for ( size_t n
= 0; n
< 100000; n
++ )
1611 #if wxUSE_LONGLONG_NATIVE
1612 for ( size_t n
= 0; n
< 33; n
++ )
1615 #else // !wxUSE_LONGLONG_NATIVE
1616 puts("Can't do it without native long long type, test skipped.");
1619 #endif // wxUSE_LONGLONG_NATIVE
1621 if ( !(nTested
% 1000) )
1633 static void TestLongLongComparison()
1635 #if wxUSE_LONGLONG_WX
1636 puts("*** Testing wxLongLong comparison ***\n");
1638 static const long testLongs
[] =
1649 static const long ls
[2] =
1655 wxLongLongWx lls
[2];
1659 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1663 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1665 res
= lls
[m
] > testLongs
[n
];
1666 printf("0x%lx > 0x%lx is %s (%s)\n",
1667 ls
[m
], testLongs
[n
], res
? "true" : "false",
1668 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1670 res
= lls
[m
] < testLongs
[n
];
1671 printf("0x%lx < 0x%lx is %s (%s)\n",
1672 ls
[m
], testLongs
[n
], res
? "true" : "false",
1673 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1675 res
= lls
[m
] == testLongs
[n
];
1676 printf("0x%lx == 0x%lx is %s (%s)\n",
1677 ls
[m
], testLongs
[n
], res
? "true" : "false",
1678 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1681 #endif // wxUSE_LONGLONG_WX
1687 #endif // TEST_LONGLONG
1689 // ----------------------------------------------------------------------------
1691 // ----------------------------------------------------------------------------
1693 #ifdef TEST_PATHLIST
1695 static void TestPathList()
1697 puts("*** Testing wxPathList ***\n");
1699 wxPathList pathlist
;
1700 pathlist
.AddEnvList("PATH");
1701 wxString path
= pathlist
.FindValidPath("ls");
1704 printf("ERROR: command not found in the path.\n");
1708 printf("Command found in the path as '%s'.\n", path
.c_str());
1712 #endif // TEST_PATHLIST
1714 // ----------------------------------------------------------------------------
1715 // regular expressions
1716 // ----------------------------------------------------------------------------
1720 #include <wx/regex.h>
1722 static void TestRegExCompile()
1724 wxPuts(_T("*** Testing RE compilation ***\n"));
1726 static struct RegExCompTestData
1728 const wxChar
*pattern
;
1730 } regExCompTestData
[] =
1732 { _T("foo"), TRUE
},
1733 { _T("foo("), FALSE
},
1734 { _T("foo(bar"), FALSE
},
1735 { _T("foo(bar)"), TRUE
},
1736 { _T("foo["), FALSE
},
1737 { _T("foo[bar"), FALSE
},
1738 { _T("foo[bar]"), TRUE
},
1739 { _T("foo{"), TRUE
},
1740 { _T("foo{1"), FALSE
},
1741 { _T("foo{bar"), TRUE
},
1742 { _T("foo{1}"), TRUE
},
1743 { _T("foo{1,2}"), TRUE
},
1744 { _T("foo{bar}"), TRUE
},
1745 { _T("foo*"), TRUE
},
1746 { _T("foo**"), FALSE
},
1747 { _T("foo+"), TRUE
},
1748 { _T("foo++"), FALSE
},
1749 { _T("foo?"), TRUE
},
1750 { _T("foo??"), FALSE
},
1751 { _T("foo?+"), FALSE
},
1755 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1757 const RegExCompTestData
& data
= regExCompTestData
[n
];
1758 bool ok
= re
.Compile(data
.pattern
);
1760 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1762 ok
? _T("") : _T("not "),
1763 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1767 static void TestRegExMatch()
1769 wxPuts(_T("*** Testing RE matching ***\n"));
1771 static struct RegExMatchTestData
1773 const wxChar
*pattern
;
1776 } regExMatchTestData
[] =
1778 { _T("foo"), _T("bar"), FALSE
},
1779 { _T("foo"), _T("foobar"), TRUE
},
1780 { _T("^foo"), _T("foobar"), TRUE
},
1781 { _T("^foo"), _T("barfoo"), FALSE
},
1782 { _T("bar$"), _T("barbar"), TRUE
},
1783 { _T("bar$"), _T("barbar "), FALSE
},
1786 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1788 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1790 wxRegEx
re(data
.pattern
);
1791 bool ok
= re
.Matches(data
.text
);
1793 wxPrintf(_T("'%s' %s %s (%s)\n"),
1795 ok
? _T("matches") : _T("doesn't match"),
1797 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1801 static void TestRegExSubmatch()
1803 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1805 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1806 if ( !re
.IsValid() )
1808 wxPuts(_T("ERROR: compilation failed."));
1812 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
1814 if ( !re
.Matches(text
) )
1816 wxPuts(_T("ERROR: match expected."));
1820 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
1822 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1823 re
.GetMatch(text
, 3).c_str(),
1824 re
.GetMatch(text
, 2).c_str(),
1825 re
.GetMatch(text
, 4).c_str(),
1826 re
.GetMatch(text
, 1).c_str());
1830 static void TestRegExInteractive()
1832 wxPuts(_T("*** Testing RE interactively ***"));
1837 printf("\nEnter a pattern: ");
1838 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1841 // kill the last '\n'
1842 pattern
[strlen(pattern
) - 1] = 0;
1845 if ( !re
.Compile(pattern
) )
1853 printf("Enter text to match: ");
1854 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
1857 // kill the last '\n'
1858 text
[strlen(text
) - 1] = 0;
1860 if ( !re
.Matches(text
) )
1862 printf("No match.\n");
1866 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
1869 for ( size_t n
= 1; ; n
++ )
1871 if ( !re
.GetMatch(&start
, &len
, n
) )
1876 printf("Subexpr %u matched '%s'\n",
1877 n
, wxString(text
+ start
, len
).c_str());
1884 #endif // TEST_REGEX
1886 // ----------------------------------------------------------------------------
1887 // registry and related stuff
1888 // ----------------------------------------------------------------------------
1890 // this is for MSW only
1893 #undef TEST_REGISTRY
1898 #include <wx/confbase.h>
1899 #include <wx/msw/regconf.h>
1901 static void TestRegConfWrite()
1903 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1904 regconf
.Write(_T("Hello"), wxString(_T("world")));
1907 #endif // TEST_REGCONF
1909 #ifdef TEST_REGISTRY
1911 #include <wx/msw/registry.h>
1913 // I chose this one because I liked its name, but it probably only exists under
1915 static const wxChar
*TESTKEY
=
1916 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1918 static void TestRegistryRead()
1920 puts("*** testing registry reading ***");
1922 wxRegKey
key(TESTKEY
);
1923 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1926 puts("ERROR: test key can't be opened, aborting test.");
1931 size_t nSubKeys
, nValues
;
1932 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1934 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1937 printf("Enumerating values:\n");
1941 bool cont
= key
.GetFirstValue(value
, dummy
);
1944 printf("Value '%s': type ", value
.c_str());
1945 switch ( key
.GetValueType(value
) )
1947 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1948 case wxRegKey::Type_String
: printf("SZ"); break;
1949 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1950 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1951 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1952 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1953 default: printf("other (unknown)"); break;
1956 printf(", value = ");
1957 if ( key
.IsNumericValue(value
) )
1960 key
.QueryValue(value
, &val
);
1966 key
.QueryValue(value
, val
);
1967 printf("'%s'", val
.c_str());
1969 key
.QueryRawValue(value
, val
);
1970 printf(" (raw value '%s')", val
.c_str());
1975 cont
= key
.GetNextValue(value
, dummy
);
1979 static void TestRegistryAssociation()
1982 The second call to deleteself genertaes an error message, with a
1983 messagebox saying .flo is crucial to system operation, while the .ddf
1984 call also fails, but with no error message
1989 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1991 key
= "ddxf_auto_file" ;
1992 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1994 key
= "ddxf_auto_file" ;
1995 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1998 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2000 key
= "program \"%1\"" ;
2002 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2004 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2006 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2008 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2012 #endif // TEST_REGISTRY
2014 // ----------------------------------------------------------------------------
2016 // ----------------------------------------------------------------------------
2020 #include <wx/socket.h>
2021 #include <wx/protocol/protocol.h>
2022 #include <wx/protocol/http.h>
2024 static void TestSocketServer()
2026 puts("*** Testing wxSocketServer ***\n");
2028 static const int PORT
= 3000;
2033 wxSocketServer
*server
= new wxSocketServer(addr
);
2034 if ( !server
->Ok() )
2036 puts("ERROR: failed to bind");
2043 printf("Server: waiting for connection on port %d...\n", PORT
);
2045 wxSocketBase
*socket
= server
->Accept();
2048 puts("ERROR: wxSocketServer::Accept() failed.");
2052 puts("Server: got a client.");
2054 server
->SetTimeout(60); // 1 min
2056 while ( socket
->IsConnected() )
2062 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2064 // don't log error if the client just close the connection
2065 if ( socket
->IsConnected() )
2067 puts("ERROR: in wxSocket::Read.");
2087 printf("Server: got '%s'.\n", s
.c_str());
2088 if ( s
== _T("bye") )
2095 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2096 socket
->Write("\r\n", 2);
2097 printf("Server: wrote '%s'.\n", s
.c_str());
2100 puts("Server: lost a client.");
2105 // same as "delete server" but is consistent with GUI programs
2109 static void TestSocketClient()
2111 puts("*** Testing wxSocketClient ***\n");
2113 static const char *hostname
= "www.wxwindows.org";
2116 addr
.Hostname(hostname
);
2119 printf("--- Attempting to connect to %s:80...\n", hostname
);
2121 wxSocketClient client
;
2122 if ( !client
.Connect(addr
) )
2124 printf("ERROR: failed to connect to %s\n", hostname
);
2128 printf("--- Connected to %s:%u...\n",
2129 addr
.Hostname().c_str(), addr
.Service());
2133 // could use simply "GET" here I suppose
2135 wxString::Format("GET http://%s/\r\n", hostname
);
2136 client
.Write(cmdGet
, cmdGet
.length());
2137 printf("--- Sent command '%s' to the server\n",
2138 MakePrintable(cmdGet
).c_str());
2139 client
.Read(buf
, WXSIZEOF(buf
));
2140 printf("--- Server replied:\n%s", buf
);
2144 #endif // TEST_SOCKETS
2146 // ----------------------------------------------------------------------------
2148 // ----------------------------------------------------------------------------
2152 #include <wx/protocol/ftp.h>
2156 #define FTP_ANONYMOUS
2158 #ifdef FTP_ANONYMOUS
2159 static const char *directory
= "/pub";
2160 static const char *filename
= "welcome.msg";
2162 static const char *directory
= "/etc";
2163 static const char *filename
= "issue";
2166 static bool TestFtpConnect()
2168 puts("*** Testing FTP connect ***");
2170 #ifdef FTP_ANONYMOUS
2171 static const char *hostname
= "ftp.wxwindows.org";
2173 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2174 #else // !FTP_ANONYMOUS
2175 static const char *hostname
= "localhost";
2178 fgets(user
, WXSIZEOF(user
), stdin
);
2179 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2183 printf("Password for %s: ", password
);
2184 fgets(password
, WXSIZEOF(password
), stdin
);
2185 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2186 ftp
.SetPassword(password
);
2188 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2189 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2191 if ( !ftp
.Connect(hostname
) )
2193 printf("ERROR: failed to connect to %s\n", hostname
);
2199 printf("--- Connected to %s, current directory is '%s'\n",
2200 hostname
, ftp
.Pwd().c_str());
2206 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2207 static void TestFtpWuFtpd()
2210 static const char *hostname
= "ftp.eudora.com";
2211 if ( !ftp
.Connect(hostname
) )
2213 printf("ERROR: failed to connect to %s\n", hostname
);
2217 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2218 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2221 printf("ERROR: couldn't get input stream for %s\n", filename
);
2225 size_t size
= in
->StreamSize();
2226 printf("Reading file %s (%u bytes)...", filename
, size
);
2228 char *data
= new char[size
];
2229 if ( !in
->Read(data
, size
) )
2231 puts("ERROR: read error");
2235 printf("Successfully retrieved the file.\n");
2244 static void TestFtpList()
2246 puts("*** Testing wxFTP file listing ***\n");
2249 if ( !ftp
.ChDir(directory
) )
2251 printf("ERROR: failed to cd to %s\n", directory
);
2254 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2256 // test NLIST and LIST
2257 wxArrayString files
;
2258 if ( !ftp
.GetFilesList(files
) )
2260 puts("ERROR: failed to get NLIST of files");
2264 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2265 size_t count
= files
.GetCount();
2266 for ( size_t n
= 0; n
< count
; n
++ )
2268 printf("\t%s\n", files
[n
].c_str());
2270 puts("End of the file list");
2273 if ( !ftp
.GetDirList(files
) )
2275 puts("ERROR: failed to get LIST of files");
2279 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2280 size_t count
= files
.GetCount();
2281 for ( size_t n
= 0; n
< count
; n
++ )
2283 printf("\t%s\n", files
[n
].c_str());
2285 puts("End of the file list");
2288 if ( !ftp
.ChDir(_T("..")) )
2290 puts("ERROR: failed to cd to ..");
2293 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2296 static void TestFtpDownload()
2298 puts("*** Testing wxFTP download ***\n");
2301 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2304 printf("ERROR: couldn't get input stream for %s\n", filename
);
2308 size_t size
= in
->StreamSize();
2309 printf("Reading file %s (%u bytes)...", filename
, size
);
2312 char *data
= new char[size
];
2313 if ( !in
->Read(data
, size
) )
2315 puts("ERROR: read error");
2319 printf("\nContents of %s:\n%s\n", filename
, data
);
2327 static void TestFtpFileSize()
2329 puts("*** Testing FTP SIZE command ***");
2331 if ( !ftp
.ChDir(directory
) )
2333 printf("ERROR: failed to cd to %s\n", directory
);
2336 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2338 if ( ftp
.FileExists(filename
) )
2340 int size
= ftp
.GetFileSize(filename
);
2342 printf("ERROR: couldn't get size of '%s'\n", filename
);
2344 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2348 printf("ERROR: '%s' doesn't exist\n", filename
);
2352 static void TestFtpMisc()
2354 puts("*** Testing miscellaneous wxFTP functions ***");
2356 if ( ftp
.SendCommand("STAT") != '2' )
2358 puts("ERROR: STAT failed");
2362 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2365 if ( ftp
.SendCommand("HELP SITE") != '2' )
2367 puts("ERROR: HELP SITE failed");
2371 printf("The list of site-specific commands:\n\n%s\n",
2372 ftp
.GetLastResult().c_str());
2376 static void TestFtpInteractive()
2378 puts("\n*** Interactive wxFTP test ***");
2384 printf("Enter FTP command: ");
2385 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2388 // kill the last '\n'
2389 buf
[strlen(buf
) - 1] = 0;
2391 // special handling of LIST and NLST as they require data connection
2392 wxString
start(buf
, 4);
2394 if ( start
== "LIST" || start
== "NLST" )
2397 if ( strlen(buf
) > 4 )
2400 wxArrayString files
;
2401 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2403 printf("ERROR: failed to get %s of files\n", start
.c_str());
2407 printf("--- %s of '%s' under '%s':\n",
2408 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2409 size_t count
= files
.GetCount();
2410 for ( size_t n
= 0; n
< count
; n
++ )
2412 printf("\t%s\n", files
[n
].c_str());
2414 puts("--- End of the file list");
2419 char ch
= ftp
.SendCommand(buf
);
2420 printf("Command %s", ch
? "succeeded" : "failed");
2423 printf(" (return code %c)", ch
);
2426 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2430 puts("\n*** done ***");
2433 static void TestFtpUpload()
2435 puts("*** Testing wxFTP uploading ***\n");
2438 static const char *file1
= "test1";
2439 static const char *file2
= "test2";
2440 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2443 printf("--- Uploading to %s ---\n", file1
);
2444 out
->Write("First hello", 11);
2448 // send a command to check the remote file
2449 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2451 printf("ERROR: STAT %s failed\n", file1
);
2455 printf("STAT %s returned:\n\n%s\n",
2456 file1
, ftp
.GetLastResult().c_str());
2459 out
= ftp
.GetOutputStream(file2
);
2462 printf("--- Uploading to %s ---\n", file1
);
2463 out
->Write("Second hello", 12);
2470 // ----------------------------------------------------------------------------
2472 // ----------------------------------------------------------------------------
2476 #include <wx/wfstream.h>
2477 #include <wx/mstream.h>
2479 static void TestFileStream()
2481 puts("*** Testing wxFileInputStream ***");
2483 static const wxChar
*filename
= _T("testdata.fs");
2485 wxFileOutputStream
fsOut(filename
);
2486 fsOut
.Write("foo", 3);
2489 wxFileInputStream
fsIn(filename
);
2490 printf("File stream size: %u\n", fsIn
.GetSize());
2491 while ( !fsIn
.Eof() )
2493 putchar(fsIn
.GetC());
2496 if ( !wxRemoveFile(filename
) )
2498 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2501 puts("\n*** wxFileInputStream test done ***");
2504 static void TestMemoryStream()
2506 puts("*** Testing wxMemoryInputStream ***");
2509 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2511 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2512 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2513 while ( !memInpStream
.Eof() )
2515 putchar(memInpStream
.GetC());
2518 puts("\n*** wxMemoryInputStream test done ***");
2521 #endif // TEST_STREAMS
2523 // ----------------------------------------------------------------------------
2525 // ----------------------------------------------------------------------------
2529 #include <wx/timer.h>
2530 #include <wx/utils.h>
2532 static void TestStopWatch()
2534 puts("*** Testing wxStopWatch ***\n");
2537 printf("Sleeping 3 seconds...");
2539 printf("\telapsed time: %ldms\n", sw
.Time());
2542 printf("Sleeping 2 more seconds...");
2544 printf("\telapsed time: %ldms\n", sw
.Time());
2547 printf("And 3 more seconds...");
2549 printf("\telapsed time: %ldms\n", sw
.Time());
2552 puts("\nChecking for 'backwards clock' bug...");
2553 for ( size_t n
= 0; n
< 70; n
++ )
2557 for ( size_t m
= 0; m
< 100000; m
++ )
2559 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2561 puts("\ntime is negative - ERROR!");
2571 #endif // TEST_TIMER
2573 // ----------------------------------------------------------------------------
2575 // ----------------------------------------------------------------------------
2579 #include <wx/vcard.h>
2581 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2584 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2588 wxString(_T('\t'), level
).c_str(),
2589 vcObj
->GetName().c_str());
2592 switch ( vcObj
->GetType() )
2594 case wxVCardObject::String
:
2595 case wxVCardObject::UString
:
2598 vcObj
->GetValue(&val
);
2599 value
<< _T('"') << val
<< _T('"');
2603 case wxVCardObject::Int
:
2606 vcObj
->GetValue(&i
);
2607 value
.Printf(_T("%u"), i
);
2611 case wxVCardObject::Long
:
2614 vcObj
->GetValue(&l
);
2615 value
.Printf(_T("%lu"), l
);
2619 case wxVCardObject::None
:
2622 case wxVCardObject::Object
:
2623 value
= _T("<node>");
2627 value
= _T("<unknown value type>");
2631 printf(" = %s", value
.c_str());
2634 DumpVObject(level
+ 1, *vcObj
);
2637 vcObj
= vcard
.GetNextProp(&cookie
);
2641 static void DumpVCardAddresses(const wxVCard
& vcard
)
2643 puts("\nShowing all addresses from vCard:\n");
2647 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2651 int flags
= addr
->GetFlags();
2652 if ( flags
& wxVCardAddress::Domestic
)
2654 flagsStr
<< _T("domestic ");
2656 if ( flags
& wxVCardAddress::Intl
)
2658 flagsStr
<< _T("international ");
2660 if ( flags
& wxVCardAddress::Postal
)
2662 flagsStr
<< _T("postal ");
2664 if ( flags
& wxVCardAddress::Parcel
)
2666 flagsStr
<< _T("parcel ");
2668 if ( flags
& wxVCardAddress::Home
)
2670 flagsStr
<< _T("home ");
2672 if ( flags
& wxVCardAddress::Work
)
2674 flagsStr
<< _T("work ");
2677 printf("Address %u:\n"
2679 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2682 addr
->GetPostOffice().c_str(),
2683 addr
->GetExtAddress().c_str(),
2684 addr
->GetStreet().c_str(),
2685 addr
->GetLocality().c_str(),
2686 addr
->GetRegion().c_str(),
2687 addr
->GetPostalCode().c_str(),
2688 addr
->GetCountry().c_str()
2692 addr
= vcard
.GetNextAddress(&cookie
);
2696 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2698 puts("\nShowing all phone numbers from vCard:\n");
2702 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2706 int flags
= phone
->GetFlags();
2707 if ( flags
& wxVCardPhoneNumber::Voice
)
2709 flagsStr
<< _T("voice ");
2711 if ( flags
& wxVCardPhoneNumber::Fax
)
2713 flagsStr
<< _T("fax ");
2715 if ( flags
& wxVCardPhoneNumber::Cellular
)
2717 flagsStr
<< _T("cellular ");
2719 if ( flags
& wxVCardPhoneNumber::Modem
)
2721 flagsStr
<< _T("modem ");
2723 if ( flags
& wxVCardPhoneNumber::Home
)
2725 flagsStr
<< _T("home ");
2727 if ( flags
& wxVCardPhoneNumber::Work
)
2729 flagsStr
<< _T("work ");
2732 printf("Phone number %u:\n"
2737 phone
->GetNumber().c_str()
2741 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2745 static void TestVCardRead()
2747 puts("*** Testing wxVCard reading ***\n");
2749 wxVCard
vcard(_T("vcard.vcf"));
2750 if ( !vcard
.IsOk() )
2752 puts("ERROR: couldn't load vCard.");
2756 // read individual vCard properties
2757 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2761 vcObj
->GetValue(&value
);
2766 value
= _T("<none>");
2769 printf("Full name retrieved directly: %s\n", value
.c_str());
2772 if ( !vcard
.GetFullName(&value
) )
2774 value
= _T("<none>");
2777 printf("Full name from wxVCard API: %s\n", value
.c_str());
2779 // now show how to deal with multiply occuring properties
2780 DumpVCardAddresses(vcard
);
2781 DumpVCardPhoneNumbers(vcard
);
2783 // and finally show all
2784 puts("\nNow dumping the entire vCard:\n"
2785 "-----------------------------\n");
2787 DumpVObject(0, vcard
);
2791 static void TestVCardWrite()
2793 puts("*** Testing wxVCard writing ***\n");
2796 if ( !vcard
.IsOk() )
2798 puts("ERROR: couldn't create vCard.");
2803 vcard
.SetName("Zeitlin", "Vadim");
2804 vcard
.SetFullName("Vadim Zeitlin");
2805 vcard
.SetOrganization("wxWindows", "R&D");
2807 // just dump the vCard back
2808 puts("Entire vCard follows:\n");
2809 puts(vcard
.Write());
2813 #endif // TEST_VCARD
2815 // ----------------------------------------------------------------------------
2816 // wide char (Unicode) support
2817 // ----------------------------------------------------------------------------
2821 #include <wx/strconv.h>
2822 #include <wx/fontenc.h>
2823 #include <wx/encconv.h>
2824 #include <wx/buffer.h>
2826 static void TestUtf8()
2828 puts("*** Testing UTF8 support ***\n");
2830 static const char textInUtf8
[] =
2832 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2833 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2834 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2835 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2836 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2837 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2838 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2843 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2845 puts("ERROR: UTF-8 decoding failed.");
2849 // using wxEncodingConverter
2851 wxEncodingConverter ec
;
2852 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2853 ec
.Convert(wbuf
, buf
);
2854 #else // using wxCSConv
2855 wxCSConv
conv(_T("koi8-r"));
2856 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2858 puts("ERROR: conversion to KOI8-R failed.");
2863 printf("The resulting string (in koi8-r): %s\n", buf
);
2867 #endif // TEST_WCHAR
2869 // ----------------------------------------------------------------------------
2871 // ----------------------------------------------------------------------------
2875 #include "wx/filesys.h"
2876 #include "wx/fs_zip.h"
2877 #include "wx/zipstrm.h"
2879 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2881 static void TestZipStreamRead()
2883 puts("*** Testing ZIP reading ***\n");
2885 static const wxChar
*filename
= _T("foo");
2886 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2887 printf("Archive size: %u\n", istr
.GetSize());
2889 printf("Dumping the file '%s':\n", filename
);
2890 while ( !istr
.Eof() )
2892 putchar(istr
.GetC());
2896 puts("\n----- done ------");
2899 static void DumpZipDirectory(wxFileSystem
& fs
,
2900 const wxString
& dir
,
2901 const wxString
& indent
)
2903 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2904 TESTFILE_ZIP
, dir
.c_str());
2905 wxString wildcard
= prefix
+ _T("/*");
2907 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2908 while ( !dirname
.empty() )
2910 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2912 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2917 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2919 DumpZipDirectory(fs
, dirname
,
2920 indent
+ wxString(_T(' '), 4));
2922 dirname
= fs
.FindNext();
2925 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2926 while ( !filename
.empty() )
2928 if ( !filename
.StartsWith(prefix
, &filename
) )
2930 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2935 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2937 filename
= fs
.FindNext();
2941 static void TestZipFileSystem()
2943 puts("*** Testing ZIP file system ***\n");
2945 wxFileSystem::AddHandler(new wxZipFSHandler
);
2947 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2949 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
2954 // ----------------------------------------------------------------------------
2956 // ----------------------------------------------------------------------------
2960 #include <wx/zstream.h>
2961 #include <wx/wfstream.h>
2963 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2964 static const char *TEST_DATA
= "hello and hello again";
2966 static void TestZlibStreamWrite()
2968 puts("*** Testing Zlib stream reading ***\n");
2970 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2971 wxZlibOutputStream
ostr(fileOutStream
, 0);
2972 printf("Compressing the test string... ");
2973 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2976 puts("(ERROR: failed)");
2983 puts("\n----- done ------");
2986 static void TestZlibStreamRead()
2988 puts("*** Testing Zlib stream reading ***\n");
2990 wxFileInputStream
fileInStream(FILENAME_GZ
);
2991 wxZlibInputStream
istr(fileInStream
);
2992 printf("Archive size: %u\n", istr
.GetSize());
2994 puts("Dumping the file:");
2995 while ( !istr
.Eof() )
2997 putchar(istr
.GetC());
3001 puts("\n----- done ------");
3006 // ----------------------------------------------------------------------------
3008 // ----------------------------------------------------------------------------
3010 #ifdef TEST_DATETIME
3014 #include <wx/date.h>
3016 #include <wx/datetime.h>
3021 wxDateTime::wxDateTime_t day
;
3022 wxDateTime::Month month
;
3024 wxDateTime::wxDateTime_t hour
, min
, sec
;
3026 wxDateTime::WeekDay wday
;
3027 time_t gmticks
, ticks
;
3029 void Init(const wxDateTime::Tm
& tm
)
3038 gmticks
= ticks
= -1;
3041 wxDateTime
DT() const
3042 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3044 bool SameDay(const wxDateTime::Tm
& tm
) const
3046 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3049 wxString
Format() const
3052 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3054 wxDateTime::GetMonthName(month
).c_str(),
3056 abs(wxDateTime::ConvertYearToBC(year
)),
3057 year
> 0 ? "AD" : "BC");
3061 wxString
FormatDate() const
3064 s
.Printf("%02d-%s-%4d%s",
3066 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3067 abs(wxDateTime::ConvertYearToBC(year
)),
3068 year
> 0 ? "AD" : "BC");
3073 static const Date testDates
[] =
3075 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3076 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3077 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3078 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3079 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3080 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3081 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3082 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3083 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3084 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3085 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3086 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3087 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3088 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3089 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3092 // this test miscellaneous static wxDateTime functions
3093 static void TestTimeStatic()
3095 puts("\n*** wxDateTime static methods test ***");
3097 // some info about the current date
3098 int year
= wxDateTime::GetCurrentYear();
3099 printf("Current year %d is %sa leap one and has %d days.\n",
3101 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3102 wxDateTime::GetNumberOfDays(year
));
3104 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3105 printf("Current month is '%s' ('%s') and it has %d days\n",
3106 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3107 wxDateTime::GetMonthName(month
).c_str(),
3108 wxDateTime::GetNumberOfDays(month
));
3111 static const size_t nYears
= 5;
3112 static const size_t years
[2][nYears
] =
3114 // first line: the years to test
3115 { 1990, 1976, 2000, 2030, 1984, },
3117 // second line: TRUE if leap, FALSE otherwise
3118 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3121 for ( size_t n
= 0; n
< nYears
; n
++ )
3123 int year
= years
[0][n
];
3124 bool should
= years
[1][n
] != 0,
3125 is
= wxDateTime::IsLeapYear(year
);
3127 printf("Year %d is %sa leap year (%s)\n",
3130 should
== is
? "ok" : "ERROR");
3132 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3136 // test constructing wxDateTime objects
3137 static void TestTimeSet()
3139 puts("\n*** wxDateTime construction test ***");
3141 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3143 const Date
& d1
= testDates
[n
];
3144 wxDateTime dt
= d1
.DT();
3147 d2
.Init(dt
.GetTm());
3149 wxString s1
= d1
.Format(),
3152 printf("Date: %s == %s (%s)\n",
3153 s1
.c_str(), s2
.c_str(),
3154 s1
== s2
? "ok" : "ERROR");
3158 // test time zones stuff
3159 static void TestTimeZones()
3161 puts("\n*** wxDateTime timezone test ***");
3163 wxDateTime now
= wxDateTime::Now();
3165 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3166 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3167 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3168 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3169 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3170 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3172 wxDateTime::Tm tm
= now
.GetTm();
3173 if ( wxDateTime(tm
) != now
)
3175 printf("ERROR: got %s instead of %s\n",
3176 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3180 // test some minimal support for the dates outside the standard range
3181 static void TestTimeRange()
3183 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3185 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3187 printf("Unix epoch:\t%s\n",
3188 wxDateTime(2440587.5).Format(fmt
).c_str());
3189 printf("Feb 29, 0: \t%s\n",
3190 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3191 printf("JDN 0: \t%s\n",
3192 wxDateTime(0.0).Format(fmt
).c_str());
3193 printf("Jan 1, 1AD:\t%s\n",
3194 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3195 printf("May 29, 2099:\t%s\n",
3196 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3199 static void TestTimeTicks()
3201 puts("\n*** wxDateTime ticks test ***");
3203 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3205 const Date
& d
= testDates
[n
];
3206 if ( d
.ticks
== -1 )
3209 wxDateTime dt
= d
.DT();
3210 long ticks
= (dt
.GetValue() / 1000).ToLong();
3211 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3212 if ( ticks
== d
.ticks
)
3218 printf(" (ERROR: should be %ld, delta = %ld)\n",
3219 d
.ticks
, ticks
- d
.ticks
);
3222 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3223 ticks
= (dt
.GetValue() / 1000).ToLong();
3224 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3225 if ( ticks
== d
.gmticks
)
3231 printf(" (ERROR: should be %ld, delta = %ld)\n",
3232 d
.gmticks
, ticks
- d
.gmticks
);
3239 // test conversions to JDN &c
3240 static void TestTimeJDN()
3242 puts("\n*** wxDateTime to JDN test ***");
3244 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3246 const Date
& d
= testDates
[n
];
3247 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3248 double jdn
= dt
.GetJulianDayNumber();
3250 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3257 printf(" (ERROR: should be %f, delta = %f)\n",
3258 d
.jdn
, jdn
- d
.jdn
);
3263 // test week days computation
3264 static void TestTimeWDays()
3266 puts("\n*** wxDateTime weekday test ***");
3268 // test GetWeekDay()
3270 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3272 const Date
& d
= testDates
[n
];
3273 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3275 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3278 wxDateTime::GetWeekDayName(wday
).c_str());
3279 if ( wday
== d
.wday
)
3285 printf(" (ERROR: should be %s)\n",
3286 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3292 // test SetToWeekDay()
3293 struct WeekDateTestData
3295 Date date
; // the real date (precomputed)
3296 int nWeek
; // its week index in the month
3297 wxDateTime::WeekDay wday
; // the weekday
3298 wxDateTime::Month month
; // the month
3299 int year
; // and the year
3301 wxString
Format() const
3304 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3306 case 1: which
= "first"; break;
3307 case 2: which
= "second"; break;
3308 case 3: which
= "third"; break;
3309 case 4: which
= "fourth"; break;
3310 case 5: which
= "fifth"; break;
3312 case -1: which
= "last"; break;
3317 which
+= " from end";
3320 s
.Printf("The %s %s of %s in %d",
3322 wxDateTime::GetWeekDayName(wday
).c_str(),
3323 wxDateTime::GetMonthName(month
).c_str(),
3330 // the array data was generated by the following python program
3332 from DateTime import *
3333 from whrandom import *
3334 from string import *
3336 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3337 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3339 week = DateTimeDelta(7)
3342 year = randint(1900, 2100)
3343 month = randint(1, 12)
3344 day = randint(1, 28)
3345 dt = DateTime(year, month, day)
3346 wday = dt.day_of_week
3348 countFromEnd = choice([-1, 1])
3351 while dt.month is month:
3352 dt = dt - countFromEnd * week
3353 weekNum = weekNum + countFromEnd
3355 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3357 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3358 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3361 static const WeekDateTestData weekDatesTestData
[] =
3363 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3364 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3365 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3366 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3367 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3368 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3369 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3370 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3371 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3372 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3373 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3374 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3375 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3376 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3377 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3378 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3379 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3380 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3381 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3382 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3385 static const char *fmt
= "%d-%b-%Y";
3388 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3390 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3392 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3394 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3396 const Date
& d
= wd
.date
;
3397 if ( d
.SameDay(dt
.GetTm()) )
3403 dt
.Set(d
.day
, d
.month
, d
.year
);
3405 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3410 // test the computation of (ISO) week numbers
3411 static void TestTimeWNumber()
3413 puts("\n*** wxDateTime week number test ***");
3415 struct WeekNumberTestData
3417 Date date
; // the date
3418 wxDateTime::wxDateTime_t week
; // the week number in the year
3419 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3420 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3421 wxDateTime::wxDateTime_t dnum
; // day number in the year
3424 // data generated with the following python script:
3426 from DateTime import *
3427 from whrandom import *
3428 from string import *
3430 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3431 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3433 def GetMonthWeek(dt):
3434 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3435 if weekNumMonth < 0:
3436 weekNumMonth = weekNumMonth + 53
3439 def GetLastSundayBefore(dt):
3440 if dt.iso_week[2] == 7:
3443 return dt - DateTimeDelta(dt.iso_week[2])
3446 year = randint(1900, 2100)
3447 month = randint(1, 12)
3448 day = randint(1, 28)
3449 dt = DateTime(year, month, day)
3450 dayNum = dt.day_of_year
3451 weekNum = dt.iso_week[1]
3452 weekNumMonth = GetMonthWeek(dt)
3455 dtSunday = GetLastSundayBefore(dt)
3457 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3458 weekNumMonth2 = weekNumMonth2 + 1
3459 dtSunday = dtSunday - DateTimeDelta(7)
3461 data = { 'day': rjust(`day`, 2), \
3462 'month': monthNames[month - 1], \
3464 'weekNum': rjust(`weekNum`, 2), \
3465 'weekNumMonth': weekNumMonth, \
3466 'weekNumMonth2': weekNumMonth2, \
3467 'dayNum': rjust(`dayNum`, 3) }
3469 print " { { %(day)s, "\
3470 "wxDateTime::%(month)s, "\
3473 "%(weekNumMonth)s, "\
3474 "%(weekNumMonth2)s, "\
3475 "%(dayNum)s }," % data
3478 static const WeekNumberTestData weekNumberTestDates
[] =
3480 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3481 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3482 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3483 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3484 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3485 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3486 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3487 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3488 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3489 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3490 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3491 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3492 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3493 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3494 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3495 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3496 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3497 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3498 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3499 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3502 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3504 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3505 const Date
& d
= wn
.date
;
3507 wxDateTime dt
= d
.DT();
3509 wxDateTime::wxDateTime_t
3510 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3511 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3512 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3513 dnum
= dt
.GetDayOfYear();
3515 printf("%s: the day number is %d",
3516 d
.FormatDate().c_str(), dnum
);
3517 if ( dnum
== wn
.dnum
)
3523 printf(" (ERROR: should be %d)", wn
.dnum
);
3526 printf(", week in month is %d", wmon
);
3527 if ( wmon
== wn
.wmon
)
3533 printf(" (ERROR: should be %d)", wn
.wmon
);
3536 printf(" or %d", wmon2
);
3537 if ( wmon2
== wn
.wmon2
)
3543 printf(" (ERROR: should be %d)", wn
.wmon2
);
3546 printf(", week in year is %d", week
);
3547 if ( week
== wn
.week
)
3553 printf(" (ERROR: should be %d)\n", wn
.week
);
3558 // test DST calculations
3559 static void TestTimeDST()
3561 puts("\n*** wxDateTime DST test ***");
3563 printf("DST is%s in effect now.\n\n",
3564 wxDateTime::Now().IsDST() ? "" : " not");
3566 // taken from http://www.energy.ca.gov/daylightsaving.html
3567 static const Date datesDST
[2][2004 - 1900 + 1] =
3570 { 1, wxDateTime::Apr
, 1990 },
3571 { 7, wxDateTime::Apr
, 1991 },
3572 { 5, wxDateTime::Apr
, 1992 },
3573 { 4, wxDateTime::Apr
, 1993 },
3574 { 3, wxDateTime::Apr
, 1994 },
3575 { 2, wxDateTime::Apr
, 1995 },
3576 { 7, wxDateTime::Apr
, 1996 },
3577 { 6, wxDateTime::Apr
, 1997 },
3578 { 5, wxDateTime::Apr
, 1998 },
3579 { 4, wxDateTime::Apr
, 1999 },
3580 { 2, wxDateTime::Apr
, 2000 },
3581 { 1, wxDateTime::Apr
, 2001 },
3582 { 7, wxDateTime::Apr
, 2002 },
3583 { 6, wxDateTime::Apr
, 2003 },
3584 { 4, wxDateTime::Apr
, 2004 },
3587 { 28, wxDateTime::Oct
, 1990 },
3588 { 27, wxDateTime::Oct
, 1991 },
3589 { 25, wxDateTime::Oct
, 1992 },
3590 { 31, wxDateTime::Oct
, 1993 },
3591 { 30, wxDateTime::Oct
, 1994 },
3592 { 29, wxDateTime::Oct
, 1995 },
3593 { 27, wxDateTime::Oct
, 1996 },
3594 { 26, wxDateTime::Oct
, 1997 },
3595 { 25, wxDateTime::Oct
, 1998 },
3596 { 31, wxDateTime::Oct
, 1999 },
3597 { 29, wxDateTime::Oct
, 2000 },
3598 { 28, wxDateTime::Oct
, 2001 },
3599 { 27, wxDateTime::Oct
, 2002 },
3600 { 26, wxDateTime::Oct
, 2003 },
3601 { 31, wxDateTime::Oct
, 2004 },
3606 for ( year
= 1990; year
< 2005; year
++ )
3608 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3609 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3611 printf("DST period in the US for year %d: from %s to %s",
3612 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3614 size_t n
= year
- 1990;
3615 const Date
& dBegin
= datesDST
[0][n
];
3616 const Date
& dEnd
= datesDST
[1][n
];
3618 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3624 printf(" (ERROR: should be %s %d to %s %d)\n",
3625 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3626 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3632 for ( year
= 1990; year
< 2005; year
++ )
3634 printf("DST period in Europe for year %d: from %s to %s\n",
3636 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3637 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3641 // test wxDateTime -> text conversion
3642 static void TestTimeFormat()
3644 puts("\n*** wxDateTime formatting test ***");
3646 // some information may be lost during conversion, so store what kind
3647 // of info should we recover after a round trip
3650 CompareNone
, // don't try comparing
3651 CompareBoth
, // dates and times should be identical
3652 CompareDate
, // dates only
3653 CompareTime
// time only
3658 CompareKind compareKind
;
3660 } formatTestFormats
[] =
3662 { CompareBoth
, "---> %c" },
3663 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3664 { CompareBoth
, "Date is %x, time is %X" },
3665 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3666 { CompareNone
, "The day of year: %j, the week of year: %W" },
3667 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3670 static const Date formatTestDates
[] =
3672 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3673 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3675 // this test can't work for other centuries because it uses two digit
3676 // years in formats, so don't even try it
3677 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3678 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3679 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3683 // an extra test (as it doesn't depend on date, don't do it in the loop)
3684 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3686 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3690 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3691 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3693 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3694 printf("%s", s
.c_str());
3696 // what can we recover?
3697 int kind
= formatTestFormats
[n
].compareKind
;
3701 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3704 // converion failed - should it have?
3705 if ( kind
== CompareNone
)
3708 puts(" (ERROR: conversion back failed)");
3712 // should have parsed the entire string
3713 puts(" (ERROR: conversion back stopped too soon)");
3717 bool equal
= FALSE
; // suppress compilaer warning
3725 equal
= dt
.IsSameDate(dt2
);
3729 equal
= dt
.IsSameTime(dt2
);
3735 printf(" (ERROR: got back '%s' instead of '%s')\n",
3736 dt2
.Format().c_str(), dt
.Format().c_str());
3747 // test text -> wxDateTime conversion
3748 static void TestTimeParse()
3750 puts("\n*** wxDateTime parse test ***");
3752 struct ParseTestData
3759 static const ParseTestData parseTestDates
[] =
3761 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3762 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3765 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3767 const char *format
= parseTestDates
[n
].format
;
3769 printf("%s => ", format
);
3772 if ( dt
.ParseRfc822Date(format
) )
3774 printf("%s ", dt
.Format().c_str());
3776 if ( parseTestDates
[n
].good
)
3778 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3785 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3790 puts("(ERROR: bad format)");
3795 printf("bad format (%s)\n",
3796 parseTestDates
[n
].good
? "ERROR" : "ok");
3801 static void TestDateTimeInteractive()
3803 puts("\n*** interactive wxDateTime tests ***");
3809 printf("Enter a date: ");
3810 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3813 // kill the last '\n'
3814 buf
[strlen(buf
) - 1] = 0;
3817 const char *p
= dt
.ParseDate(buf
);
3820 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3826 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3829 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3830 dt
.Format("%b %d, %Y").c_str(),
3832 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3833 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3834 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3837 puts("\n*** done ***");
3840 static void TestTimeMS()
3842 puts("*** testing millisecond-resolution support in wxDateTime ***");
3844 wxDateTime dt1
= wxDateTime::Now(),
3845 dt2
= wxDateTime::UNow();
3847 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3848 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3849 printf("Dummy loop: ");
3850 for ( int i
= 0; i
< 6000; i
++ )
3852 //for ( int j = 0; j < 10; j++ )
3855 s
.Printf("%g", sqrt(i
));
3864 dt2
= wxDateTime::UNow();
3865 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3867 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3869 puts("\n*** done ***");
3872 static void TestTimeArithmetics()
3874 puts("\n*** testing arithmetic operations on wxDateTime ***");
3876 static const struct ArithmData
3878 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3879 : span(sp
), name(nam
) { }
3883 } testArithmData
[] =
3885 ArithmData(wxDateSpan::Day(), "day"),
3886 ArithmData(wxDateSpan::Week(), "week"),
3887 ArithmData(wxDateSpan::Month(), "month"),
3888 ArithmData(wxDateSpan::Year(), "year"),
3889 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3892 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3894 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3896 wxDateSpan span
= testArithmData
[n
].span
;
3900 const char *name
= testArithmData
[n
].name
;
3901 printf("%s + %s = %s, %s - %s = %s\n",
3902 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3903 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3905 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3906 if ( dt1
- span
== dt
)
3912 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3915 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3916 if ( dt2
+ span
== dt
)
3922 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3925 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3926 if ( dt2
+ 2*span
== dt1
)
3932 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3939 static void TestTimeHolidays()
3941 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3943 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3944 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3945 dtEnd
= dtStart
.GetLastMonthDay();
3947 wxDateTimeArray hol
;
3948 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3950 const wxChar
*format
= "%d-%b-%Y (%a)";
3952 printf("All holidays between %s and %s:\n",
3953 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3955 size_t count
= hol
.GetCount();
3956 for ( size_t n
= 0; n
< count
; n
++ )
3958 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3964 static void TestTimeZoneBug()
3966 puts("\n*** testing for DST/timezone bug ***\n");
3968 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3969 for ( int i
= 0; i
< 31; i
++ )
3971 printf("Date %s: week day %s.\n",
3972 date
.Format(_T("%d-%m-%Y")).c_str(),
3973 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3975 date
+= wxDateSpan::Day();
3981 static void TestTimeSpanFormat()
3983 puts("\n*** wxTimeSpan tests ***");
3985 static const char *formats
[] =
3987 _T("(default) %H:%M:%S"),
3988 _T("%E weeks and %D days"),
3989 _T("%l milliseconds"),
3990 _T("(with ms) %H:%M:%S:%l"),
3991 _T("100%% of minutes is %M"), // test "%%"
3992 _T("%D days and %H hours"),
3995 wxTimeSpan
ts1(1, 2, 3, 4),
3997 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3999 printf("ts1 = %s\tts2 = %s\n",
4000 ts1
.Format(formats
[n
]).c_str(),
4001 ts2
.Format(formats
[n
]).c_str());
4009 // test compatibility with the old wxDate/wxTime classes
4010 static void TestTimeCompatibility()
4012 puts("\n*** wxDateTime compatibility test ***");
4014 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4015 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4017 double jdnNow
= wxDateTime::Now().GetJDN();
4018 long jdnMidnight
= (long)(jdnNow
- 0.5);
4019 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4021 jdnMidnight
= wxDate().Set().GetJulianDate();
4022 printf("wxDateTime for today: %s\n",
4023 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4025 int flags
= wxEUROPEAN
;//wxFULL;
4028 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4029 for ( int n
= 0; n
< 7; n
++ )
4031 printf("Previous %s is %s\n",
4032 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4033 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4039 #endif // TEST_DATETIME
4041 // ----------------------------------------------------------------------------
4043 // ----------------------------------------------------------------------------
4047 #include <wx/thread.h>
4049 static size_t gs_counter
= (size_t)-1;
4050 static wxCriticalSection gs_critsect
;
4051 static wxCondition gs_cond
;
4053 class MyJoinableThread
: public wxThread
4056 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4057 { m_n
= n
; Create(); }
4059 // thread execution starts here
4060 virtual ExitCode
Entry();
4066 wxThread::ExitCode
MyJoinableThread::Entry()
4068 unsigned long res
= 1;
4069 for ( size_t n
= 1; n
< m_n
; n
++ )
4073 // it's a loooong calculation :-)
4077 return (ExitCode
)res
;
4080 class MyDetachedThread
: public wxThread
4083 MyDetachedThread(size_t n
, char ch
)
4087 m_cancelled
= FALSE
;
4092 // thread execution starts here
4093 virtual ExitCode
Entry();
4096 virtual void OnExit();
4099 size_t m_n
; // number of characters to write
4100 char m_ch
; // character to write
4102 bool m_cancelled
; // FALSE if we exit normally
4105 wxThread::ExitCode
MyDetachedThread::Entry()
4108 wxCriticalSectionLocker
lock(gs_critsect
);
4109 if ( gs_counter
== (size_t)-1 )
4115 for ( size_t n
= 0; n
< m_n
; n
++ )
4117 if ( TestDestroy() )
4127 wxThread::Sleep(100);
4133 void MyDetachedThread::OnExit()
4135 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4137 wxCriticalSectionLocker
lock(gs_critsect
);
4138 if ( !--gs_counter
&& !m_cancelled
)
4142 void TestDetachedThreads()
4144 puts("\n*** Testing detached threads ***");
4146 static const size_t nThreads
= 3;
4147 MyDetachedThread
*threads
[nThreads
];
4149 for ( n
= 0; n
< nThreads
; n
++ )
4151 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4154 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4155 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4157 for ( n
= 0; n
< nThreads
; n
++ )
4162 // wait until all threads terminate
4168 void TestJoinableThreads()
4170 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4172 // calc 10! in the background
4173 MyJoinableThread
thread(10);
4176 printf("\nThread terminated with exit code %lu.\n",
4177 (unsigned long)thread
.Wait());
4180 void TestThreadSuspend()
4182 puts("\n*** Testing thread suspend/resume functions ***");
4184 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4188 // this is for this demo only, in a real life program we'd use another
4189 // condition variable which would be signaled from wxThread::Entry() to
4190 // tell us that the thread really started running - but here just wait a
4191 // bit and hope that it will be enough (the problem is, of course, that
4192 // the thread might still not run when we call Pause() which will result
4194 wxThread::Sleep(300);
4196 for ( size_t n
= 0; n
< 3; n
++ )
4200 puts("\nThread suspended");
4203 // don't sleep but resume immediately the first time
4204 wxThread::Sleep(300);
4206 puts("Going to resume the thread");
4211 puts("Waiting until it terminates now");
4213 // wait until the thread terminates
4219 void TestThreadDelete()
4221 // As above, using Sleep() is only for testing here - we must use some
4222 // synchronisation object instead to ensure that the thread is still
4223 // running when we delete it - deleting a detached thread which already
4224 // terminated will lead to a crash!
4226 puts("\n*** Testing thread delete function ***");
4228 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4232 puts("\nDeleted a thread which didn't start to run yet.");
4234 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4238 wxThread::Sleep(300);
4242 puts("\nDeleted a running thread.");
4244 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4248 wxThread::Sleep(300);
4254 puts("\nDeleted a sleeping thread.");
4256 MyJoinableThread
thread3(20);
4261 puts("\nDeleted a joinable thread.");
4263 MyJoinableThread
thread4(2);
4266 wxThread::Sleep(300);
4270 puts("\nDeleted a joinable thread which already terminated.");
4275 #endif // TEST_THREADS
4277 // ----------------------------------------------------------------------------
4279 // ----------------------------------------------------------------------------
4283 static void PrintArray(const char* name
, const wxArrayString
& array
)
4285 printf("Dump of the array '%s'\n", name
);
4287 size_t nCount
= array
.GetCount();
4288 for ( size_t n
= 0; n
< nCount
; n
++ )
4290 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4294 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4296 printf("Dump of the array '%s'\n", name
);
4298 size_t nCount
= array
.GetCount();
4299 for ( size_t n
= 0; n
< nCount
; n
++ )
4301 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4305 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4306 const wxString
& second
)
4308 return first
.length() - second
.length();
4311 int wxCMPFUNC_CONV
IntCompare(int *first
,
4314 return *first
- *second
;
4317 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4320 return *second
- *first
;
4323 static void TestArrayOfInts()
4325 puts("*** Testing wxArrayInt ***\n");
4336 puts("After sort:");
4340 puts("After reverse sort:");
4341 a
.Sort(IntRevCompare
);
4345 #include "wx/dynarray.h"
4347 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4348 #include "wx/arrimpl.cpp"
4349 WX_DEFINE_OBJARRAY(ArrayBars
);
4351 static void TestArrayOfObjects()
4353 puts("*** Testing wxObjArray ***\n");
4357 Bar
bar("second bar");
4359 printf("Initially: %u objects in the array, %u objects total.\n",
4360 bars
.GetCount(), Bar::GetNumber());
4362 bars
.Add(new Bar("first bar"));
4365 printf("Now: %u objects in the array, %u objects total.\n",
4366 bars
.GetCount(), Bar::GetNumber());
4370 printf("After Empty(): %u objects in the array, %u objects total.\n",
4371 bars
.GetCount(), Bar::GetNumber());
4374 printf("Finally: no more objects in the array, %u objects total.\n",
4378 #endif // TEST_ARRAYS
4380 // ----------------------------------------------------------------------------
4382 // ----------------------------------------------------------------------------
4386 #include "wx/timer.h"
4387 #include "wx/tokenzr.h"
4389 static void TestStringConstruction()
4391 puts("*** Testing wxString constructores ***");
4393 #define TEST_CTOR(args, res) \
4396 printf("wxString%s = %s ", #args, s.c_str()); \
4403 printf("(ERROR: should be %s)\n", res); \
4407 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4408 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4409 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4410 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4412 static const wxChar
*s
= _T("?really!");
4413 const wxChar
*start
= wxStrchr(s
, _T('r'));
4414 const wxChar
*end
= wxStrchr(s
, _T('!'));
4415 TEST_CTOR((start
, end
), _T("really"));
4420 static void TestString()
4430 for (int i
= 0; i
< 1000000; ++i
)
4434 c
= "! How'ya doin'?";
4437 c
= "Hello world! What's up?";
4442 printf ("TestString elapsed time: %ld\n", sw
.Time());
4445 static void TestPChar()
4453 for (int i
= 0; i
< 1000000; ++i
)
4455 strcpy (a
, "Hello");
4456 strcpy (b
, " world");
4457 strcpy (c
, "! How'ya doin'?");
4460 strcpy (c
, "Hello world! What's up?");
4461 if (strcmp (c
, a
) == 0)
4465 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4468 static void TestStringSub()
4470 wxString
s("Hello, world!");
4472 puts("*** Testing wxString substring extraction ***");
4474 printf("String = '%s'\n", s
.c_str());
4475 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4476 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4477 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4478 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4479 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4480 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4482 static const wxChar
*prefixes
[] =
4486 _T("Hello, world!"),
4487 _T("Hello, world!!!"),
4493 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4495 wxString prefix
= prefixes
[n
], rest
;
4496 bool rc
= s
.StartsWith(prefix
, &rest
);
4497 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4500 printf(" (the rest is '%s')\n", rest
.c_str());
4511 static void TestStringFormat()
4513 puts("*** Testing wxString formatting ***");
4516 s
.Printf("%03d", 18);
4518 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4519 printf("Number 18: %s\n", s
.c_str());
4524 // returns "not found" for npos, value for all others
4525 static wxString
PosToString(size_t res
)
4527 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4528 : wxString::Format(_T("%u"), res
);
4532 static void TestStringFind()
4534 puts("*** Testing wxString find() functions ***");
4536 static const wxChar
*strToFind
= _T("ell");
4537 static const struct StringFindTest
4541 result
; // of searching "ell" in str
4544 { _T("Well, hello world"), 0, 1 },
4545 { _T("Well, hello world"), 6, 7 },
4546 { _T("Well, hello world"), 9, wxString::npos
},
4549 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4551 const StringFindTest
& ft
= findTestData
[n
];
4552 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4554 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4555 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4557 size_t resTrue
= ft
.result
;
4558 if ( res
== resTrue
)
4564 printf(_T("(ERROR: should be %s)\n"),
4565 PosToString(resTrue
).c_str());
4572 static void TestStringTokenizer()
4574 puts("*** Testing wxStringTokenizer ***");
4576 static const wxChar
*modeNames
[] =
4580 _T("return all empty"),
4585 static const struct StringTokenizerTest
4587 const wxChar
*str
; // string to tokenize
4588 const wxChar
*delims
; // delimiters to use
4589 size_t count
; // count of token
4590 wxStringTokenizerMode mode
; // how should we tokenize it
4591 } tokenizerTestData
[] =
4593 { _T(""), _T(" "), 0 },
4594 { _T("Hello, world"), _T(" "), 2 },
4595 { _T("Hello, world "), _T(" "), 2 },
4596 { _T("Hello, world"), _T(","), 2 },
4597 { _T("Hello, world!"), _T(",!"), 2 },
4598 { _T("Hello,, world!"), _T(",!"), 3 },
4599 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4600 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4601 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4602 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4603 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4604 { _T("01/02/99"), _T("/-"), 3 },
4605 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4608 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4610 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4611 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4613 size_t count
= tkz
.CountTokens();
4614 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4615 MakePrintable(tt
.str
).c_str(),
4617 MakePrintable(tt
.delims
).c_str(),
4618 modeNames
[tkz
.GetMode()]);
4619 if ( count
== tt
.count
)
4625 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4630 // if we emulate strtok(), check that we do it correctly
4631 wxChar
*buf
, *s
= NULL
, *last
;
4633 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4635 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4636 wxStrcpy(buf
, tt
.str
);
4638 s
= wxStrtok(buf
, tt
.delims
, &last
);
4645 // now show the tokens themselves
4647 while ( tkz
.HasMoreTokens() )
4649 wxString token
= tkz
.GetNextToken();
4651 printf(_T("\ttoken %u: '%s'"),
4653 MakePrintable(token
).c_str());
4663 printf(" (ERROR: should be %s)\n", s
);
4666 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4670 // nothing to compare with
4675 if ( count2
!= count
)
4677 puts(_T("\tERROR: token count mismatch"));
4686 static void TestStringReplace()
4688 puts("*** Testing wxString::replace ***");
4690 static const struct StringReplaceTestData
4692 const wxChar
*original
; // original test string
4693 size_t start
, len
; // the part to replace
4694 const wxChar
*replacement
; // the replacement string
4695 const wxChar
*result
; // and the expected result
4696 } stringReplaceTestData
[] =
4698 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4699 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4700 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4701 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4702 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4705 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4707 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4709 wxString original
= data
.original
;
4710 original
.replace(data
.start
, data
.len
, data
.replacement
);
4712 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4713 data
.original
, data
.start
, data
.len
, data
.replacement
,
4716 if ( original
== data
.result
)
4722 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4729 static void TestStringMatch()
4731 wxPuts(_T("*** Testing wxString::Matches() ***"));
4733 static const struct StringMatchTestData
4736 const wxChar
*wildcard
;
4738 } stringMatchTestData
[] =
4740 { _T("foobar"), _T("foo*"), 1 },
4741 { _T("foobar"), _T("*oo*"), 1 },
4742 { _T("foobar"), _T("*bar"), 1 },
4743 { _T("foobar"), _T("??????"), 1 },
4744 { _T("foobar"), _T("f??b*"), 1 },
4745 { _T("foobar"), _T("f?b*"), 0 },
4746 { _T("foobar"), _T("*goo*"), 0 },
4747 { _T("foobar"), _T("*foo"), 0 },
4748 { _T("foobarfoo"), _T("*foo"), 1 },
4749 { _T(""), _T("*"), 1 },
4750 { _T(""), _T("?"), 0 },
4753 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4755 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4756 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4757 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4759 matches
? _T("matches") : _T("doesn't match"),
4761 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4767 #endif // TEST_STRINGS
4769 // ----------------------------------------------------------------------------
4771 // ----------------------------------------------------------------------------
4773 int main(int argc
, char **argv
)
4775 wxInitializer initializer
;
4778 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4783 #ifdef TEST_SNGLINST
4784 wxSingleInstanceChecker checker
;
4785 if ( checker
.Create(_T(".wxconsole.lock")) )
4787 if ( checker
.IsAnotherRunning() )
4789 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4794 // wait some time to give time to launch another instance
4795 wxPrintf(_T("Press \"Enter\" to continue..."));
4798 else // failed to create
4800 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4802 #endif // TEST_SNGLINST
4806 #endif // TEST_CHARSET
4809 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4811 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4812 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4814 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4815 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4816 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4817 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4819 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4820 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4825 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4827 parser
.AddOption("project_name", "", "full path to project file",
4828 wxCMD_LINE_VAL_STRING
,
4829 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4831 switch ( parser
.Parse() )
4834 wxLogMessage("Help was given, terminating.");
4838 ShowCmdLine(parser
);
4842 wxLogMessage("Syntax error detected, aborting.");
4845 #endif // TEST_CMDLINE
4853 TestStringConstruction();
4856 TestStringTokenizer();
4857 TestStringReplace();
4860 #endif // TEST_STRINGS
4873 puts("*** Initially:");
4875 PrintArray("a1", a1
);
4877 wxArrayString
a2(a1
);
4878 PrintArray("a2", a2
);
4880 wxSortedArrayString
a3(a1
);
4881 PrintArray("a3", a3
);
4883 puts("*** After deleting a string from a1");
4886 PrintArray("a1", a1
);
4887 PrintArray("a2", a2
);
4888 PrintArray("a3", a3
);
4890 puts("*** After reassigning a1 to a2 and a3");
4892 PrintArray("a2", a2
);
4893 PrintArray("a3", a3
);
4895 puts("*** After sorting a1");
4897 PrintArray("a1", a1
);
4899 puts("*** After sorting a1 in reverse order");
4901 PrintArray("a1", a1
);
4903 puts("*** After sorting a1 by the string length");
4904 a1
.Sort(StringLenCompare
);
4905 PrintArray("a1", a1
);
4907 TestArrayOfObjects();
4910 #endif // TEST_ARRAYS
4918 #ifdef TEST_DLLLOADER
4920 #endif // TEST_DLLLOADER
4924 #endif // TEST_ENVIRON
4928 #endif // TEST_EXECUTE
4930 #ifdef TEST_FILECONF
4932 #endif // TEST_FILECONF
4940 #endif // TEST_LOCALE
4944 for ( size_t n
= 0; n
< 8000; n
++ )
4946 s
<< (char)('A' + (n
% 26));
4950 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4952 // this one shouldn't be truncated
4955 // but this one will because log functions use fixed size buffer
4956 // (note that it doesn't need '\n' at the end neither - will be added
4958 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4970 #ifdef TEST_FILENAME
4971 TestFileNameSplit();
4974 TestFileNameConstruction();
4976 TestFileNameComparison();
4977 TestFileNameOperations();
4979 #endif // TEST_FILENAME
4982 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4983 if ( TestFtpConnect() )
4994 TestFtpInteractive();
4996 //else: connecting to the FTP server failed
5003 int nCPUs
= wxThread::GetCPUCount();
5004 printf("This system has %d CPUs\n", nCPUs
);
5006 wxThread::SetConcurrency(nCPUs
);
5008 if ( argc
> 1 && argv
[1][0] == 't' )
5009 wxLog::AddTraceMask("thread");
5012 TestDetachedThreads();
5014 TestJoinableThreads();
5016 TestThreadSuspend();
5020 #endif // TEST_THREADS
5022 #ifdef TEST_LONGLONG
5023 // seed pseudo random generator
5024 srand((unsigned)time(NULL
));
5032 TestMultiplication();
5035 TestLongLongConversion();
5036 TestBitOperations();
5038 TestLongLongComparison();
5039 #endif // TEST_LONGLONG
5046 wxLog::AddTraceMask(_T("mime"));
5054 TestMimeAssociate();
5057 #ifdef TEST_INFO_FUNCTIONS
5060 #endif // TEST_INFO_FUNCTIONS
5062 #ifdef TEST_PATHLIST
5064 #endif // TEST_PATHLIST
5068 #endif // TEST_REGCONF
5071 // TODO: write a real test using src/regex/tests file
5076 TestRegExSubmatch();
5078 TestRegExInteractive();
5079 #endif // TEST_REGEX
5081 #ifdef TEST_REGISTRY
5084 TestRegistryAssociation();
5085 #endif // TEST_REGISTRY
5093 #endif // TEST_SOCKETS
5099 #endif // TEST_STREAMS
5103 #endif // TEST_TIMER
5105 #ifdef TEST_DATETIME
5118 TestTimeArithmetics();
5125 TestTimeSpanFormat();
5127 TestDateTimeInteractive();
5128 #endif // TEST_DATETIME
5131 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5133 #endif // TEST_USLEEP
5139 #endif // TEST_VCARD
5143 #endif // TEST_WCHAR
5147 TestZipStreamRead();
5148 TestZipFileSystem();
5153 TestZlibStreamWrite();
5154 TestZlibStreamRead();