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
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 TestRegExReplacement()
1832 wxPuts(_T("*** Testing RE replacement ***"));
1834 static struct RegExReplTestData
1838 const wxChar
*result
;
1840 } regExReplTestData
[] =
1842 { _T("foo123"), _T("bar"), _T("bar"), 1 },
1843 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
1844 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
1845 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
1846 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
1847 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
1848 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
1851 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
1852 wxRegEx re
= pattern
;
1854 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
1856 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
1858 const RegExReplTestData
& data
= regExReplTestData
[n
];
1860 wxString text
= data
.text
;
1861 size_t nRepl
= re
.Replace(&text
, data
.repl
);
1863 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
1864 data
.text
, data
.repl
,
1865 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
1867 if ( text
== data
.result
&& nRepl
== data
.count
)
1873 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
1874 data
.count
, data
.result
);
1879 static void TestRegExInteractive()
1881 wxPuts(_T("*** Testing RE interactively ***"));
1886 printf("\nEnter a pattern: ");
1887 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1890 // kill the last '\n'
1891 pattern
[strlen(pattern
) - 1] = 0;
1894 if ( !re
.Compile(pattern
) )
1902 printf("Enter text to match: ");
1903 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
1906 // kill the last '\n'
1907 text
[strlen(text
) - 1] = 0;
1909 if ( !re
.Matches(text
) )
1911 printf("No match.\n");
1915 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
1918 for ( size_t n
= 1; ; n
++ )
1920 if ( !re
.GetMatch(&start
, &len
, n
) )
1925 printf("Subexpr %u matched '%s'\n",
1926 n
, wxString(text
+ start
, len
).c_str());
1933 #endif // TEST_REGEX
1935 // ----------------------------------------------------------------------------
1936 // registry and related stuff
1937 // ----------------------------------------------------------------------------
1939 // this is for MSW only
1942 #undef TEST_REGISTRY
1947 #include <wx/confbase.h>
1948 #include <wx/msw/regconf.h>
1950 static void TestRegConfWrite()
1952 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1953 regconf
.Write(_T("Hello"), wxString(_T("world")));
1956 #endif // TEST_REGCONF
1958 #ifdef TEST_REGISTRY
1960 #include <wx/msw/registry.h>
1962 // I chose this one because I liked its name, but it probably only exists under
1964 static const wxChar
*TESTKEY
=
1965 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1967 static void TestRegistryRead()
1969 puts("*** testing registry reading ***");
1971 wxRegKey
key(TESTKEY
);
1972 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1975 puts("ERROR: test key can't be opened, aborting test.");
1980 size_t nSubKeys
, nValues
;
1981 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1983 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1986 printf("Enumerating values:\n");
1990 bool cont
= key
.GetFirstValue(value
, dummy
);
1993 printf("Value '%s': type ", value
.c_str());
1994 switch ( key
.GetValueType(value
) )
1996 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1997 case wxRegKey::Type_String
: printf("SZ"); break;
1998 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1999 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2000 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2001 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2002 default: printf("other (unknown)"); break;
2005 printf(", value = ");
2006 if ( key
.IsNumericValue(value
) )
2009 key
.QueryValue(value
, &val
);
2015 key
.QueryValue(value
, val
);
2016 printf("'%s'", val
.c_str());
2018 key
.QueryRawValue(value
, val
);
2019 printf(" (raw value '%s')", val
.c_str());
2024 cont
= key
.GetNextValue(value
, dummy
);
2028 static void TestRegistryAssociation()
2031 The second call to deleteself genertaes an error message, with a
2032 messagebox saying .flo is crucial to system operation, while the .ddf
2033 call also fails, but with no error message
2038 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2040 key
= "ddxf_auto_file" ;
2041 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2043 key
= "ddxf_auto_file" ;
2044 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2047 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2049 key
= "program \"%1\"" ;
2051 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2053 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2055 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2057 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2061 #endif // TEST_REGISTRY
2063 // ----------------------------------------------------------------------------
2065 // ----------------------------------------------------------------------------
2069 #include <wx/socket.h>
2070 #include <wx/protocol/protocol.h>
2071 #include <wx/protocol/http.h>
2073 static void TestSocketServer()
2075 puts("*** Testing wxSocketServer ***\n");
2077 static const int PORT
= 3000;
2082 wxSocketServer
*server
= new wxSocketServer(addr
);
2083 if ( !server
->Ok() )
2085 puts("ERROR: failed to bind");
2092 printf("Server: waiting for connection on port %d...\n", PORT
);
2094 wxSocketBase
*socket
= server
->Accept();
2097 puts("ERROR: wxSocketServer::Accept() failed.");
2101 puts("Server: got a client.");
2103 server
->SetTimeout(60); // 1 min
2105 while ( socket
->IsConnected() )
2111 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2113 // don't log error if the client just close the connection
2114 if ( socket
->IsConnected() )
2116 puts("ERROR: in wxSocket::Read.");
2136 printf("Server: got '%s'.\n", s
.c_str());
2137 if ( s
== _T("bye") )
2144 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2145 socket
->Write("\r\n", 2);
2146 printf("Server: wrote '%s'.\n", s
.c_str());
2149 puts("Server: lost a client.");
2154 // same as "delete server" but is consistent with GUI programs
2158 static void TestSocketClient()
2160 puts("*** Testing wxSocketClient ***\n");
2162 static const char *hostname
= "www.wxwindows.org";
2165 addr
.Hostname(hostname
);
2168 printf("--- Attempting to connect to %s:80...\n", hostname
);
2170 wxSocketClient client
;
2171 if ( !client
.Connect(addr
) )
2173 printf("ERROR: failed to connect to %s\n", hostname
);
2177 printf("--- Connected to %s:%u...\n",
2178 addr
.Hostname().c_str(), addr
.Service());
2182 // could use simply "GET" here I suppose
2184 wxString::Format("GET http://%s/\r\n", hostname
);
2185 client
.Write(cmdGet
, cmdGet
.length());
2186 printf("--- Sent command '%s' to the server\n",
2187 MakePrintable(cmdGet
).c_str());
2188 client
.Read(buf
, WXSIZEOF(buf
));
2189 printf("--- Server replied:\n%s", buf
);
2193 #endif // TEST_SOCKETS
2195 // ----------------------------------------------------------------------------
2197 // ----------------------------------------------------------------------------
2201 #include <wx/protocol/ftp.h>
2205 #define FTP_ANONYMOUS
2207 #ifdef FTP_ANONYMOUS
2208 static const char *directory
= "/pub";
2209 static const char *filename
= "welcome.msg";
2211 static const char *directory
= "/etc";
2212 static const char *filename
= "issue";
2215 static bool TestFtpConnect()
2217 puts("*** Testing FTP connect ***");
2219 #ifdef FTP_ANONYMOUS
2220 static const char *hostname
= "ftp.wxwindows.org";
2222 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2223 #else // !FTP_ANONYMOUS
2224 static const char *hostname
= "localhost";
2227 fgets(user
, WXSIZEOF(user
), stdin
);
2228 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2232 printf("Password for %s: ", password
);
2233 fgets(password
, WXSIZEOF(password
), stdin
);
2234 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2235 ftp
.SetPassword(password
);
2237 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2238 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2240 if ( !ftp
.Connect(hostname
) )
2242 printf("ERROR: failed to connect to %s\n", hostname
);
2248 printf("--- Connected to %s, current directory is '%s'\n",
2249 hostname
, ftp
.Pwd().c_str());
2255 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2256 static void TestFtpWuFtpd()
2259 static const char *hostname
= "ftp.eudora.com";
2260 if ( !ftp
.Connect(hostname
) )
2262 printf("ERROR: failed to connect to %s\n", hostname
);
2266 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2267 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2270 printf("ERROR: couldn't get input stream for %s\n", filename
);
2274 size_t size
= in
->StreamSize();
2275 printf("Reading file %s (%u bytes)...", filename
, size
);
2277 char *data
= new char[size
];
2278 if ( !in
->Read(data
, size
) )
2280 puts("ERROR: read error");
2284 printf("Successfully retrieved the file.\n");
2293 static void TestFtpList()
2295 puts("*** Testing wxFTP file listing ***\n");
2298 if ( !ftp
.ChDir(directory
) )
2300 printf("ERROR: failed to cd to %s\n", directory
);
2303 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2305 // test NLIST and LIST
2306 wxArrayString files
;
2307 if ( !ftp
.GetFilesList(files
) )
2309 puts("ERROR: failed to get NLIST of files");
2313 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2314 size_t count
= files
.GetCount();
2315 for ( size_t n
= 0; n
< count
; n
++ )
2317 printf("\t%s\n", files
[n
].c_str());
2319 puts("End of the file list");
2322 if ( !ftp
.GetDirList(files
) )
2324 puts("ERROR: failed to get LIST of files");
2328 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2329 size_t count
= files
.GetCount();
2330 for ( size_t n
= 0; n
< count
; n
++ )
2332 printf("\t%s\n", files
[n
].c_str());
2334 puts("End of the file list");
2337 if ( !ftp
.ChDir(_T("..")) )
2339 puts("ERROR: failed to cd to ..");
2342 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2345 static void TestFtpDownload()
2347 puts("*** Testing wxFTP download ***\n");
2350 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2353 printf("ERROR: couldn't get input stream for %s\n", filename
);
2357 size_t size
= in
->StreamSize();
2358 printf("Reading file %s (%u bytes)...", filename
, size
);
2361 char *data
= new char[size
];
2362 if ( !in
->Read(data
, size
) )
2364 puts("ERROR: read error");
2368 printf("\nContents of %s:\n%s\n", filename
, data
);
2376 static void TestFtpFileSize()
2378 puts("*** Testing FTP SIZE command ***");
2380 if ( !ftp
.ChDir(directory
) )
2382 printf("ERROR: failed to cd to %s\n", directory
);
2385 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2387 if ( ftp
.FileExists(filename
) )
2389 int size
= ftp
.GetFileSize(filename
);
2391 printf("ERROR: couldn't get size of '%s'\n", filename
);
2393 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2397 printf("ERROR: '%s' doesn't exist\n", filename
);
2401 static void TestFtpMisc()
2403 puts("*** Testing miscellaneous wxFTP functions ***");
2405 if ( ftp
.SendCommand("STAT") != '2' )
2407 puts("ERROR: STAT failed");
2411 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2414 if ( ftp
.SendCommand("HELP SITE") != '2' )
2416 puts("ERROR: HELP SITE failed");
2420 printf("The list of site-specific commands:\n\n%s\n",
2421 ftp
.GetLastResult().c_str());
2425 static void TestFtpInteractive()
2427 puts("\n*** Interactive wxFTP test ***");
2433 printf("Enter FTP command: ");
2434 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2437 // kill the last '\n'
2438 buf
[strlen(buf
) - 1] = 0;
2440 // special handling of LIST and NLST as they require data connection
2441 wxString
start(buf
, 4);
2443 if ( start
== "LIST" || start
== "NLST" )
2446 if ( strlen(buf
) > 4 )
2449 wxArrayString files
;
2450 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2452 printf("ERROR: failed to get %s of files\n", start
.c_str());
2456 printf("--- %s of '%s' under '%s':\n",
2457 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2458 size_t count
= files
.GetCount();
2459 for ( size_t n
= 0; n
< count
; n
++ )
2461 printf("\t%s\n", files
[n
].c_str());
2463 puts("--- End of the file list");
2468 char ch
= ftp
.SendCommand(buf
);
2469 printf("Command %s", ch
? "succeeded" : "failed");
2472 printf(" (return code %c)", ch
);
2475 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2479 puts("\n*** done ***");
2482 static void TestFtpUpload()
2484 puts("*** Testing wxFTP uploading ***\n");
2487 static const char *file1
= "test1";
2488 static const char *file2
= "test2";
2489 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2492 printf("--- Uploading to %s ---\n", file1
);
2493 out
->Write("First hello", 11);
2497 // send a command to check the remote file
2498 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2500 printf("ERROR: STAT %s failed\n", file1
);
2504 printf("STAT %s returned:\n\n%s\n",
2505 file1
, ftp
.GetLastResult().c_str());
2508 out
= ftp
.GetOutputStream(file2
);
2511 printf("--- Uploading to %s ---\n", file1
);
2512 out
->Write("Second hello", 12);
2519 // ----------------------------------------------------------------------------
2521 // ----------------------------------------------------------------------------
2525 #include <wx/wfstream.h>
2526 #include <wx/mstream.h>
2528 static void TestFileStream()
2530 puts("*** Testing wxFileInputStream ***");
2532 static const wxChar
*filename
= _T("testdata.fs");
2534 wxFileOutputStream
fsOut(filename
);
2535 fsOut
.Write("foo", 3);
2538 wxFileInputStream
fsIn(filename
);
2539 printf("File stream size: %u\n", fsIn
.GetSize());
2540 while ( !fsIn
.Eof() )
2542 putchar(fsIn
.GetC());
2545 if ( !wxRemoveFile(filename
) )
2547 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2550 puts("\n*** wxFileInputStream test done ***");
2553 static void TestMemoryStream()
2555 puts("*** Testing wxMemoryInputStream ***");
2558 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2560 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2561 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2562 while ( !memInpStream
.Eof() )
2564 putchar(memInpStream
.GetC());
2567 puts("\n*** wxMemoryInputStream test done ***");
2570 #endif // TEST_STREAMS
2572 // ----------------------------------------------------------------------------
2574 // ----------------------------------------------------------------------------
2578 #include <wx/timer.h>
2579 #include <wx/utils.h>
2581 static void TestStopWatch()
2583 puts("*** Testing wxStopWatch ***\n");
2586 printf("Sleeping 3 seconds...");
2588 printf("\telapsed time: %ldms\n", sw
.Time());
2591 printf("Sleeping 2 more seconds...");
2593 printf("\telapsed time: %ldms\n", sw
.Time());
2596 printf("And 3 more seconds...");
2598 printf("\telapsed time: %ldms\n", sw
.Time());
2601 puts("\nChecking for 'backwards clock' bug...");
2602 for ( size_t n
= 0; n
< 70; n
++ )
2606 for ( size_t m
= 0; m
< 100000; m
++ )
2608 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2610 puts("\ntime is negative - ERROR!");
2620 #endif // TEST_TIMER
2622 // ----------------------------------------------------------------------------
2624 // ----------------------------------------------------------------------------
2628 #include <wx/vcard.h>
2630 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2633 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2637 wxString(_T('\t'), level
).c_str(),
2638 vcObj
->GetName().c_str());
2641 switch ( vcObj
->GetType() )
2643 case wxVCardObject::String
:
2644 case wxVCardObject::UString
:
2647 vcObj
->GetValue(&val
);
2648 value
<< _T('"') << val
<< _T('"');
2652 case wxVCardObject::Int
:
2655 vcObj
->GetValue(&i
);
2656 value
.Printf(_T("%u"), i
);
2660 case wxVCardObject::Long
:
2663 vcObj
->GetValue(&l
);
2664 value
.Printf(_T("%lu"), l
);
2668 case wxVCardObject::None
:
2671 case wxVCardObject::Object
:
2672 value
= _T("<node>");
2676 value
= _T("<unknown value type>");
2680 printf(" = %s", value
.c_str());
2683 DumpVObject(level
+ 1, *vcObj
);
2686 vcObj
= vcard
.GetNextProp(&cookie
);
2690 static void DumpVCardAddresses(const wxVCard
& vcard
)
2692 puts("\nShowing all addresses from vCard:\n");
2696 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2700 int flags
= addr
->GetFlags();
2701 if ( flags
& wxVCardAddress::Domestic
)
2703 flagsStr
<< _T("domestic ");
2705 if ( flags
& wxVCardAddress::Intl
)
2707 flagsStr
<< _T("international ");
2709 if ( flags
& wxVCardAddress::Postal
)
2711 flagsStr
<< _T("postal ");
2713 if ( flags
& wxVCardAddress::Parcel
)
2715 flagsStr
<< _T("parcel ");
2717 if ( flags
& wxVCardAddress::Home
)
2719 flagsStr
<< _T("home ");
2721 if ( flags
& wxVCardAddress::Work
)
2723 flagsStr
<< _T("work ");
2726 printf("Address %u:\n"
2728 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2731 addr
->GetPostOffice().c_str(),
2732 addr
->GetExtAddress().c_str(),
2733 addr
->GetStreet().c_str(),
2734 addr
->GetLocality().c_str(),
2735 addr
->GetRegion().c_str(),
2736 addr
->GetPostalCode().c_str(),
2737 addr
->GetCountry().c_str()
2741 addr
= vcard
.GetNextAddress(&cookie
);
2745 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2747 puts("\nShowing all phone numbers from vCard:\n");
2751 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2755 int flags
= phone
->GetFlags();
2756 if ( flags
& wxVCardPhoneNumber::Voice
)
2758 flagsStr
<< _T("voice ");
2760 if ( flags
& wxVCardPhoneNumber::Fax
)
2762 flagsStr
<< _T("fax ");
2764 if ( flags
& wxVCardPhoneNumber::Cellular
)
2766 flagsStr
<< _T("cellular ");
2768 if ( flags
& wxVCardPhoneNumber::Modem
)
2770 flagsStr
<< _T("modem ");
2772 if ( flags
& wxVCardPhoneNumber::Home
)
2774 flagsStr
<< _T("home ");
2776 if ( flags
& wxVCardPhoneNumber::Work
)
2778 flagsStr
<< _T("work ");
2781 printf("Phone number %u:\n"
2786 phone
->GetNumber().c_str()
2790 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2794 static void TestVCardRead()
2796 puts("*** Testing wxVCard reading ***\n");
2798 wxVCard
vcard(_T("vcard.vcf"));
2799 if ( !vcard
.IsOk() )
2801 puts("ERROR: couldn't load vCard.");
2805 // read individual vCard properties
2806 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2810 vcObj
->GetValue(&value
);
2815 value
= _T("<none>");
2818 printf("Full name retrieved directly: %s\n", value
.c_str());
2821 if ( !vcard
.GetFullName(&value
) )
2823 value
= _T("<none>");
2826 printf("Full name from wxVCard API: %s\n", value
.c_str());
2828 // now show how to deal with multiply occuring properties
2829 DumpVCardAddresses(vcard
);
2830 DumpVCardPhoneNumbers(vcard
);
2832 // and finally show all
2833 puts("\nNow dumping the entire vCard:\n"
2834 "-----------------------------\n");
2836 DumpVObject(0, vcard
);
2840 static void TestVCardWrite()
2842 puts("*** Testing wxVCard writing ***\n");
2845 if ( !vcard
.IsOk() )
2847 puts("ERROR: couldn't create vCard.");
2852 vcard
.SetName("Zeitlin", "Vadim");
2853 vcard
.SetFullName("Vadim Zeitlin");
2854 vcard
.SetOrganization("wxWindows", "R&D");
2856 // just dump the vCard back
2857 puts("Entire vCard follows:\n");
2858 puts(vcard
.Write());
2862 #endif // TEST_VCARD
2864 // ----------------------------------------------------------------------------
2865 // wide char (Unicode) support
2866 // ----------------------------------------------------------------------------
2870 #include <wx/strconv.h>
2871 #include <wx/fontenc.h>
2872 #include <wx/encconv.h>
2873 #include <wx/buffer.h>
2875 static void TestUtf8()
2877 puts("*** Testing UTF8 support ***\n");
2879 static const char textInUtf8
[] =
2881 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2882 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2883 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2884 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2885 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2886 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2887 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2892 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2894 puts("ERROR: UTF-8 decoding failed.");
2898 // using wxEncodingConverter
2900 wxEncodingConverter ec
;
2901 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2902 ec
.Convert(wbuf
, buf
);
2903 #else // using wxCSConv
2904 wxCSConv
conv(_T("koi8-r"));
2905 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2907 puts("ERROR: conversion to KOI8-R failed.");
2912 printf("The resulting string (in koi8-r): %s\n", buf
);
2916 #endif // TEST_WCHAR
2918 // ----------------------------------------------------------------------------
2920 // ----------------------------------------------------------------------------
2924 #include "wx/filesys.h"
2925 #include "wx/fs_zip.h"
2926 #include "wx/zipstrm.h"
2928 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2930 static void TestZipStreamRead()
2932 puts("*** Testing ZIP reading ***\n");
2934 static const wxChar
*filename
= _T("foo");
2935 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2936 printf("Archive size: %u\n", istr
.GetSize());
2938 printf("Dumping the file '%s':\n", filename
);
2939 while ( !istr
.Eof() )
2941 putchar(istr
.GetC());
2945 puts("\n----- done ------");
2948 static void DumpZipDirectory(wxFileSystem
& fs
,
2949 const wxString
& dir
,
2950 const wxString
& indent
)
2952 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2953 TESTFILE_ZIP
, dir
.c_str());
2954 wxString wildcard
= prefix
+ _T("/*");
2956 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
2957 while ( !dirname
.empty() )
2959 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
2961 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2966 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
2968 DumpZipDirectory(fs
, dirname
,
2969 indent
+ wxString(_T(' '), 4));
2971 dirname
= fs
.FindNext();
2974 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
2975 while ( !filename
.empty() )
2977 if ( !filename
.StartsWith(prefix
, &filename
) )
2979 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
2984 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
2986 filename
= fs
.FindNext();
2990 static void TestZipFileSystem()
2992 puts("*** Testing ZIP file system ***\n");
2994 wxFileSystem::AddHandler(new wxZipFSHandler
);
2996 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
2998 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3003 // ----------------------------------------------------------------------------
3005 // ----------------------------------------------------------------------------
3009 #include <wx/zstream.h>
3010 #include <wx/wfstream.h>
3012 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3013 static const char *TEST_DATA
= "hello and hello again";
3015 static void TestZlibStreamWrite()
3017 puts("*** Testing Zlib stream reading ***\n");
3019 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3020 wxZlibOutputStream
ostr(fileOutStream
, 0);
3021 printf("Compressing the test string... ");
3022 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3025 puts("(ERROR: failed)");
3032 puts("\n----- done ------");
3035 static void TestZlibStreamRead()
3037 puts("*** Testing Zlib stream reading ***\n");
3039 wxFileInputStream
fileInStream(FILENAME_GZ
);
3040 wxZlibInputStream
istr(fileInStream
);
3041 printf("Archive size: %u\n", istr
.GetSize());
3043 puts("Dumping the file:");
3044 while ( !istr
.Eof() )
3046 putchar(istr
.GetC());
3050 puts("\n----- done ------");
3055 // ----------------------------------------------------------------------------
3057 // ----------------------------------------------------------------------------
3059 #ifdef TEST_DATETIME
3063 #include <wx/date.h>
3065 #include <wx/datetime.h>
3070 wxDateTime::wxDateTime_t day
;
3071 wxDateTime::Month month
;
3073 wxDateTime::wxDateTime_t hour
, min
, sec
;
3075 wxDateTime::WeekDay wday
;
3076 time_t gmticks
, ticks
;
3078 void Init(const wxDateTime::Tm
& tm
)
3087 gmticks
= ticks
= -1;
3090 wxDateTime
DT() const
3091 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3093 bool SameDay(const wxDateTime::Tm
& tm
) const
3095 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3098 wxString
Format() const
3101 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3103 wxDateTime::GetMonthName(month
).c_str(),
3105 abs(wxDateTime::ConvertYearToBC(year
)),
3106 year
> 0 ? "AD" : "BC");
3110 wxString
FormatDate() const
3113 s
.Printf("%02d-%s-%4d%s",
3115 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3116 abs(wxDateTime::ConvertYearToBC(year
)),
3117 year
> 0 ? "AD" : "BC");
3122 static const Date testDates
[] =
3124 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3125 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3126 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3127 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3128 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3129 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3130 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3131 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3132 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3133 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3134 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3135 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3136 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3137 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3138 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3141 // this test miscellaneous static wxDateTime functions
3142 static void TestTimeStatic()
3144 puts("\n*** wxDateTime static methods test ***");
3146 // some info about the current date
3147 int year
= wxDateTime::GetCurrentYear();
3148 printf("Current year %d is %sa leap one and has %d days.\n",
3150 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3151 wxDateTime::GetNumberOfDays(year
));
3153 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3154 printf("Current month is '%s' ('%s') and it has %d days\n",
3155 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3156 wxDateTime::GetMonthName(month
).c_str(),
3157 wxDateTime::GetNumberOfDays(month
));
3160 static const size_t nYears
= 5;
3161 static const size_t years
[2][nYears
] =
3163 // first line: the years to test
3164 { 1990, 1976, 2000, 2030, 1984, },
3166 // second line: TRUE if leap, FALSE otherwise
3167 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3170 for ( size_t n
= 0; n
< nYears
; n
++ )
3172 int year
= years
[0][n
];
3173 bool should
= years
[1][n
] != 0,
3174 is
= wxDateTime::IsLeapYear(year
);
3176 printf("Year %d is %sa leap year (%s)\n",
3179 should
== is
? "ok" : "ERROR");
3181 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3185 // test constructing wxDateTime objects
3186 static void TestTimeSet()
3188 puts("\n*** wxDateTime construction test ***");
3190 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3192 const Date
& d1
= testDates
[n
];
3193 wxDateTime dt
= d1
.DT();
3196 d2
.Init(dt
.GetTm());
3198 wxString s1
= d1
.Format(),
3201 printf("Date: %s == %s (%s)\n",
3202 s1
.c_str(), s2
.c_str(),
3203 s1
== s2
? "ok" : "ERROR");
3207 // test time zones stuff
3208 static void TestTimeZones()
3210 puts("\n*** wxDateTime timezone test ***");
3212 wxDateTime now
= wxDateTime::Now();
3214 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3215 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3216 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3217 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3218 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3219 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3221 wxDateTime::Tm tm
= now
.GetTm();
3222 if ( wxDateTime(tm
) != now
)
3224 printf("ERROR: got %s instead of %s\n",
3225 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3229 // test some minimal support for the dates outside the standard range
3230 static void TestTimeRange()
3232 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3234 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3236 printf("Unix epoch:\t%s\n",
3237 wxDateTime(2440587.5).Format(fmt
).c_str());
3238 printf("Feb 29, 0: \t%s\n",
3239 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3240 printf("JDN 0: \t%s\n",
3241 wxDateTime(0.0).Format(fmt
).c_str());
3242 printf("Jan 1, 1AD:\t%s\n",
3243 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3244 printf("May 29, 2099:\t%s\n",
3245 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3248 static void TestTimeTicks()
3250 puts("\n*** wxDateTime ticks test ***");
3252 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3254 const Date
& d
= testDates
[n
];
3255 if ( d
.ticks
== -1 )
3258 wxDateTime dt
= d
.DT();
3259 long ticks
= (dt
.GetValue() / 1000).ToLong();
3260 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3261 if ( ticks
== d
.ticks
)
3267 printf(" (ERROR: should be %ld, delta = %ld)\n",
3268 d
.ticks
, ticks
- d
.ticks
);
3271 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3272 ticks
= (dt
.GetValue() / 1000).ToLong();
3273 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3274 if ( ticks
== d
.gmticks
)
3280 printf(" (ERROR: should be %ld, delta = %ld)\n",
3281 d
.gmticks
, ticks
- d
.gmticks
);
3288 // test conversions to JDN &c
3289 static void TestTimeJDN()
3291 puts("\n*** wxDateTime to JDN test ***");
3293 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3295 const Date
& d
= testDates
[n
];
3296 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3297 double jdn
= dt
.GetJulianDayNumber();
3299 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3306 printf(" (ERROR: should be %f, delta = %f)\n",
3307 d
.jdn
, jdn
- d
.jdn
);
3312 // test week days computation
3313 static void TestTimeWDays()
3315 puts("\n*** wxDateTime weekday test ***");
3317 // test GetWeekDay()
3319 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3321 const Date
& d
= testDates
[n
];
3322 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3324 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3327 wxDateTime::GetWeekDayName(wday
).c_str());
3328 if ( wday
== d
.wday
)
3334 printf(" (ERROR: should be %s)\n",
3335 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3341 // test SetToWeekDay()
3342 struct WeekDateTestData
3344 Date date
; // the real date (precomputed)
3345 int nWeek
; // its week index in the month
3346 wxDateTime::WeekDay wday
; // the weekday
3347 wxDateTime::Month month
; // the month
3348 int year
; // and the year
3350 wxString
Format() const
3353 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3355 case 1: which
= "first"; break;
3356 case 2: which
= "second"; break;
3357 case 3: which
= "third"; break;
3358 case 4: which
= "fourth"; break;
3359 case 5: which
= "fifth"; break;
3361 case -1: which
= "last"; break;
3366 which
+= " from end";
3369 s
.Printf("The %s %s of %s in %d",
3371 wxDateTime::GetWeekDayName(wday
).c_str(),
3372 wxDateTime::GetMonthName(month
).c_str(),
3379 // the array data was generated by the following python program
3381 from DateTime import *
3382 from whrandom import *
3383 from string import *
3385 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3386 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3388 week = DateTimeDelta(7)
3391 year = randint(1900, 2100)
3392 month = randint(1, 12)
3393 day = randint(1, 28)
3394 dt = DateTime(year, month, day)
3395 wday = dt.day_of_week
3397 countFromEnd = choice([-1, 1])
3400 while dt.month is month:
3401 dt = dt - countFromEnd * week
3402 weekNum = weekNum + countFromEnd
3404 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3406 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3407 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3410 static const WeekDateTestData weekDatesTestData
[] =
3412 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3413 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3414 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3415 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3416 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3417 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3418 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3419 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3420 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3421 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3422 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3423 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3424 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3425 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3426 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3427 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3428 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3429 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3430 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3431 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3434 static const char *fmt
= "%d-%b-%Y";
3437 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3439 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3441 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3443 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3445 const Date
& d
= wd
.date
;
3446 if ( d
.SameDay(dt
.GetTm()) )
3452 dt
.Set(d
.day
, d
.month
, d
.year
);
3454 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3459 // test the computation of (ISO) week numbers
3460 static void TestTimeWNumber()
3462 puts("\n*** wxDateTime week number test ***");
3464 struct WeekNumberTestData
3466 Date date
; // the date
3467 wxDateTime::wxDateTime_t week
; // the week number in the year
3468 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3469 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3470 wxDateTime::wxDateTime_t dnum
; // day number in the year
3473 // data generated with the following python script:
3475 from DateTime import *
3476 from whrandom import *
3477 from string import *
3479 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3480 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3482 def GetMonthWeek(dt):
3483 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3484 if weekNumMonth < 0:
3485 weekNumMonth = weekNumMonth + 53
3488 def GetLastSundayBefore(dt):
3489 if dt.iso_week[2] == 7:
3492 return dt - DateTimeDelta(dt.iso_week[2])
3495 year = randint(1900, 2100)
3496 month = randint(1, 12)
3497 day = randint(1, 28)
3498 dt = DateTime(year, month, day)
3499 dayNum = dt.day_of_year
3500 weekNum = dt.iso_week[1]
3501 weekNumMonth = GetMonthWeek(dt)
3504 dtSunday = GetLastSundayBefore(dt)
3506 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3507 weekNumMonth2 = weekNumMonth2 + 1
3508 dtSunday = dtSunday - DateTimeDelta(7)
3510 data = { 'day': rjust(`day`, 2), \
3511 'month': monthNames[month - 1], \
3513 'weekNum': rjust(`weekNum`, 2), \
3514 'weekNumMonth': weekNumMonth, \
3515 'weekNumMonth2': weekNumMonth2, \
3516 'dayNum': rjust(`dayNum`, 3) }
3518 print " { { %(day)s, "\
3519 "wxDateTime::%(month)s, "\
3522 "%(weekNumMonth)s, "\
3523 "%(weekNumMonth2)s, "\
3524 "%(dayNum)s }," % data
3527 static const WeekNumberTestData weekNumberTestDates
[] =
3529 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3530 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3531 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3532 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3533 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3534 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3535 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3536 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3537 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3538 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3539 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3540 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3541 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3542 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3543 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3544 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3545 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3546 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3547 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3548 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3551 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3553 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3554 const Date
& d
= wn
.date
;
3556 wxDateTime dt
= d
.DT();
3558 wxDateTime::wxDateTime_t
3559 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3560 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3561 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3562 dnum
= dt
.GetDayOfYear();
3564 printf("%s: the day number is %d",
3565 d
.FormatDate().c_str(), dnum
);
3566 if ( dnum
== wn
.dnum
)
3572 printf(" (ERROR: should be %d)", wn
.dnum
);
3575 printf(", week in month is %d", wmon
);
3576 if ( wmon
== wn
.wmon
)
3582 printf(" (ERROR: should be %d)", wn
.wmon
);
3585 printf(" or %d", wmon2
);
3586 if ( wmon2
== wn
.wmon2
)
3592 printf(" (ERROR: should be %d)", wn
.wmon2
);
3595 printf(", week in year is %d", week
);
3596 if ( week
== wn
.week
)
3602 printf(" (ERROR: should be %d)\n", wn
.week
);
3607 // test DST calculations
3608 static void TestTimeDST()
3610 puts("\n*** wxDateTime DST test ***");
3612 printf("DST is%s in effect now.\n\n",
3613 wxDateTime::Now().IsDST() ? "" : " not");
3615 // taken from http://www.energy.ca.gov/daylightsaving.html
3616 static const Date datesDST
[2][2004 - 1900 + 1] =
3619 { 1, wxDateTime::Apr
, 1990 },
3620 { 7, wxDateTime::Apr
, 1991 },
3621 { 5, wxDateTime::Apr
, 1992 },
3622 { 4, wxDateTime::Apr
, 1993 },
3623 { 3, wxDateTime::Apr
, 1994 },
3624 { 2, wxDateTime::Apr
, 1995 },
3625 { 7, wxDateTime::Apr
, 1996 },
3626 { 6, wxDateTime::Apr
, 1997 },
3627 { 5, wxDateTime::Apr
, 1998 },
3628 { 4, wxDateTime::Apr
, 1999 },
3629 { 2, wxDateTime::Apr
, 2000 },
3630 { 1, wxDateTime::Apr
, 2001 },
3631 { 7, wxDateTime::Apr
, 2002 },
3632 { 6, wxDateTime::Apr
, 2003 },
3633 { 4, wxDateTime::Apr
, 2004 },
3636 { 28, wxDateTime::Oct
, 1990 },
3637 { 27, wxDateTime::Oct
, 1991 },
3638 { 25, wxDateTime::Oct
, 1992 },
3639 { 31, wxDateTime::Oct
, 1993 },
3640 { 30, wxDateTime::Oct
, 1994 },
3641 { 29, wxDateTime::Oct
, 1995 },
3642 { 27, wxDateTime::Oct
, 1996 },
3643 { 26, wxDateTime::Oct
, 1997 },
3644 { 25, wxDateTime::Oct
, 1998 },
3645 { 31, wxDateTime::Oct
, 1999 },
3646 { 29, wxDateTime::Oct
, 2000 },
3647 { 28, wxDateTime::Oct
, 2001 },
3648 { 27, wxDateTime::Oct
, 2002 },
3649 { 26, wxDateTime::Oct
, 2003 },
3650 { 31, wxDateTime::Oct
, 2004 },
3655 for ( year
= 1990; year
< 2005; year
++ )
3657 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3658 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3660 printf("DST period in the US for year %d: from %s to %s",
3661 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3663 size_t n
= year
- 1990;
3664 const Date
& dBegin
= datesDST
[0][n
];
3665 const Date
& dEnd
= datesDST
[1][n
];
3667 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3673 printf(" (ERROR: should be %s %d to %s %d)\n",
3674 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3675 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3681 for ( year
= 1990; year
< 2005; year
++ )
3683 printf("DST period in Europe for year %d: from %s to %s\n",
3685 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3686 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3690 // test wxDateTime -> text conversion
3691 static void TestTimeFormat()
3693 puts("\n*** wxDateTime formatting test ***");
3695 // some information may be lost during conversion, so store what kind
3696 // of info should we recover after a round trip
3699 CompareNone
, // don't try comparing
3700 CompareBoth
, // dates and times should be identical
3701 CompareDate
, // dates only
3702 CompareTime
// time only
3707 CompareKind compareKind
;
3709 } formatTestFormats
[] =
3711 { CompareBoth
, "---> %c" },
3712 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3713 { CompareBoth
, "Date is %x, time is %X" },
3714 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3715 { CompareNone
, "The day of year: %j, the week of year: %W" },
3716 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3719 static const Date formatTestDates
[] =
3721 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3722 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3724 // this test can't work for other centuries because it uses two digit
3725 // years in formats, so don't even try it
3726 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3727 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3728 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3732 // an extra test (as it doesn't depend on date, don't do it in the loop)
3733 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3735 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3739 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3740 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3742 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3743 printf("%s", s
.c_str());
3745 // what can we recover?
3746 int kind
= formatTestFormats
[n
].compareKind
;
3750 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3753 // converion failed - should it have?
3754 if ( kind
== CompareNone
)
3757 puts(" (ERROR: conversion back failed)");
3761 // should have parsed the entire string
3762 puts(" (ERROR: conversion back stopped too soon)");
3766 bool equal
= FALSE
; // suppress compilaer warning
3774 equal
= dt
.IsSameDate(dt2
);
3778 equal
= dt
.IsSameTime(dt2
);
3784 printf(" (ERROR: got back '%s' instead of '%s')\n",
3785 dt2
.Format().c_str(), dt
.Format().c_str());
3796 // test text -> wxDateTime conversion
3797 static void TestTimeParse()
3799 puts("\n*** wxDateTime parse test ***");
3801 struct ParseTestData
3808 static const ParseTestData parseTestDates
[] =
3810 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3811 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3814 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3816 const char *format
= parseTestDates
[n
].format
;
3818 printf("%s => ", format
);
3821 if ( dt
.ParseRfc822Date(format
) )
3823 printf("%s ", dt
.Format().c_str());
3825 if ( parseTestDates
[n
].good
)
3827 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3834 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3839 puts("(ERROR: bad format)");
3844 printf("bad format (%s)\n",
3845 parseTestDates
[n
].good
? "ERROR" : "ok");
3850 static void TestDateTimeInteractive()
3852 puts("\n*** interactive wxDateTime tests ***");
3858 printf("Enter a date: ");
3859 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3862 // kill the last '\n'
3863 buf
[strlen(buf
) - 1] = 0;
3866 const char *p
= dt
.ParseDate(buf
);
3869 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3875 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3878 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3879 dt
.Format("%b %d, %Y").c_str(),
3881 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3882 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3883 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3886 puts("\n*** done ***");
3889 static void TestTimeMS()
3891 puts("*** testing millisecond-resolution support in wxDateTime ***");
3893 wxDateTime dt1
= wxDateTime::Now(),
3894 dt2
= wxDateTime::UNow();
3896 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3897 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3898 printf("Dummy loop: ");
3899 for ( int i
= 0; i
< 6000; i
++ )
3901 //for ( int j = 0; j < 10; j++ )
3904 s
.Printf("%g", sqrt(i
));
3913 dt2
= wxDateTime::UNow();
3914 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3916 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3918 puts("\n*** done ***");
3921 static void TestTimeArithmetics()
3923 puts("\n*** testing arithmetic operations on wxDateTime ***");
3925 static const struct ArithmData
3927 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3928 : span(sp
), name(nam
) { }
3932 } testArithmData
[] =
3934 ArithmData(wxDateSpan::Day(), "day"),
3935 ArithmData(wxDateSpan::Week(), "week"),
3936 ArithmData(wxDateSpan::Month(), "month"),
3937 ArithmData(wxDateSpan::Year(), "year"),
3938 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3941 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3943 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3945 wxDateSpan span
= testArithmData
[n
].span
;
3949 const char *name
= testArithmData
[n
].name
;
3950 printf("%s + %s = %s, %s - %s = %s\n",
3951 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3952 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3954 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3955 if ( dt1
- span
== dt
)
3961 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3964 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3965 if ( dt2
+ span
== dt
)
3971 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3974 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3975 if ( dt2
+ 2*span
== dt1
)
3981 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3988 static void TestTimeHolidays()
3990 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3992 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3993 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3994 dtEnd
= dtStart
.GetLastMonthDay();
3996 wxDateTimeArray hol
;
3997 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3999 const wxChar
*format
= "%d-%b-%Y (%a)";
4001 printf("All holidays between %s and %s:\n",
4002 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4004 size_t count
= hol
.GetCount();
4005 for ( size_t n
= 0; n
< count
; n
++ )
4007 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4013 static void TestTimeZoneBug()
4015 puts("\n*** testing for DST/timezone bug ***\n");
4017 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4018 for ( int i
= 0; i
< 31; i
++ )
4020 printf("Date %s: week day %s.\n",
4021 date
.Format(_T("%d-%m-%Y")).c_str(),
4022 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4024 date
+= wxDateSpan::Day();
4030 static void TestTimeSpanFormat()
4032 puts("\n*** wxTimeSpan tests ***");
4034 static const char *formats
[] =
4036 _T("(default) %H:%M:%S"),
4037 _T("%E weeks and %D days"),
4038 _T("%l milliseconds"),
4039 _T("(with ms) %H:%M:%S:%l"),
4040 _T("100%% of minutes is %M"), // test "%%"
4041 _T("%D days and %H hours"),
4042 _T("or also %S seconds"),
4045 wxTimeSpan
ts1(1, 2, 3, 4),
4047 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4049 printf("ts1 = %s\tts2 = %s\n",
4050 ts1
.Format(formats
[n
]).c_str(),
4051 ts2
.Format(formats
[n
]).c_str());
4059 // test compatibility with the old wxDate/wxTime classes
4060 static void TestTimeCompatibility()
4062 puts("\n*** wxDateTime compatibility test ***");
4064 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4065 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4067 double jdnNow
= wxDateTime::Now().GetJDN();
4068 long jdnMidnight
= (long)(jdnNow
- 0.5);
4069 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4071 jdnMidnight
= wxDate().Set().GetJulianDate();
4072 printf("wxDateTime for today: %s\n",
4073 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4075 int flags
= wxEUROPEAN
;//wxFULL;
4078 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4079 for ( int n
= 0; n
< 7; n
++ )
4081 printf("Previous %s is %s\n",
4082 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4083 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4089 #endif // TEST_DATETIME
4091 // ----------------------------------------------------------------------------
4093 // ----------------------------------------------------------------------------
4097 #include <wx/thread.h>
4099 static size_t gs_counter
= (size_t)-1;
4100 static wxCriticalSection gs_critsect
;
4101 static wxCondition gs_cond
;
4103 class MyJoinableThread
: public wxThread
4106 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4107 { m_n
= n
; Create(); }
4109 // thread execution starts here
4110 virtual ExitCode
Entry();
4116 wxThread::ExitCode
MyJoinableThread::Entry()
4118 unsigned long res
= 1;
4119 for ( size_t n
= 1; n
< m_n
; n
++ )
4123 // it's a loooong calculation :-)
4127 return (ExitCode
)res
;
4130 class MyDetachedThread
: public wxThread
4133 MyDetachedThread(size_t n
, char ch
)
4137 m_cancelled
= FALSE
;
4142 // thread execution starts here
4143 virtual ExitCode
Entry();
4146 virtual void OnExit();
4149 size_t m_n
; // number of characters to write
4150 char m_ch
; // character to write
4152 bool m_cancelled
; // FALSE if we exit normally
4155 wxThread::ExitCode
MyDetachedThread::Entry()
4158 wxCriticalSectionLocker
lock(gs_critsect
);
4159 if ( gs_counter
== (size_t)-1 )
4165 for ( size_t n
= 0; n
< m_n
; n
++ )
4167 if ( TestDestroy() )
4177 wxThread::Sleep(100);
4183 void MyDetachedThread::OnExit()
4185 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4187 wxCriticalSectionLocker
lock(gs_critsect
);
4188 if ( !--gs_counter
&& !m_cancelled
)
4192 void TestDetachedThreads()
4194 puts("\n*** Testing detached threads ***");
4196 static const size_t nThreads
= 3;
4197 MyDetachedThread
*threads
[nThreads
];
4199 for ( n
= 0; n
< nThreads
; n
++ )
4201 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4204 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4205 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4207 for ( n
= 0; n
< nThreads
; n
++ )
4212 // wait until all threads terminate
4218 void TestJoinableThreads()
4220 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4222 // calc 10! in the background
4223 MyJoinableThread
thread(10);
4226 printf("\nThread terminated with exit code %lu.\n",
4227 (unsigned long)thread
.Wait());
4230 void TestThreadSuspend()
4232 puts("\n*** Testing thread suspend/resume functions ***");
4234 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4238 // this is for this demo only, in a real life program we'd use another
4239 // condition variable which would be signaled from wxThread::Entry() to
4240 // tell us that the thread really started running - but here just wait a
4241 // bit and hope that it will be enough (the problem is, of course, that
4242 // the thread might still not run when we call Pause() which will result
4244 wxThread::Sleep(300);
4246 for ( size_t n
= 0; n
< 3; n
++ )
4250 puts("\nThread suspended");
4253 // don't sleep but resume immediately the first time
4254 wxThread::Sleep(300);
4256 puts("Going to resume the thread");
4261 puts("Waiting until it terminates now");
4263 // wait until the thread terminates
4269 void TestThreadDelete()
4271 // As above, using Sleep() is only for testing here - we must use some
4272 // synchronisation object instead to ensure that the thread is still
4273 // running when we delete it - deleting a detached thread which already
4274 // terminated will lead to a crash!
4276 puts("\n*** Testing thread delete function ***");
4278 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4282 puts("\nDeleted a thread which didn't start to run yet.");
4284 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4288 wxThread::Sleep(300);
4292 puts("\nDeleted a running thread.");
4294 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4298 wxThread::Sleep(300);
4304 puts("\nDeleted a sleeping thread.");
4306 MyJoinableThread
thread3(20);
4311 puts("\nDeleted a joinable thread.");
4313 MyJoinableThread
thread4(2);
4316 wxThread::Sleep(300);
4320 puts("\nDeleted a joinable thread which already terminated.");
4325 #endif // TEST_THREADS
4327 // ----------------------------------------------------------------------------
4329 // ----------------------------------------------------------------------------
4333 static void PrintArray(const char* name
, const wxArrayString
& array
)
4335 printf("Dump of the array '%s'\n", name
);
4337 size_t nCount
= array
.GetCount();
4338 for ( size_t n
= 0; n
< nCount
; n
++ )
4340 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4344 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4346 printf("Dump of the array '%s'\n", name
);
4348 size_t nCount
= array
.GetCount();
4349 for ( size_t n
= 0; n
< nCount
; n
++ )
4351 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4355 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4356 const wxString
& second
)
4358 return first
.length() - second
.length();
4361 int wxCMPFUNC_CONV
IntCompare(int *first
,
4364 return *first
- *second
;
4367 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4370 return *second
- *first
;
4373 static void TestArrayOfInts()
4375 puts("*** Testing wxArrayInt ***\n");
4386 puts("After sort:");
4390 puts("After reverse sort:");
4391 a
.Sort(IntRevCompare
);
4395 #include "wx/dynarray.h"
4397 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4398 #include "wx/arrimpl.cpp"
4399 WX_DEFINE_OBJARRAY(ArrayBars
);
4401 static void TestArrayOfObjects()
4403 puts("*** Testing wxObjArray ***\n");
4407 Bar
bar("second bar");
4409 printf("Initially: %u objects in the array, %u objects total.\n",
4410 bars
.GetCount(), Bar::GetNumber());
4412 bars
.Add(new Bar("first bar"));
4415 printf("Now: %u objects in the array, %u objects total.\n",
4416 bars
.GetCount(), Bar::GetNumber());
4420 printf("After Empty(): %u objects in the array, %u objects total.\n",
4421 bars
.GetCount(), Bar::GetNumber());
4424 printf("Finally: no more objects in the array, %u objects total.\n",
4428 #endif // TEST_ARRAYS
4430 // ----------------------------------------------------------------------------
4432 // ----------------------------------------------------------------------------
4436 #include "wx/timer.h"
4437 #include "wx/tokenzr.h"
4439 static void TestStringConstruction()
4441 puts("*** Testing wxString constructores ***");
4443 #define TEST_CTOR(args, res) \
4446 printf("wxString%s = %s ", #args, s.c_str()); \
4453 printf("(ERROR: should be %s)\n", res); \
4457 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4458 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4459 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4460 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4462 static const wxChar
*s
= _T("?really!");
4463 const wxChar
*start
= wxStrchr(s
, _T('r'));
4464 const wxChar
*end
= wxStrchr(s
, _T('!'));
4465 TEST_CTOR((start
, end
), _T("really"));
4470 static void TestString()
4480 for (int i
= 0; i
< 1000000; ++i
)
4484 c
= "! How'ya doin'?";
4487 c
= "Hello world! What's up?";
4492 printf ("TestString elapsed time: %ld\n", sw
.Time());
4495 static void TestPChar()
4503 for (int i
= 0; i
< 1000000; ++i
)
4505 strcpy (a
, "Hello");
4506 strcpy (b
, " world");
4507 strcpy (c
, "! How'ya doin'?");
4510 strcpy (c
, "Hello world! What's up?");
4511 if (strcmp (c
, a
) == 0)
4515 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4518 static void TestStringSub()
4520 wxString
s("Hello, world!");
4522 puts("*** Testing wxString substring extraction ***");
4524 printf("String = '%s'\n", s
.c_str());
4525 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4526 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4527 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4528 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4529 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4530 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4532 static const wxChar
*prefixes
[] =
4536 _T("Hello, world!"),
4537 _T("Hello, world!!!"),
4543 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4545 wxString prefix
= prefixes
[n
], rest
;
4546 bool rc
= s
.StartsWith(prefix
, &rest
);
4547 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4550 printf(" (the rest is '%s')\n", rest
.c_str());
4561 static void TestStringFormat()
4563 puts("*** Testing wxString formatting ***");
4566 s
.Printf("%03d", 18);
4568 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4569 printf("Number 18: %s\n", s
.c_str());
4574 // returns "not found" for npos, value for all others
4575 static wxString
PosToString(size_t res
)
4577 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4578 : wxString::Format(_T("%u"), res
);
4582 static void TestStringFind()
4584 puts("*** Testing wxString find() functions ***");
4586 static const wxChar
*strToFind
= _T("ell");
4587 static const struct StringFindTest
4591 result
; // of searching "ell" in str
4594 { _T("Well, hello world"), 0, 1 },
4595 { _T("Well, hello world"), 6, 7 },
4596 { _T("Well, hello world"), 9, wxString::npos
},
4599 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4601 const StringFindTest
& ft
= findTestData
[n
];
4602 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4604 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4605 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4607 size_t resTrue
= ft
.result
;
4608 if ( res
== resTrue
)
4614 printf(_T("(ERROR: should be %s)\n"),
4615 PosToString(resTrue
).c_str());
4622 static void TestStringTokenizer()
4624 puts("*** Testing wxStringTokenizer ***");
4626 static const wxChar
*modeNames
[] =
4630 _T("return all empty"),
4635 static const struct StringTokenizerTest
4637 const wxChar
*str
; // string to tokenize
4638 const wxChar
*delims
; // delimiters to use
4639 size_t count
; // count of token
4640 wxStringTokenizerMode mode
; // how should we tokenize it
4641 } tokenizerTestData
[] =
4643 { _T(""), _T(" "), 0 },
4644 { _T("Hello, world"), _T(" "), 2 },
4645 { _T("Hello, world "), _T(" "), 2 },
4646 { _T("Hello, world"), _T(","), 2 },
4647 { _T("Hello, world!"), _T(",!"), 2 },
4648 { _T("Hello,, world!"), _T(",!"), 3 },
4649 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4650 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4651 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4652 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4653 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4654 { _T("01/02/99"), _T("/-"), 3 },
4655 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4658 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4660 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4661 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4663 size_t count
= tkz
.CountTokens();
4664 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4665 MakePrintable(tt
.str
).c_str(),
4667 MakePrintable(tt
.delims
).c_str(),
4668 modeNames
[tkz
.GetMode()]);
4669 if ( count
== tt
.count
)
4675 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4680 // if we emulate strtok(), check that we do it correctly
4681 wxChar
*buf
, *s
= NULL
, *last
;
4683 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4685 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4686 wxStrcpy(buf
, tt
.str
);
4688 s
= wxStrtok(buf
, tt
.delims
, &last
);
4695 // now show the tokens themselves
4697 while ( tkz
.HasMoreTokens() )
4699 wxString token
= tkz
.GetNextToken();
4701 printf(_T("\ttoken %u: '%s'"),
4703 MakePrintable(token
).c_str());
4713 printf(" (ERROR: should be %s)\n", s
);
4716 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4720 // nothing to compare with
4725 if ( count2
!= count
)
4727 puts(_T("\tERROR: token count mismatch"));
4736 static void TestStringReplace()
4738 puts("*** Testing wxString::replace ***");
4740 static const struct StringReplaceTestData
4742 const wxChar
*original
; // original test string
4743 size_t start
, len
; // the part to replace
4744 const wxChar
*replacement
; // the replacement string
4745 const wxChar
*result
; // and the expected result
4746 } stringReplaceTestData
[] =
4748 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4749 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4750 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4751 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4752 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4755 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4757 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4759 wxString original
= data
.original
;
4760 original
.replace(data
.start
, data
.len
, data
.replacement
);
4762 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4763 data
.original
, data
.start
, data
.len
, data
.replacement
,
4766 if ( original
== data
.result
)
4772 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4779 static void TestStringMatch()
4781 wxPuts(_T("*** Testing wxString::Matches() ***"));
4783 static const struct StringMatchTestData
4786 const wxChar
*wildcard
;
4788 } stringMatchTestData
[] =
4790 { _T("foobar"), _T("foo*"), 1 },
4791 { _T("foobar"), _T("*oo*"), 1 },
4792 { _T("foobar"), _T("*bar"), 1 },
4793 { _T("foobar"), _T("??????"), 1 },
4794 { _T("foobar"), _T("f??b*"), 1 },
4795 { _T("foobar"), _T("f?b*"), 0 },
4796 { _T("foobar"), _T("*goo*"), 0 },
4797 { _T("foobar"), _T("*foo"), 0 },
4798 { _T("foobarfoo"), _T("*foo"), 1 },
4799 { _T(""), _T("*"), 1 },
4800 { _T(""), _T("?"), 0 },
4803 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4805 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4806 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4807 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4809 matches
? _T("matches") : _T("doesn't match"),
4811 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4817 #endif // TEST_STRINGS
4819 // ----------------------------------------------------------------------------
4821 // ----------------------------------------------------------------------------
4823 int main(int argc
, char **argv
)
4825 wxInitializer initializer
;
4828 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4833 #ifdef TEST_SNGLINST
4834 wxSingleInstanceChecker checker
;
4835 if ( checker
.Create(_T(".wxconsole.lock")) )
4837 if ( checker
.IsAnotherRunning() )
4839 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4844 // wait some time to give time to launch another instance
4845 wxPrintf(_T("Press \"Enter\" to continue..."));
4848 else // failed to create
4850 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4852 #endif // TEST_SNGLINST
4856 #endif // TEST_CHARSET
4859 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4861 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4862 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4864 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4865 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4866 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
4867 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
4869 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4870 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4875 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4877 parser
.AddOption("project_name", "", "full path to project file",
4878 wxCMD_LINE_VAL_STRING
,
4879 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4881 switch ( parser
.Parse() )
4884 wxLogMessage("Help was given, terminating.");
4888 ShowCmdLine(parser
);
4892 wxLogMessage("Syntax error detected, aborting.");
4895 #endif // TEST_CMDLINE
4903 TestStringConstruction();
4906 TestStringTokenizer();
4907 TestStringReplace();
4910 #endif // TEST_STRINGS
4923 puts("*** Initially:");
4925 PrintArray("a1", a1
);
4927 wxArrayString
a2(a1
);
4928 PrintArray("a2", a2
);
4930 wxSortedArrayString
a3(a1
);
4931 PrintArray("a3", a3
);
4933 puts("*** After deleting a string from a1");
4936 PrintArray("a1", a1
);
4937 PrintArray("a2", a2
);
4938 PrintArray("a3", a3
);
4940 puts("*** After reassigning a1 to a2 and a3");
4942 PrintArray("a2", a2
);
4943 PrintArray("a3", a3
);
4945 puts("*** After sorting a1");
4947 PrintArray("a1", a1
);
4949 puts("*** After sorting a1 in reverse order");
4951 PrintArray("a1", a1
);
4953 puts("*** After sorting a1 by the string length");
4954 a1
.Sort(StringLenCompare
);
4955 PrintArray("a1", a1
);
4957 TestArrayOfObjects();
4960 #endif // TEST_ARRAYS
4968 #ifdef TEST_DLLLOADER
4970 #endif // TEST_DLLLOADER
4974 #endif // TEST_ENVIRON
4978 #endif // TEST_EXECUTE
4980 #ifdef TEST_FILECONF
4982 #endif // TEST_FILECONF
4990 #endif // TEST_LOCALE
4994 for ( size_t n
= 0; n
< 8000; n
++ )
4996 s
<< (char)('A' + (n
% 26));
5000 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5002 // this one shouldn't be truncated
5005 // but this one will because log functions use fixed size buffer
5006 // (note that it doesn't need '\n' at the end neither - will be added
5008 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5020 #ifdef TEST_FILENAME
5021 TestFileNameSplit();
5024 TestFileNameConstruction();
5026 TestFileNameComparison();
5027 TestFileNameOperations();
5029 #endif // TEST_FILENAME
5032 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5033 if ( TestFtpConnect() )
5044 TestFtpInteractive();
5046 //else: connecting to the FTP server failed
5053 int nCPUs
= wxThread::GetCPUCount();
5054 printf("This system has %d CPUs\n", nCPUs
);
5056 wxThread::SetConcurrency(nCPUs
);
5058 if ( argc
> 1 && argv
[1][0] == 't' )
5059 wxLog::AddTraceMask("thread");
5062 TestDetachedThreads();
5064 TestJoinableThreads();
5066 TestThreadSuspend();
5070 #endif // TEST_THREADS
5072 #ifdef TEST_LONGLONG
5073 // seed pseudo random generator
5074 srand((unsigned)time(NULL
));
5082 TestMultiplication();
5085 TestLongLongConversion();
5086 TestBitOperations();
5088 TestLongLongComparison();
5089 #endif // TEST_LONGLONG
5096 wxLog::AddTraceMask(_T("mime"));
5104 TestMimeAssociate();
5107 #ifdef TEST_INFO_FUNCTIONS
5110 #endif // TEST_INFO_FUNCTIONS
5112 #ifdef TEST_PATHLIST
5114 #endif // TEST_PATHLIST
5118 #endif // TEST_REGCONF
5121 // TODO: write a real test using src/regex/tests file
5126 TestRegExSubmatch();
5127 TestRegExInteractive();
5129 TestRegExReplacement();
5130 #endif // TEST_REGEX
5132 #ifdef TEST_REGISTRY
5135 TestRegistryAssociation();
5136 #endif // TEST_REGISTRY
5144 #endif // TEST_SOCKETS
5150 #endif // TEST_STREAMS
5154 #endif // TEST_TIMER
5156 #ifdef TEST_DATETIME
5169 TestTimeArithmetics();
5176 TestTimeSpanFormat();
5178 TestDateTimeInteractive();
5179 #endif // TEST_DATETIME
5182 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5184 #endif // TEST_USLEEP
5190 #endif // TEST_VCARD
5194 #endif // TEST_WCHAR
5198 TestZipStreamRead();
5199 TestZipFileSystem();
5204 TestZlibStreamWrite();
5205 TestZlibStreamRead();