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
47 //#define TEST_DATETIME
49 //#define TEST_DLLLOADER
50 //#define TEST_ENVIRON
51 //#define TEST_EXECUTE
53 //#define TEST_FILECONF
54 //#define TEST_FILENAME
57 //#define TEST_INFO_FUNCTIONS
61 //#define TEST_LONGLONG
63 //#define TEST_PATHLIST
64 //#define TEST_REGCONF
66 //#define TEST_REGISTRY
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 TestDiskInfo()
1369 puts("*** Testing wxGetDiskSpace() ***");
1374 printf("\nEnter a directory name: ");
1375 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1378 // kill the last '\n'
1379 pathname
[strlen(pathname
) - 1] = 0;
1381 wxLongLong total
, free
;
1382 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1384 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1388 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1389 (total
/ 1024).ToString().c_str(),
1390 (free
/ 1024).ToString().c_str(),
1396 static void TestOsInfo()
1398 puts("*** Testing OS info functions ***\n");
1401 wxGetOsVersion(&major
, &minor
);
1402 printf("Running under: %s, version %d.%d\n",
1403 wxGetOsDescription().c_str(), major
, minor
);
1405 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1407 printf("Host name is %s (%s).\n",
1408 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1413 static void TestUserInfo()
1415 puts("*** Testing user info functions ***\n");
1417 printf("User id is:\t%s\n", wxGetUserId().c_str());
1418 printf("User name is:\t%s\n", wxGetUserName().c_str());
1419 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1420 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1425 #endif // TEST_INFO_FUNCTIONS
1427 // ----------------------------------------------------------------------------
1429 // ----------------------------------------------------------------------------
1431 #ifdef TEST_LONGLONG
1433 #include <wx/longlong.h>
1434 #include <wx/timer.h>
1436 // make a 64 bit number from 4 16 bit ones
1437 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1439 // get a random 64 bit number
1440 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1442 static const long testLongs
[] =
1453 #if wxUSE_LONGLONG_WX
1454 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1455 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1456 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1457 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1458 #endif // wxUSE_LONGLONG_WX
1460 static void TestSpeed()
1462 static const long max
= 100000000;
1469 for ( n
= 0; n
< max
; n
++ )
1474 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1477 #if wxUSE_LONGLONG_NATIVE
1482 for ( n
= 0; n
< max
; n
++ )
1487 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1489 #endif // wxUSE_LONGLONG_NATIVE
1495 for ( n
= 0; n
< max
; n
++ )
1500 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1504 static void TestLongLongConversion()
1506 puts("*** Testing wxLongLong conversions ***\n");
1510 for ( size_t n
= 0; n
< 100000; n
++ )
1514 #if wxUSE_LONGLONG_NATIVE
1515 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1517 wxASSERT_MSG( a
== b
, "conversions failure" );
1519 puts("Can't do it without native long long type, test skipped.");
1522 #endif // wxUSE_LONGLONG_NATIVE
1524 if ( !(nTested
% 1000) )
1536 static void TestMultiplication()
1538 puts("*** Testing wxLongLong multiplication ***\n");
1542 for ( size_t n
= 0; n
< 100000; n
++ )
1547 #if wxUSE_LONGLONG_NATIVE
1548 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1549 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1551 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1552 #else // !wxUSE_LONGLONG_NATIVE
1553 puts("Can't do it without native long long type, test skipped.");
1556 #endif // wxUSE_LONGLONG_NATIVE
1558 if ( !(nTested
% 1000) )
1570 static void TestDivision()
1572 puts("*** Testing wxLongLong division ***\n");
1576 for ( size_t n
= 0; n
< 100000; n
++ )
1578 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1579 // multiplication will not overflow)
1580 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1582 // get a random long (not wxLongLong for now) to divide it with
1587 #if wxUSE_LONGLONG_NATIVE
1588 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1590 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1591 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1592 #else // !wxUSE_LONGLONG_NATIVE
1593 // verify the result
1594 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1595 #endif // wxUSE_LONGLONG_NATIVE
1597 if ( !(nTested
% 1000) )
1609 static void TestAddition()
1611 puts("*** Testing wxLongLong addition ***\n");
1615 for ( size_t n
= 0; n
< 100000; n
++ )
1621 #if wxUSE_LONGLONG_NATIVE
1622 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1623 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1624 "addition failure" );
1625 #else // !wxUSE_LONGLONG_NATIVE
1626 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1627 #endif // wxUSE_LONGLONG_NATIVE
1629 if ( !(nTested
% 1000) )
1641 static void TestBitOperations()
1643 puts("*** Testing wxLongLong bit operation ***\n");
1647 for ( size_t n
= 0; n
< 100000; n
++ )
1651 #if wxUSE_LONGLONG_NATIVE
1652 for ( size_t n
= 0; n
< 33; n
++ )
1655 #else // !wxUSE_LONGLONG_NATIVE
1656 puts("Can't do it without native long long type, test skipped.");
1659 #endif // wxUSE_LONGLONG_NATIVE
1661 if ( !(nTested
% 1000) )
1673 static void TestLongLongComparison()
1675 #if wxUSE_LONGLONG_WX
1676 puts("*** Testing wxLongLong comparison ***\n");
1678 static const long ls
[2] =
1684 wxLongLongWx lls
[2];
1688 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1692 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1694 res
= lls
[m
] > testLongs
[n
];
1695 printf("0x%lx > 0x%lx is %s (%s)\n",
1696 ls
[m
], testLongs
[n
], res
? "true" : "false",
1697 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1699 res
= lls
[m
] < testLongs
[n
];
1700 printf("0x%lx < 0x%lx is %s (%s)\n",
1701 ls
[m
], testLongs
[n
], res
? "true" : "false",
1702 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1704 res
= lls
[m
] == testLongs
[n
];
1705 printf("0x%lx == 0x%lx is %s (%s)\n",
1706 ls
[m
], testLongs
[n
], res
? "true" : "false",
1707 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1710 #endif // wxUSE_LONGLONG_WX
1713 static void TestLongLongPrint()
1715 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1717 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1719 wxLongLong ll
= testLongs
[n
];
1720 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1723 wxLongLong
ll(0x12345678, 0x87654321);
1724 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1727 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1733 #endif // TEST_LONGLONG
1735 // ----------------------------------------------------------------------------
1737 // ----------------------------------------------------------------------------
1739 #ifdef TEST_PATHLIST
1741 static void TestPathList()
1743 puts("*** Testing wxPathList ***\n");
1745 wxPathList pathlist
;
1746 pathlist
.AddEnvList("PATH");
1747 wxString path
= pathlist
.FindValidPath("ls");
1750 printf("ERROR: command not found in the path.\n");
1754 printf("Command found in the path as '%s'.\n", path
.c_str());
1758 #endif // TEST_PATHLIST
1760 // ----------------------------------------------------------------------------
1761 // regular expressions
1762 // ----------------------------------------------------------------------------
1766 #include <wx/regex.h>
1768 static void TestRegExCompile()
1770 wxPuts(_T("*** Testing RE compilation ***\n"));
1772 static struct RegExCompTestData
1774 const wxChar
*pattern
;
1776 } regExCompTestData
[] =
1778 { _T("foo"), TRUE
},
1779 { _T("foo("), FALSE
},
1780 { _T("foo(bar"), FALSE
},
1781 { _T("foo(bar)"), TRUE
},
1782 { _T("foo["), FALSE
},
1783 { _T("foo[bar"), FALSE
},
1784 { _T("foo[bar]"), TRUE
},
1785 { _T("foo{"), TRUE
},
1786 { _T("foo{1"), FALSE
},
1787 { _T("foo{bar"), TRUE
},
1788 { _T("foo{1}"), TRUE
},
1789 { _T("foo{1,2}"), TRUE
},
1790 { _T("foo{bar}"), TRUE
},
1791 { _T("foo*"), TRUE
},
1792 { _T("foo**"), FALSE
},
1793 { _T("foo+"), TRUE
},
1794 { _T("foo++"), FALSE
},
1795 { _T("foo?"), TRUE
},
1796 { _T("foo??"), FALSE
},
1797 { _T("foo?+"), FALSE
},
1801 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
1803 const RegExCompTestData
& data
= regExCompTestData
[n
];
1804 bool ok
= re
.Compile(data
.pattern
);
1806 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
1808 ok
? _T("") : _T("not "),
1809 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1813 static void TestRegExMatch()
1815 wxPuts(_T("*** Testing RE matching ***\n"));
1817 static struct RegExMatchTestData
1819 const wxChar
*pattern
;
1822 } regExMatchTestData
[] =
1824 { _T("foo"), _T("bar"), FALSE
},
1825 { _T("foo"), _T("foobar"), TRUE
},
1826 { _T("^foo"), _T("foobar"), TRUE
},
1827 { _T("^foo"), _T("barfoo"), FALSE
},
1828 { _T("bar$"), _T("barbar"), TRUE
},
1829 { _T("bar$"), _T("barbar "), FALSE
},
1832 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
1834 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
1836 wxRegEx
re(data
.pattern
);
1837 bool ok
= re
.Matches(data
.text
);
1839 wxPrintf(_T("'%s' %s %s (%s)\n"),
1841 ok
? _T("matches") : _T("doesn't match"),
1843 ok
== data
.correct
? _T("ok") : _T("ERROR"));
1847 static void TestRegExSubmatch()
1849 wxPuts(_T("*** Testing RE subexpressions ***\n"));
1851 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
1852 if ( !re
.IsValid() )
1854 wxPuts(_T("ERROR: compilation failed."));
1858 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
1860 if ( !re
.Matches(text
) )
1862 wxPuts(_T("ERROR: match expected."));
1866 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
1868 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
1869 re
.GetMatch(text
, 3).c_str(),
1870 re
.GetMatch(text
, 2).c_str(),
1871 re
.GetMatch(text
, 4).c_str(),
1872 re
.GetMatch(text
, 1).c_str());
1876 static void TestRegExReplacement()
1878 wxPuts(_T("*** Testing RE replacement ***"));
1880 static struct RegExReplTestData
1884 const wxChar
*result
;
1886 } regExReplTestData
[] =
1888 { _T("foo123"), _T("bar"), _T("bar"), 1 },
1889 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
1890 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
1891 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
1892 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
1893 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
1894 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
1897 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
1898 wxRegEx re
= pattern
;
1900 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
1902 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
1904 const RegExReplTestData
& data
= regExReplTestData
[n
];
1906 wxString text
= data
.text
;
1907 size_t nRepl
= re
.Replace(&text
, data
.repl
);
1909 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
1910 data
.text
, data
.repl
,
1911 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
1913 if ( text
== data
.result
&& nRepl
== data
.count
)
1919 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
1920 data
.count
, data
.result
);
1925 static void TestRegExInteractive()
1927 wxPuts(_T("*** Testing RE interactively ***"));
1932 printf("\nEnter a pattern: ");
1933 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1936 // kill the last '\n'
1937 pattern
[strlen(pattern
) - 1] = 0;
1940 if ( !re
.Compile(pattern
) )
1948 printf("Enter text to match: ");
1949 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
1952 // kill the last '\n'
1953 text
[strlen(text
) - 1] = 0;
1955 if ( !re
.Matches(text
) )
1957 printf("No match.\n");
1961 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
1964 for ( size_t n
= 1; ; n
++ )
1966 if ( !re
.GetMatch(&start
, &len
, n
) )
1971 printf("Subexpr %u matched '%s'\n",
1972 n
, wxString(text
+ start
, len
).c_str());
1979 #endif // TEST_REGEX
1981 // ----------------------------------------------------------------------------
1982 // registry and related stuff
1983 // ----------------------------------------------------------------------------
1985 // this is for MSW only
1988 #undef TEST_REGISTRY
1993 #include <wx/confbase.h>
1994 #include <wx/msw/regconf.h>
1996 static void TestRegConfWrite()
1998 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
1999 regconf
.Write(_T("Hello"), wxString(_T("world")));
2002 #endif // TEST_REGCONF
2004 #ifdef TEST_REGISTRY
2006 #include <wx/msw/registry.h>
2008 // I chose this one because I liked its name, but it probably only exists under
2010 static const wxChar
*TESTKEY
=
2011 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2013 static void TestRegistryRead()
2015 puts("*** testing registry reading ***");
2017 wxRegKey
key(TESTKEY
);
2018 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2021 puts("ERROR: test key can't be opened, aborting test.");
2026 size_t nSubKeys
, nValues
;
2027 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2029 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2032 printf("Enumerating values:\n");
2036 bool cont
= key
.GetFirstValue(value
, dummy
);
2039 printf("Value '%s': type ", value
.c_str());
2040 switch ( key
.GetValueType(value
) )
2042 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2043 case wxRegKey::Type_String
: printf("SZ"); break;
2044 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2045 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2046 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2047 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2048 default: printf("other (unknown)"); break;
2051 printf(", value = ");
2052 if ( key
.IsNumericValue(value
) )
2055 key
.QueryValue(value
, &val
);
2061 key
.QueryValue(value
, val
);
2062 printf("'%s'", val
.c_str());
2064 key
.QueryRawValue(value
, val
);
2065 printf(" (raw value '%s')", val
.c_str());
2070 cont
= key
.GetNextValue(value
, dummy
);
2074 static void TestRegistryAssociation()
2077 The second call to deleteself genertaes an error message, with a
2078 messagebox saying .flo is crucial to system operation, while the .ddf
2079 call also fails, but with no error message
2084 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2086 key
= "ddxf_auto_file" ;
2087 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2089 key
= "ddxf_auto_file" ;
2090 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2093 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2095 key
= "program \"%1\"" ;
2097 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2099 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2101 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2103 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2107 #endif // TEST_REGISTRY
2109 // ----------------------------------------------------------------------------
2111 // ----------------------------------------------------------------------------
2115 #include <wx/socket.h>
2116 #include <wx/protocol/protocol.h>
2117 #include <wx/protocol/http.h>
2119 static void TestSocketServer()
2121 puts("*** Testing wxSocketServer ***\n");
2123 static const int PORT
= 3000;
2128 wxSocketServer
*server
= new wxSocketServer(addr
);
2129 if ( !server
->Ok() )
2131 puts("ERROR: failed to bind");
2138 printf("Server: waiting for connection on port %d...\n", PORT
);
2140 wxSocketBase
*socket
= server
->Accept();
2143 puts("ERROR: wxSocketServer::Accept() failed.");
2147 puts("Server: got a client.");
2149 server
->SetTimeout(60); // 1 min
2151 while ( socket
->IsConnected() )
2157 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2159 // don't log error if the client just close the connection
2160 if ( socket
->IsConnected() )
2162 puts("ERROR: in wxSocket::Read.");
2182 printf("Server: got '%s'.\n", s
.c_str());
2183 if ( s
== _T("bye") )
2190 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2191 socket
->Write("\r\n", 2);
2192 printf("Server: wrote '%s'.\n", s
.c_str());
2195 puts("Server: lost a client.");
2200 // same as "delete server" but is consistent with GUI programs
2204 static void TestSocketClient()
2206 puts("*** Testing wxSocketClient ***\n");
2208 static const char *hostname
= "www.wxwindows.org";
2211 addr
.Hostname(hostname
);
2214 printf("--- Attempting to connect to %s:80...\n", hostname
);
2216 wxSocketClient client
;
2217 if ( !client
.Connect(addr
) )
2219 printf("ERROR: failed to connect to %s\n", hostname
);
2223 printf("--- Connected to %s:%u...\n",
2224 addr
.Hostname().c_str(), addr
.Service());
2228 // could use simply "GET" here I suppose
2230 wxString::Format("GET http://%s/\r\n", hostname
);
2231 client
.Write(cmdGet
, cmdGet
.length());
2232 printf("--- Sent command '%s' to the server\n",
2233 MakePrintable(cmdGet
).c_str());
2234 client
.Read(buf
, WXSIZEOF(buf
));
2235 printf("--- Server replied:\n%s", buf
);
2239 #endif // TEST_SOCKETS
2241 // ----------------------------------------------------------------------------
2243 // ----------------------------------------------------------------------------
2247 #include <wx/protocol/ftp.h>
2251 #define FTP_ANONYMOUS
2253 #ifdef FTP_ANONYMOUS
2254 static const char *directory
= "/pub";
2255 static const char *filename
= "welcome.msg";
2257 static const char *directory
= "/etc";
2258 static const char *filename
= "issue";
2261 static bool TestFtpConnect()
2263 puts("*** Testing FTP connect ***");
2265 #ifdef FTP_ANONYMOUS
2266 static const char *hostname
= "ftp.wxwindows.org";
2268 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2269 #else // !FTP_ANONYMOUS
2270 static const char *hostname
= "localhost";
2273 fgets(user
, WXSIZEOF(user
), stdin
);
2274 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2278 printf("Password for %s: ", password
);
2279 fgets(password
, WXSIZEOF(password
), stdin
);
2280 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2281 ftp
.SetPassword(password
);
2283 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2284 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2286 if ( !ftp
.Connect(hostname
) )
2288 printf("ERROR: failed to connect to %s\n", hostname
);
2294 printf("--- Connected to %s, current directory is '%s'\n",
2295 hostname
, ftp
.Pwd().c_str());
2301 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2302 static void TestFtpWuFtpd()
2305 static const char *hostname
= "ftp.eudora.com";
2306 if ( !ftp
.Connect(hostname
) )
2308 printf("ERROR: failed to connect to %s\n", hostname
);
2312 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2313 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2316 printf("ERROR: couldn't get input stream for %s\n", filename
);
2320 size_t size
= in
->StreamSize();
2321 printf("Reading file %s (%u bytes)...", filename
, size
);
2323 char *data
= new char[size
];
2324 if ( !in
->Read(data
, size
) )
2326 puts("ERROR: read error");
2330 printf("Successfully retrieved the file.\n");
2339 static void TestFtpList()
2341 puts("*** Testing wxFTP file listing ***\n");
2344 if ( !ftp
.ChDir(directory
) )
2346 printf("ERROR: failed to cd to %s\n", directory
);
2349 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2351 // test NLIST and LIST
2352 wxArrayString files
;
2353 if ( !ftp
.GetFilesList(files
) )
2355 puts("ERROR: failed to get NLIST of files");
2359 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2360 size_t count
= files
.GetCount();
2361 for ( size_t n
= 0; n
< count
; n
++ )
2363 printf("\t%s\n", files
[n
].c_str());
2365 puts("End of the file list");
2368 if ( !ftp
.GetDirList(files
) )
2370 puts("ERROR: failed to get LIST of files");
2374 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2375 size_t count
= files
.GetCount();
2376 for ( size_t n
= 0; n
< count
; n
++ )
2378 printf("\t%s\n", files
[n
].c_str());
2380 puts("End of the file list");
2383 if ( !ftp
.ChDir(_T("..")) )
2385 puts("ERROR: failed to cd to ..");
2388 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2391 static void TestFtpDownload()
2393 puts("*** Testing wxFTP download ***\n");
2396 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2399 printf("ERROR: couldn't get input stream for %s\n", filename
);
2403 size_t size
= in
->StreamSize();
2404 printf("Reading file %s (%u bytes)...", filename
, size
);
2407 char *data
= new char[size
];
2408 if ( !in
->Read(data
, size
) )
2410 puts("ERROR: read error");
2414 printf("\nContents of %s:\n%s\n", filename
, data
);
2422 static void TestFtpFileSize()
2424 puts("*** Testing FTP SIZE command ***");
2426 if ( !ftp
.ChDir(directory
) )
2428 printf("ERROR: failed to cd to %s\n", directory
);
2431 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2433 if ( ftp
.FileExists(filename
) )
2435 int size
= ftp
.GetFileSize(filename
);
2437 printf("ERROR: couldn't get size of '%s'\n", filename
);
2439 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2443 printf("ERROR: '%s' doesn't exist\n", filename
);
2447 static void TestFtpMisc()
2449 puts("*** Testing miscellaneous wxFTP functions ***");
2451 if ( ftp
.SendCommand("STAT") != '2' )
2453 puts("ERROR: STAT failed");
2457 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2460 if ( ftp
.SendCommand("HELP SITE") != '2' )
2462 puts("ERROR: HELP SITE failed");
2466 printf("The list of site-specific commands:\n\n%s\n",
2467 ftp
.GetLastResult().c_str());
2471 static void TestFtpInteractive()
2473 puts("\n*** Interactive wxFTP test ***");
2479 printf("Enter FTP command: ");
2480 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2483 // kill the last '\n'
2484 buf
[strlen(buf
) - 1] = 0;
2486 // special handling of LIST and NLST as they require data connection
2487 wxString
start(buf
, 4);
2489 if ( start
== "LIST" || start
== "NLST" )
2492 if ( strlen(buf
) > 4 )
2495 wxArrayString files
;
2496 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2498 printf("ERROR: failed to get %s of files\n", start
.c_str());
2502 printf("--- %s of '%s' under '%s':\n",
2503 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2504 size_t count
= files
.GetCount();
2505 for ( size_t n
= 0; n
< count
; n
++ )
2507 printf("\t%s\n", files
[n
].c_str());
2509 puts("--- End of the file list");
2514 char ch
= ftp
.SendCommand(buf
);
2515 printf("Command %s", ch
? "succeeded" : "failed");
2518 printf(" (return code %c)", ch
);
2521 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2525 puts("\n*** done ***");
2528 static void TestFtpUpload()
2530 puts("*** Testing wxFTP uploading ***\n");
2533 static const char *file1
= "test1";
2534 static const char *file2
= "test2";
2535 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2538 printf("--- Uploading to %s ---\n", file1
);
2539 out
->Write("First hello", 11);
2543 // send a command to check the remote file
2544 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2546 printf("ERROR: STAT %s failed\n", file1
);
2550 printf("STAT %s returned:\n\n%s\n",
2551 file1
, ftp
.GetLastResult().c_str());
2554 out
= ftp
.GetOutputStream(file2
);
2557 printf("--- Uploading to %s ---\n", file1
);
2558 out
->Write("Second hello", 12);
2565 // ----------------------------------------------------------------------------
2567 // ----------------------------------------------------------------------------
2571 #include <wx/wfstream.h>
2572 #include <wx/mstream.h>
2574 static void TestFileStream()
2576 puts("*** Testing wxFileInputStream ***");
2578 static const wxChar
*filename
= _T("testdata.fs");
2580 wxFileOutputStream
fsOut(filename
);
2581 fsOut
.Write("foo", 3);
2584 wxFileInputStream
fsIn(filename
);
2585 printf("File stream size: %u\n", fsIn
.GetSize());
2586 while ( !fsIn
.Eof() )
2588 putchar(fsIn
.GetC());
2591 if ( !wxRemoveFile(filename
) )
2593 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2596 puts("\n*** wxFileInputStream test done ***");
2599 static void TestMemoryStream()
2601 puts("*** Testing wxMemoryInputStream ***");
2604 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2606 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2607 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2608 while ( !memInpStream
.Eof() )
2610 putchar(memInpStream
.GetC());
2613 puts("\n*** wxMemoryInputStream test done ***");
2616 #endif // TEST_STREAMS
2618 // ----------------------------------------------------------------------------
2620 // ----------------------------------------------------------------------------
2624 #include <wx/timer.h>
2625 #include <wx/utils.h>
2627 static void TestStopWatch()
2629 puts("*** Testing wxStopWatch ***\n");
2632 printf("Sleeping 3 seconds...");
2634 printf("\telapsed time: %ldms\n", sw
.Time());
2637 printf("Sleeping 2 more seconds...");
2639 printf("\telapsed time: %ldms\n", sw
.Time());
2642 printf("And 3 more seconds...");
2644 printf("\telapsed time: %ldms\n", sw
.Time());
2647 puts("\nChecking for 'backwards clock' bug...");
2648 for ( size_t n
= 0; n
< 70; n
++ )
2652 for ( size_t m
= 0; m
< 100000; m
++ )
2654 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2656 puts("\ntime is negative - ERROR!");
2666 #endif // TEST_TIMER
2668 // ----------------------------------------------------------------------------
2670 // ----------------------------------------------------------------------------
2674 #include <wx/vcard.h>
2676 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2679 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2683 wxString(_T('\t'), level
).c_str(),
2684 vcObj
->GetName().c_str());
2687 switch ( vcObj
->GetType() )
2689 case wxVCardObject::String
:
2690 case wxVCardObject::UString
:
2693 vcObj
->GetValue(&val
);
2694 value
<< _T('"') << val
<< _T('"');
2698 case wxVCardObject::Int
:
2701 vcObj
->GetValue(&i
);
2702 value
.Printf(_T("%u"), i
);
2706 case wxVCardObject::Long
:
2709 vcObj
->GetValue(&l
);
2710 value
.Printf(_T("%lu"), l
);
2714 case wxVCardObject::None
:
2717 case wxVCardObject::Object
:
2718 value
= _T("<node>");
2722 value
= _T("<unknown value type>");
2726 printf(" = %s", value
.c_str());
2729 DumpVObject(level
+ 1, *vcObj
);
2732 vcObj
= vcard
.GetNextProp(&cookie
);
2736 static void DumpVCardAddresses(const wxVCard
& vcard
)
2738 puts("\nShowing all addresses from vCard:\n");
2742 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2746 int flags
= addr
->GetFlags();
2747 if ( flags
& wxVCardAddress::Domestic
)
2749 flagsStr
<< _T("domestic ");
2751 if ( flags
& wxVCardAddress::Intl
)
2753 flagsStr
<< _T("international ");
2755 if ( flags
& wxVCardAddress::Postal
)
2757 flagsStr
<< _T("postal ");
2759 if ( flags
& wxVCardAddress::Parcel
)
2761 flagsStr
<< _T("parcel ");
2763 if ( flags
& wxVCardAddress::Home
)
2765 flagsStr
<< _T("home ");
2767 if ( flags
& wxVCardAddress::Work
)
2769 flagsStr
<< _T("work ");
2772 printf("Address %u:\n"
2774 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2777 addr
->GetPostOffice().c_str(),
2778 addr
->GetExtAddress().c_str(),
2779 addr
->GetStreet().c_str(),
2780 addr
->GetLocality().c_str(),
2781 addr
->GetRegion().c_str(),
2782 addr
->GetPostalCode().c_str(),
2783 addr
->GetCountry().c_str()
2787 addr
= vcard
.GetNextAddress(&cookie
);
2791 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2793 puts("\nShowing all phone numbers from vCard:\n");
2797 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2801 int flags
= phone
->GetFlags();
2802 if ( flags
& wxVCardPhoneNumber::Voice
)
2804 flagsStr
<< _T("voice ");
2806 if ( flags
& wxVCardPhoneNumber::Fax
)
2808 flagsStr
<< _T("fax ");
2810 if ( flags
& wxVCardPhoneNumber::Cellular
)
2812 flagsStr
<< _T("cellular ");
2814 if ( flags
& wxVCardPhoneNumber::Modem
)
2816 flagsStr
<< _T("modem ");
2818 if ( flags
& wxVCardPhoneNumber::Home
)
2820 flagsStr
<< _T("home ");
2822 if ( flags
& wxVCardPhoneNumber::Work
)
2824 flagsStr
<< _T("work ");
2827 printf("Phone number %u:\n"
2832 phone
->GetNumber().c_str()
2836 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2840 static void TestVCardRead()
2842 puts("*** Testing wxVCard reading ***\n");
2844 wxVCard
vcard(_T("vcard.vcf"));
2845 if ( !vcard
.IsOk() )
2847 puts("ERROR: couldn't load vCard.");
2851 // read individual vCard properties
2852 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2856 vcObj
->GetValue(&value
);
2861 value
= _T("<none>");
2864 printf("Full name retrieved directly: %s\n", value
.c_str());
2867 if ( !vcard
.GetFullName(&value
) )
2869 value
= _T("<none>");
2872 printf("Full name from wxVCard API: %s\n", value
.c_str());
2874 // now show how to deal with multiply occuring properties
2875 DumpVCardAddresses(vcard
);
2876 DumpVCardPhoneNumbers(vcard
);
2878 // and finally show all
2879 puts("\nNow dumping the entire vCard:\n"
2880 "-----------------------------\n");
2882 DumpVObject(0, vcard
);
2886 static void TestVCardWrite()
2888 puts("*** Testing wxVCard writing ***\n");
2891 if ( !vcard
.IsOk() )
2893 puts("ERROR: couldn't create vCard.");
2898 vcard
.SetName("Zeitlin", "Vadim");
2899 vcard
.SetFullName("Vadim Zeitlin");
2900 vcard
.SetOrganization("wxWindows", "R&D");
2902 // just dump the vCard back
2903 puts("Entire vCard follows:\n");
2904 puts(vcard
.Write());
2908 #endif // TEST_VCARD
2910 // ----------------------------------------------------------------------------
2911 // wide char (Unicode) support
2912 // ----------------------------------------------------------------------------
2916 #include <wx/strconv.h>
2917 #include <wx/fontenc.h>
2918 #include <wx/encconv.h>
2919 #include <wx/buffer.h>
2921 static void TestUtf8()
2923 puts("*** Testing UTF8 support ***\n");
2925 static const char textInUtf8
[] =
2927 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
2928 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
2929 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
2930 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
2931 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
2932 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
2933 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
2938 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
2940 puts("ERROR: UTF-8 decoding failed.");
2944 // using wxEncodingConverter
2946 wxEncodingConverter ec
;
2947 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
2948 ec
.Convert(wbuf
, buf
);
2949 #else // using wxCSConv
2950 wxCSConv
conv(_T("koi8-r"));
2951 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
2953 puts("ERROR: conversion to KOI8-R failed.");
2958 printf("The resulting string (in koi8-r): %s\n", buf
);
2962 #endif // TEST_WCHAR
2964 // ----------------------------------------------------------------------------
2966 // ----------------------------------------------------------------------------
2970 #include "wx/filesys.h"
2971 #include "wx/fs_zip.h"
2972 #include "wx/zipstrm.h"
2974 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
2976 static void TestZipStreamRead()
2978 puts("*** Testing ZIP reading ***\n");
2980 static const wxChar
*filename
= _T("foo");
2981 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
2982 printf("Archive size: %u\n", istr
.GetSize());
2984 printf("Dumping the file '%s':\n", filename
);
2985 while ( !istr
.Eof() )
2987 putchar(istr
.GetC());
2991 puts("\n----- done ------");
2994 static void DumpZipDirectory(wxFileSystem
& fs
,
2995 const wxString
& dir
,
2996 const wxString
& indent
)
2998 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
2999 TESTFILE_ZIP
, dir
.c_str());
3000 wxString wildcard
= prefix
+ _T("/*");
3002 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3003 while ( !dirname
.empty() )
3005 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3007 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3012 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3014 DumpZipDirectory(fs
, dirname
,
3015 indent
+ wxString(_T(' '), 4));
3017 dirname
= fs
.FindNext();
3020 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3021 while ( !filename
.empty() )
3023 if ( !filename
.StartsWith(prefix
, &filename
) )
3025 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3030 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3032 filename
= fs
.FindNext();
3036 static void TestZipFileSystem()
3038 puts("*** Testing ZIP file system ***\n");
3040 wxFileSystem::AddHandler(new wxZipFSHandler
);
3042 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3044 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3049 // ----------------------------------------------------------------------------
3051 // ----------------------------------------------------------------------------
3055 #include <wx/zstream.h>
3056 #include <wx/wfstream.h>
3058 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3059 static const char *TEST_DATA
= "hello and hello again";
3061 static void TestZlibStreamWrite()
3063 puts("*** Testing Zlib stream reading ***\n");
3065 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3066 wxZlibOutputStream
ostr(fileOutStream
, 0);
3067 printf("Compressing the test string... ");
3068 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3071 puts("(ERROR: failed)");
3078 puts("\n----- done ------");
3081 static void TestZlibStreamRead()
3083 puts("*** Testing Zlib stream reading ***\n");
3085 wxFileInputStream
fileInStream(FILENAME_GZ
);
3086 wxZlibInputStream
istr(fileInStream
);
3087 printf("Archive size: %u\n", istr
.GetSize());
3089 puts("Dumping the file:");
3090 while ( !istr
.Eof() )
3092 putchar(istr
.GetC());
3096 puts("\n----- done ------");
3101 // ----------------------------------------------------------------------------
3103 // ----------------------------------------------------------------------------
3105 #ifdef TEST_DATETIME
3109 #include <wx/date.h>
3111 #include <wx/datetime.h>
3116 wxDateTime::wxDateTime_t day
;
3117 wxDateTime::Month month
;
3119 wxDateTime::wxDateTime_t hour
, min
, sec
;
3121 wxDateTime::WeekDay wday
;
3122 time_t gmticks
, ticks
;
3124 void Init(const wxDateTime::Tm
& tm
)
3133 gmticks
= ticks
= -1;
3136 wxDateTime
DT() const
3137 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3139 bool SameDay(const wxDateTime::Tm
& tm
) const
3141 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3144 wxString
Format() const
3147 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3149 wxDateTime::GetMonthName(month
).c_str(),
3151 abs(wxDateTime::ConvertYearToBC(year
)),
3152 year
> 0 ? "AD" : "BC");
3156 wxString
FormatDate() const
3159 s
.Printf("%02d-%s-%4d%s",
3161 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3162 abs(wxDateTime::ConvertYearToBC(year
)),
3163 year
> 0 ? "AD" : "BC");
3168 static const Date testDates
[] =
3170 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3171 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3172 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3173 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3174 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3175 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3176 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3177 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3178 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3179 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3180 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3181 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3182 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3183 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3184 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3187 // this test miscellaneous static wxDateTime functions
3188 static void TestTimeStatic()
3190 puts("\n*** wxDateTime static methods test ***");
3192 // some info about the current date
3193 int year
= wxDateTime::GetCurrentYear();
3194 printf("Current year %d is %sa leap one and has %d days.\n",
3196 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3197 wxDateTime::GetNumberOfDays(year
));
3199 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3200 printf("Current month is '%s' ('%s') and it has %d days\n",
3201 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3202 wxDateTime::GetMonthName(month
).c_str(),
3203 wxDateTime::GetNumberOfDays(month
));
3206 static const size_t nYears
= 5;
3207 static const size_t years
[2][nYears
] =
3209 // first line: the years to test
3210 { 1990, 1976, 2000, 2030, 1984, },
3212 // second line: TRUE if leap, FALSE otherwise
3213 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3216 for ( size_t n
= 0; n
< nYears
; n
++ )
3218 int year
= years
[0][n
];
3219 bool should
= years
[1][n
] != 0,
3220 is
= wxDateTime::IsLeapYear(year
);
3222 printf("Year %d is %sa leap year (%s)\n",
3225 should
== is
? "ok" : "ERROR");
3227 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3231 // test constructing wxDateTime objects
3232 static void TestTimeSet()
3234 puts("\n*** wxDateTime construction test ***");
3236 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3238 const Date
& d1
= testDates
[n
];
3239 wxDateTime dt
= d1
.DT();
3242 d2
.Init(dt
.GetTm());
3244 wxString s1
= d1
.Format(),
3247 printf("Date: %s == %s (%s)\n",
3248 s1
.c_str(), s2
.c_str(),
3249 s1
== s2
? "ok" : "ERROR");
3253 // test time zones stuff
3254 static void TestTimeZones()
3256 puts("\n*** wxDateTime timezone test ***");
3258 wxDateTime now
= wxDateTime::Now();
3260 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3261 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3262 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3263 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3264 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3265 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3267 wxDateTime::Tm tm
= now
.GetTm();
3268 if ( wxDateTime(tm
) != now
)
3270 printf("ERROR: got %s instead of %s\n",
3271 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3275 // test some minimal support for the dates outside the standard range
3276 static void TestTimeRange()
3278 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3280 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3282 printf("Unix epoch:\t%s\n",
3283 wxDateTime(2440587.5).Format(fmt
).c_str());
3284 printf("Feb 29, 0: \t%s\n",
3285 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3286 printf("JDN 0: \t%s\n",
3287 wxDateTime(0.0).Format(fmt
).c_str());
3288 printf("Jan 1, 1AD:\t%s\n",
3289 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3290 printf("May 29, 2099:\t%s\n",
3291 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3294 static void TestTimeTicks()
3296 puts("\n*** wxDateTime ticks test ***");
3298 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3300 const Date
& d
= testDates
[n
];
3301 if ( d
.ticks
== -1 )
3304 wxDateTime dt
= d
.DT();
3305 long ticks
= (dt
.GetValue() / 1000).ToLong();
3306 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3307 if ( ticks
== d
.ticks
)
3313 printf(" (ERROR: should be %ld, delta = %ld)\n",
3314 d
.ticks
, ticks
- d
.ticks
);
3317 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3318 ticks
= (dt
.GetValue() / 1000).ToLong();
3319 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3320 if ( ticks
== d
.gmticks
)
3326 printf(" (ERROR: should be %ld, delta = %ld)\n",
3327 d
.gmticks
, ticks
- d
.gmticks
);
3334 // test conversions to JDN &c
3335 static void TestTimeJDN()
3337 puts("\n*** wxDateTime to JDN test ***");
3339 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3341 const Date
& d
= testDates
[n
];
3342 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3343 double jdn
= dt
.GetJulianDayNumber();
3345 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3352 printf(" (ERROR: should be %f, delta = %f)\n",
3353 d
.jdn
, jdn
- d
.jdn
);
3358 // test week days computation
3359 static void TestTimeWDays()
3361 puts("\n*** wxDateTime weekday test ***");
3363 // test GetWeekDay()
3365 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3367 const Date
& d
= testDates
[n
];
3368 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3370 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3373 wxDateTime::GetWeekDayName(wday
).c_str());
3374 if ( wday
== d
.wday
)
3380 printf(" (ERROR: should be %s)\n",
3381 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3387 // test SetToWeekDay()
3388 struct WeekDateTestData
3390 Date date
; // the real date (precomputed)
3391 int nWeek
; // its week index in the month
3392 wxDateTime::WeekDay wday
; // the weekday
3393 wxDateTime::Month month
; // the month
3394 int year
; // and the year
3396 wxString
Format() const
3399 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3401 case 1: which
= "first"; break;
3402 case 2: which
= "second"; break;
3403 case 3: which
= "third"; break;
3404 case 4: which
= "fourth"; break;
3405 case 5: which
= "fifth"; break;
3407 case -1: which
= "last"; break;
3412 which
+= " from end";
3415 s
.Printf("The %s %s of %s in %d",
3417 wxDateTime::GetWeekDayName(wday
).c_str(),
3418 wxDateTime::GetMonthName(month
).c_str(),
3425 // the array data was generated by the following python program
3427 from DateTime import *
3428 from whrandom import *
3429 from string import *
3431 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3432 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3434 week = DateTimeDelta(7)
3437 year = randint(1900, 2100)
3438 month = randint(1, 12)
3439 day = randint(1, 28)
3440 dt = DateTime(year, month, day)
3441 wday = dt.day_of_week
3443 countFromEnd = choice([-1, 1])
3446 while dt.month is month:
3447 dt = dt - countFromEnd * week
3448 weekNum = weekNum + countFromEnd
3450 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3452 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3453 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3456 static const WeekDateTestData weekDatesTestData
[] =
3458 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3459 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3460 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3461 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3462 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3463 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3464 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3465 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3466 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3467 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3468 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3469 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3470 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3471 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3472 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3473 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3474 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3475 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3476 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3477 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3480 static const char *fmt
= "%d-%b-%Y";
3483 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3485 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3487 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3489 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3491 const Date
& d
= wd
.date
;
3492 if ( d
.SameDay(dt
.GetTm()) )
3498 dt
.Set(d
.day
, d
.month
, d
.year
);
3500 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3505 // test the computation of (ISO) week numbers
3506 static void TestTimeWNumber()
3508 puts("\n*** wxDateTime week number test ***");
3510 struct WeekNumberTestData
3512 Date date
; // the date
3513 wxDateTime::wxDateTime_t week
; // the week number in the year
3514 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3515 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3516 wxDateTime::wxDateTime_t dnum
; // day number in the year
3519 // data generated with the following python script:
3521 from DateTime import *
3522 from whrandom import *
3523 from string import *
3525 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3526 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3528 def GetMonthWeek(dt):
3529 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3530 if weekNumMonth < 0:
3531 weekNumMonth = weekNumMonth + 53
3534 def GetLastSundayBefore(dt):
3535 if dt.iso_week[2] == 7:
3538 return dt - DateTimeDelta(dt.iso_week[2])
3541 year = randint(1900, 2100)
3542 month = randint(1, 12)
3543 day = randint(1, 28)
3544 dt = DateTime(year, month, day)
3545 dayNum = dt.day_of_year
3546 weekNum = dt.iso_week[1]
3547 weekNumMonth = GetMonthWeek(dt)
3550 dtSunday = GetLastSundayBefore(dt)
3552 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3553 weekNumMonth2 = weekNumMonth2 + 1
3554 dtSunday = dtSunday - DateTimeDelta(7)
3556 data = { 'day': rjust(`day`, 2), \
3557 'month': monthNames[month - 1], \
3559 'weekNum': rjust(`weekNum`, 2), \
3560 'weekNumMonth': weekNumMonth, \
3561 'weekNumMonth2': weekNumMonth2, \
3562 'dayNum': rjust(`dayNum`, 3) }
3564 print " { { %(day)s, "\
3565 "wxDateTime::%(month)s, "\
3568 "%(weekNumMonth)s, "\
3569 "%(weekNumMonth2)s, "\
3570 "%(dayNum)s }," % data
3573 static const WeekNumberTestData weekNumberTestDates
[] =
3575 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3576 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3577 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3578 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3579 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3580 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3581 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3582 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3583 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3584 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3585 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3586 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3587 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3588 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3589 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3590 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3591 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3592 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3593 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3594 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3597 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3599 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3600 const Date
& d
= wn
.date
;
3602 wxDateTime dt
= d
.DT();
3604 wxDateTime::wxDateTime_t
3605 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3606 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3607 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3608 dnum
= dt
.GetDayOfYear();
3610 printf("%s: the day number is %d",
3611 d
.FormatDate().c_str(), dnum
);
3612 if ( dnum
== wn
.dnum
)
3618 printf(" (ERROR: should be %d)", wn
.dnum
);
3621 printf(", week in month is %d", wmon
);
3622 if ( wmon
== wn
.wmon
)
3628 printf(" (ERROR: should be %d)", wn
.wmon
);
3631 printf(" or %d", wmon2
);
3632 if ( wmon2
== wn
.wmon2
)
3638 printf(" (ERROR: should be %d)", wn
.wmon2
);
3641 printf(", week in year is %d", week
);
3642 if ( week
== wn
.week
)
3648 printf(" (ERROR: should be %d)\n", wn
.week
);
3653 // test DST calculations
3654 static void TestTimeDST()
3656 puts("\n*** wxDateTime DST test ***");
3658 printf("DST is%s in effect now.\n\n",
3659 wxDateTime::Now().IsDST() ? "" : " not");
3661 // taken from http://www.energy.ca.gov/daylightsaving.html
3662 static const Date datesDST
[2][2004 - 1900 + 1] =
3665 { 1, wxDateTime::Apr
, 1990 },
3666 { 7, wxDateTime::Apr
, 1991 },
3667 { 5, wxDateTime::Apr
, 1992 },
3668 { 4, wxDateTime::Apr
, 1993 },
3669 { 3, wxDateTime::Apr
, 1994 },
3670 { 2, wxDateTime::Apr
, 1995 },
3671 { 7, wxDateTime::Apr
, 1996 },
3672 { 6, wxDateTime::Apr
, 1997 },
3673 { 5, wxDateTime::Apr
, 1998 },
3674 { 4, wxDateTime::Apr
, 1999 },
3675 { 2, wxDateTime::Apr
, 2000 },
3676 { 1, wxDateTime::Apr
, 2001 },
3677 { 7, wxDateTime::Apr
, 2002 },
3678 { 6, wxDateTime::Apr
, 2003 },
3679 { 4, wxDateTime::Apr
, 2004 },
3682 { 28, wxDateTime::Oct
, 1990 },
3683 { 27, wxDateTime::Oct
, 1991 },
3684 { 25, wxDateTime::Oct
, 1992 },
3685 { 31, wxDateTime::Oct
, 1993 },
3686 { 30, wxDateTime::Oct
, 1994 },
3687 { 29, wxDateTime::Oct
, 1995 },
3688 { 27, wxDateTime::Oct
, 1996 },
3689 { 26, wxDateTime::Oct
, 1997 },
3690 { 25, wxDateTime::Oct
, 1998 },
3691 { 31, wxDateTime::Oct
, 1999 },
3692 { 29, wxDateTime::Oct
, 2000 },
3693 { 28, wxDateTime::Oct
, 2001 },
3694 { 27, wxDateTime::Oct
, 2002 },
3695 { 26, wxDateTime::Oct
, 2003 },
3696 { 31, wxDateTime::Oct
, 2004 },
3701 for ( year
= 1990; year
< 2005; year
++ )
3703 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3704 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3706 printf("DST period in the US for year %d: from %s to %s",
3707 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3709 size_t n
= year
- 1990;
3710 const Date
& dBegin
= datesDST
[0][n
];
3711 const Date
& dEnd
= datesDST
[1][n
];
3713 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3719 printf(" (ERROR: should be %s %d to %s %d)\n",
3720 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3721 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3727 for ( year
= 1990; year
< 2005; year
++ )
3729 printf("DST period in Europe for year %d: from %s to %s\n",
3731 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3732 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3736 // test wxDateTime -> text conversion
3737 static void TestTimeFormat()
3739 puts("\n*** wxDateTime formatting test ***");
3741 // some information may be lost during conversion, so store what kind
3742 // of info should we recover after a round trip
3745 CompareNone
, // don't try comparing
3746 CompareBoth
, // dates and times should be identical
3747 CompareDate
, // dates only
3748 CompareTime
// time only
3753 CompareKind compareKind
;
3755 } formatTestFormats
[] =
3757 { CompareBoth
, "---> %c" },
3758 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3759 { CompareBoth
, "Date is %x, time is %X" },
3760 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3761 { CompareNone
, "The day of year: %j, the week of year: %W" },
3762 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3765 static const Date formatTestDates
[] =
3767 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3768 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3770 // this test can't work for other centuries because it uses two digit
3771 // years in formats, so don't even try it
3772 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3773 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3774 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3778 // an extra test (as it doesn't depend on date, don't do it in the loop)
3779 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
3781 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
3785 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
3786 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
3788 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
3789 printf("%s", s
.c_str());
3791 // what can we recover?
3792 int kind
= formatTestFormats
[n
].compareKind
;
3796 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
3799 // converion failed - should it have?
3800 if ( kind
== CompareNone
)
3803 puts(" (ERROR: conversion back failed)");
3807 // should have parsed the entire string
3808 puts(" (ERROR: conversion back stopped too soon)");
3812 bool equal
= FALSE
; // suppress compilaer warning
3820 equal
= dt
.IsSameDate(dt2
);
3824 equal
= dt
.IsSameTime(dt2
);
3830 printf(" (ERROR: got back '%s' instead of '%s')\n",
3831 dt2
.Format().c_str(), dt
.Format().c_str());
3842 // test text -> wxDateTime conversion
3843 static void TestTimeParse()
3845 puts("\n*** wxDateTime parse test ***");
3847 struct ParseTestData
3854 static const ParseTestData parseTestDates
[] =
3856 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3857 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3860 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3862 const char *format
= parseTestDates
[n
].format
;
3864 printf("%s => ", format
);
3867 if ( dt
.ParseRfc822Date(format
) )
3869 printf("%s ", dt
.Format().c_str());
3871 if ( parseTestDates
[n
].good
)
3873 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3880 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3885 puts("(ERROR: bad format)");
3890 printf("bad format (%s)\n",
3891 parseTestDates
[n
].good
? "ERROR" : "ok");
3896 static void TestDateTimeInteractive()
3898 puts("\n*** interactive wxDateTime tests ***");
3904 printf("Enter a date: ");
3905 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3908 // kill the last '\n'
3909 buf
[strlen(buf
) - 1] = 0;
3912 const char *p
= dt
.ParseDate(buf
);
3915 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3921 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3924 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3925 dt
.Format("%b %d, %Y").c_str(),
3927 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3928 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3929 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3932 puts("\n*** done ***");
3935 static void TestTimeMS()
3937 puts("*** testing millisecond-resolution support in wxDateTime ***");
3939 wxDateTime dt1
= wxDateTime::Now(),
3940 dt2
= wxDateTime::UNow();
3942 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3943 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3944 printf("Dummy loop: ");
3945 for ( int i
= 0; i
< 6000; i
++ )
3947 //for ( int j = 0; j < 10; j++ )
3950 s
.Printf("%g", sqrt(i
));
3959 dt2
= wxDateTime::UNow();
3960 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3962 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3964 puts("\n*** done ***");
3967 static void TestTimeArithmetics()
3969 puts("\n*** testing arithmetic operations on wxDateTime ***");
3971 static const struct ArithmData
3973 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3974 : span(sp
), name(nam
) { }
3978 } testArithmData
[] =
3980 ArithmData(wxDateSpan::Day(), "day"),
3981 ArithmData(wxDateSpan::Week(), "week"),
3982 ArithmData(wxDateSpan::Month(), "month"),
3983 ArithmData(wxDateSpan::Year(), "year"),
3984 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3987 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3989 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3991 wxDateSpan span
= testArithmData
[n
].span
;
3995 const char *name
= testArithmData
[n
].name
;
3996 printf("%s + %s = %s, %s - %s = %s\n",
3997 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3998 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4000 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4001 if ( dt1
- span
== dt
)
4007 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4010 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4011 if ( dt2
+ span
== dt
)
4017 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4020 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4021 if ( dt2
+ 2*span
== dt1
)
4027 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4034 static void TestTimeHolidays()
4036 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4038 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4039 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4040 dtEnd
= dtStart
.GetLastMonthDay();
4042 wxDateTimeArray hol
;
4043 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4045 const wxChar
*format
= "%d-%b-%Y (%a)";
4047 printf("All holidays between %s and %s:\n",
4048 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4050 size_t count
= hol
.GetCount();
4051 for ( size_t n
= 0; n
< count
; n
++ )
4053 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4059 static void TestTimeZoneBug()
4061 puts("\n*** testing for DST/timezone bug ***\n");
4063 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4064 for ( int i
= 0; i
< 31; i
++ )
4066 printf("Date %s: week day %s.\n",
4067 date
.Format(_T("%d-%m-%Y")).c_str(),
4068 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4070 date
+= wxDateSpan::Day();
4076 static void TestTimeSpanFormat()
4078 puts("\n*** wxTimeSpan tests ***");
4080 static const char *formats
[] =
4082 _T("(default) %H:%M:%S"),
4083 _T("%E weeks and %D days"),
4084 _T("%l milliseconds"),
4085 _T("(with ms) %H:%M:%S:%l"),
4086 _T("100%% of minutes is %M"), // test "%%"
4087 _T("%D days and %H hours"),
4088 _T("or also %S seconds"),
4091 wxTimeSpan
ts1(1, 2, 3, 4),
4093 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4095 printf("ts1 = %s\tts2 = %s\n",
4096 ts1
.Format(formats
[n
]).c_str(),
4097 ts2
.Format(formats
[n
]).c_str());
4105 // test compatibility with the old wxDate/wxTime classes
4106 static void TestTimeCompatibility()
4108 puts("\n*** wxDateTime compatibility test ***");
4110 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4111 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4113 double jdnNow
= wxDateTime::Now().GetJDN();
4114 long jdnMidnight
= (long)(jdnNow
- 0.5);
4115 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4117 jdnMidnight
= wxDate().Set().GetJulianDate();
4118 printf("wxDateTime for today: %s\n",
4119 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4121 int flags
= wxEUROPEAN
;//wxFULL;
4124 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4125 for ( int n
= 0; n
< 7; n
++ )
4127 printf("Previous %s is %s\n",
4128 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4129 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4135 #endif // TEST_DATETIME
4137 // ----------------------------------------------------------------------------
4139 // ----------------------------------------------------------------------------
4143 #include <wx/thread.h>
4145 static size_t gs_counter
= (size_t)-1;
4146 static wxCriticalSection gs_critsect
;
4147 static wxCondition gs_cond
;
4149 class MyJoinableThread
: public wxThread
4152 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4153 { m_n
= n
; Create(); }
4155 // thread execution starts here
4156 virtual ExitCode
Entry();
4162 wxThread::ExitCode
MyJoinableThread::Entry()
4164 unsigned long res
= 1;
4165 for ( size_t n
= 1; n
< m_n
; n
++ )
4169 // it's a loooong calculation :-)
4173 return (ExitCode
)res
;
4176 class MyDetachedThread
: public wxThread
4179 MyDetachedThread(size_t n
, char ch
)
4183 m_cancelled
= FALSE
;
4188 // thread execution starts here
4189 virtual ExitCode
Entry();
4192 virtual void OnExit();
4195 size_t m_n
; // number of characters to write
4196 char m_ch
; // character to write
4198 bool m_cancelled
; // FALSE if we exit normally
4201 wxThread::ExitCode
MyDetachedThread::Entry()
4204 wxCriticalSectionLocker
lock(gs_critsect
);
4205 if ( gs_counter
== (size_t)-1 )
4211 for ( size_t n
= 0; n
< m_n
; n
++ )
4213 if ( TestDestroy() )
4223 wxThread::Sleep(100);
4229 void MyDetachedThread::OnExit()
4231 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4233 wxCriticalSectionLocker
lock(gs_critsect
);
4234 if ( !--gs_counter
&& !m_cancelled
)
4238 void TestDetachedThreads()
4240 puts("\n*** Testing detached threads ***");
4242 static const size_t nThreads
= 3;
4243 MyDetachedThread
*threads
[nThreads
];
4245 for ( n
= 0; n
< nThreads
; n
++ )
4247 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4250 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4251 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4253 for ( n
= 0; n
< nThreads
; n
++ )
4258 // wait until all threads terminate
4264 void TestJoinableThreads()
4266 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4268 // calc 10! in the background
4269 MyJoinableThread
thread(10);
4272 printf("\nThread terminated with exit code %lu.\n",
4273 (unsigned long)thread
.Wait());
4276 void TestThreadSuspend()
4278 puts("\n*** Testing thread suspend/resume functions ***");
4280 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4284 // this is for this demo only, in a real life program we'd use another
4285 // condition variable which would be signaled from wxThread::Entry() to
4286 // tell us that the thread really started running - but here just wait a
4287 // bit and hope that it will be enough (the problem is, of course, that
4288 // the thread might still not run when we call Pause() which will result
4290 wxThread::Sleep(300);
4292 for ( size_t n
= 0; n
< 3; n
++ )
4296 puts("\nThread suspended");
4299 // don't sleep but resume immediately the first time
4300 wxThread::Sleep(300);
4302 puts("Going to resume the thread");
4307 puts("Waiting until it terminates now");
4309 // wait until the thread terminates
4315 void TestThreadDelete()
4317 // As above, using Sleep() is only for testing here - we must use some
4318 // synchronisation object instead to ensure that the thread is still
4319 // running when we delete it - deleting a detached thread which already
4320 // terminated will lead to a crash!
4322 puts("\n*** Testing thread delete function ***");
4324 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4328 puts("\nDeleted a thread which didn't start to run yet.");
4330 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4334 wxThread::Sleep(300);
4338 puts("\nDeleted a running thread.");
4340 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4344 wxThread::Sleep(300);
4350 puts("\nDeleted a sleeping thread.");
4352 MyJoinableThread
thread3(20);
4357 puts("\nDeleted a joinable thread.");
4359 MyJoinableThread
thread4(2);
4362 wxThread::Sleep(300);
4366 puts("\nDeleted a joinable thread which already terminated.");
4371 #endif // TEST_THREADS
4373 // ----------------------------------------------------------------------------
4375 // ----------------------------------------------------------------------------
4379 static void PrintArray(const char* name
, const wxArrayString
& array
)
4381 printf("Dump of the array '%s'\n", name
);
4383 size_t nCount
= array
.GetCount();
4384 for ( size_t n
= 0; n
< nCount
; n
++ )
4386 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4390 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4392 printf("Dump of the array '%s'\n", name
);
4394 size_t nCount
= array
.GetCount();
4395 for ( size_t n
= 0; n
< nCount
; n
++ )
4397 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4401 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4402 const wxString
& second
)
4404 return first
.length() - second
.length();
4407 int wxCMPFUNC_CONV
IntCompare(int *first
,
4410 return *first
- *second
;
4413 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4416 return *second
- *first
;
4419 static void TestArrayOfInts()
4421 puts("*** Testing wxArrayInt ***\n");
4432 puts("After sort:");
4436 puts("After reverse sort:");
4437 a
.Sort(IntRevCompare
);
4441 #include "wx/dynarray.h"
4443 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4444 #include "wx/arrimpl.cpp"
4445 WX_DEFINE_OBJARRAY(ArrayBars
);
4447 static void TestArrayOfObjects()
4449 puts("*** Testing wxObjArray ***\n");
4453 Bar
bar("second bar");
4455 printf("Initially: %u objects in the array, %u objects total.\n",
4456 bars
.GetCount(), Bar::GetNumber());
4458 bars
.Add(new Bar("first bar"));
4461 printf("Now: %u objects in the array, %u objects total.\n",
4462 bars
.GetCount(), Bar::GetNumber());
4466 printf("After Empty(): %u objects in the array, %u objects total.\n",
4467 bars
.GetCount(), Bar::GetNumber());
4470 printf("Finally: no more objects in the array, %u objects total.\n",
4474 #endif // TEST_ARRAYS
4476 // ----------------------------------------------------------------------------
4478 // ----------------------------------------------------------------------------
4482 #include "wx/timer.h"
4483 #include "wx/tokenzr.h"
4485 static void TestStringConstruction()
4487 puts("*** Testing wxString constructores ***");
4489 #define TEST_CTOR(args, res) \
4492 printf("wxString%s = %s ", #args, s.c_str()); \
4499 printf("(ERROR: should be %s)\n", res); \
4503 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4504 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4505 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4506 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4508 static const wxChar
*s
= _T("?really!");
4509 const wxChar
*start
= wxStrchr(s
, _T('r'));
4510 const wxChar
*end
= wxStrchr(s
, _T('!'));
4511 TEST_CTOR((start
, end
), _T("really"));
4516 static void TestString()
4526 for (int i
= 0; i
< 1000000; ++i
)
4530 c
= "! How'ya doin'?";
4533 c
= "Hello world! What's up?";
4538 printf ("TestString elapsed time: %ld\n", sw
.Time());
4541 static void TestPChar()
4549 for (int i
= 0; i
< 1000000; ++i
)
4551 strcpy (a
, "Hello");
4552 strcpy (b
, " world");
4553 strcpy (c
, "! How'ya doin'?");
4556 strcpy (c
, "Hello world! What's up?");
4557 if (strcmp (c
, a
) == 0)
4561 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4564 static void TestStringSub()
4566 wxString
s("Hello, world!");
4568 puts("*** Testing wxString substring extraction ***");
4570 printf("String = '%s'\n", s
.c_str());
4571 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4572 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4573 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4574 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4575 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4576 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4578 static const wxChar
*prefixes
[] =
4582 _T("Hello, world!"),
4583 _T("Hello, world!!!"),
4589 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4591 wxString prefix
= prefixes
[n
], rest
;
4592 bool rc
= s
.StartsWith(prefix
, &rest
);
4593 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4596 printf(" (the rest is '%s')\n", rest
.c_str());
4607 static void TestStringFormat()
4609 puts("*** Testing wxString formatting ***");
4612 s
.Printf("%03d", 18);
4614 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4615 printf("Number 18: %s\n", s
.c_str());
4620 // returns "not found" for npos, value for all others
4621 static wxString
PosToString(size_t res
)
4623 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4624 : wxString::Format(_T("%u"), res
);
4628 static void TestStringFind()
4630 puts("*** Testing wxString find() functions ***");
4632 static const wxChar
*strToFind
= _T("ell");
4633 static const struct StringFindTest
4637 result
; // of searching "ell" in str
4640 { _T("Well, hello world"), 0, 1 },
4641 { _T("Well, hello world"), 6, 7 },
4642 { _T("Well, hello world"), 9, wxString::npos
},
4645 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4647 const StringFindTest
& ft
= findTestData
[n
];
4648 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4650 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4651 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4653 size_t resTrue
= ft
.result
;
4654 if ( res
== resTrue
)
4660 printf(_T("(ERROR: should be %s)\n"),
4661 PosToString(resTrue
).c_str());
4668 static void TestStringTokenizer()
4670 puts("*** Testing wxStringTokenizer ***");
4672 static const wxChar
*modeNames
[] =
4676 _T("return all empty"),
4681 static const struct StringTokenizerTest
4683 const wxChar
*str
; // string to tokenize
4684 const wxChar
*delims
; // delimiters to use
4685 size_t count
; // count of token
4686 wxStringTokenizerMode mode
; // how should we tokenize it
4687 } tokenizerTestData
[] =
4689 { _T(""), _T(" "), 0 },
4690 { _T("Hello, world"), _T(" "), 2 },
4691 { _T("Hello, world "), _T(" "), 2 },
4692 { _T("Hello, world"), _T(","), 2 },
4693 { _T("Hello, world!"), _T(",!"), 2 },
4694 { _T("Hello,, world!"), _T(",!"), 3 },
4695 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4696 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4697 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4698 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4699 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4700 { _T("01/02/99"), _T("/-"), 3 },
4701 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4704 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4706 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4707 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4709 size_t count
= tkz
.CountTokens();
4710 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4711 MakePrintable(tt
.str
).c_str(),
4713 MakePrintable(tt
.delims
).c_str(),
4714 modeNames
[tkz
.GetMode()]);
4715 if ( count
== tt
.count
)
4721 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4726 // if we emulate strtok(), check that we do it correctly
4727 wxChar
*buf
, *s
= NULL
, *last
;
4729 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4731 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4732 wxStrcpy(buf
, tt
.str
);
4734 s
= wxStrtok(buf
, tt
.delims
, &last
);
4741 // now show the tokens themselves
4743 while ( tkz
.HasMoreTokens() )
4745 wxString token
= tkz
.GetNextToken();
4747 printf(_T("\ttoken %u: '%s'"),
4749 MakePrintable(token
).c_str());
4759 printf(" (ERROR: should be %s)\n", s
);
4762 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4766 // nothing to compare with
4771 if ( count2
!= count
)
4773 puts(_T("\tERROR: token count mismatch"));
4782 static void TestStringReplace()
4784 puts("*** Testing wxString::replace ***");
4786 static const struct StringReplaceTestData
4788 const wxChar
*original
; // original test string
4789 size_t start
, len
; // the part to replace
4790 const wxChar
*replacement
; // the replacement string
4791 const wxChar
*result
; // and the expected result
4792 } stringReplaceTestData
[] =
4794 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
4795 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
4796 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
4797 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
4798 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
4801 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
4803 const StringReplaceTestData data
= stringReplaceTestData
[n
];
4805 wxString original
= data
.original
;
4806 original
.replace(data
.start
, data
.len
, data
.replacement
);
4808 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
4809 data
.original
, data
.start
, data
.len
, data
.replacement
,
4812 if ( original
== data
.result
)
4818 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
4825 static void TestStringMatch()
4827 wxPuts(_T("*** Testing wxString::Matches() ***"));
4829 static const struct StringMatchTestData
4832 const wxChar
*wildcard
;
4834 } stringMatchTestData
[] =
4836 { _T("foobar"), _T("foo*"), 1 },
4837 { _T("foobar"), _T("*oo*"), 1 },
4838 { _T("foobar"), _T("*bar"), 1 },
4839 { _T("foobar"), _T("??????"), 1 },
4840 { _T("foobar"), _T("f??b*"), 1 },
4841 { _T("foobar"), _T("f?b*"), 0 },
4842 { _T("foobar"), _T("*goo*"), 0 },
4843 { _T("foobar"), _T("*foo"), 0 },
4844 { _T("foobarfoo"), _T("*foo"), 1 },
4845 { _T(""), _T("*"), 1 },
4846 { _T(""), _T("?"), 0 },
4849 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
4851 const StringMatchTestData
& data
= stringMatchTestData
[n
];
4852 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
4853 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
4855 matches
? _T("matches") : _T("doesn't match"),
4857 matches
== data
.matches
? _T("ok") : _T("ERROR"));
4863 #endif // TEST_STRINGS
4865 // ----------------------------------------------------------------------------
4867 // ----------------------------------------------------------------------------
4869 int main(int argc
, char **argv
)
4871 wxInitializer initializer
;
4874 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
4879 #ifdef TEST_SNGLINST
4880 wxSingleInstanceChecker checker
;
4881 if ( checker
.Create(_T(".wxconsole.lock")) )
4883 if ( checker
.IsAnotherRunning() )
4885 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4890 // wait some time to give time to launch another instance
4891 wxPrintf(_T("Press \"Enter\" to continue..."));
4894 else // failed to create
4896 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4898 #endif // TEST_SNGLINST
4902 #endif // TEST_CHARSET
4905 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4907 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
4908 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4909 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
4910 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
4912 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
4913 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
4914 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
4915 wxCMD_LINE_VAL_NUMBER
},
4916 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
4917 wxCMD_LINE_VAL_DATE
},
4919 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4920 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4925 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4927 parser
.AddOption("project_name", "", "full path to project file",
4928 wxCMD_LINE_VAL_STRING
,
4929 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4931 switch ( parser
.Parse() )
4934 wxLogMessage("Help was given, terminating.");
4938 ShowCmdLine(parser
);
4942 wxLogMessage("Syntax error detected, aborting.");
4945 #endif // TEST_CMDLINE
4953 TestStringConstruction();
4956 TestStringTokenizer();
4957 TestStringReplace();
4960 #endif // TEST_STRINGS
4973 puts("*** Initially:");
4975 PrintArray("a1", a1
);
4977 wxArrayString
a2(a1
);
4978 PrintArray("a2", a2
);
4980 wxSortedArrayString
a3(a1
);
4981 PrintArray("a3", a3
);
4983 puts("*** After deleting a string from a1");
4986 PrintArray("a1", a1
);
4987 PrintArray("a2", a2
);
4988 PrintArray("a3", a3
);
4990 puts("*** After reassigning a1 to a2 and a3");
4992 PrintArray("a2", a2
);
4993 PrintArray("a3", a3
);
4995 puts("*** After sorting a1");
4997 PrintArray("a1", a1
);
4999 puts("*** After sorting a1 in reverse order");
5001 PrintArray("a1", a1
);
5003 puts("*** After sorting a1 by the string length");
5004 a1
.Sort(StringLenCompare
);
5005 PrintArray("a1", a1
);
5007 TestArrayOfObjects();
5010 #endif // TEST_ARRAYS
5018 #ifdef TEST_DLLLOADER
5020 #endif // TEST_DLLLOADER
5024 #endif // TEST_ENVIRON
5028 #endif // TEST_EXECUTE
5030 #ifdef TEST_FILECONF
5032 #endif // TEST_FILECONF
5040 #endif // TEST_LOCALE
5044 for ( size_t n
= 0; n
< 8000; n
++ )
5046 s
<< (char)('A' + (n
% 26));
5050 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5052 // this one shouldn't be truncated
5055 // but this one will because log functions use fixed size buffer
5056 // (note that it doesn't need '\n' at the end neither - will be added
5058 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5070 #ifdef TEST_FILENAME
5071 TestFileNameSplit();
5074 TestFileNameConstruction();
5076 TestFileNameComparison();
5077 TestFileNameOperations();
5079 #endif // TEST_FILENAME
5082 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5083 if ( TestFtpConnect() )
5094 TestFtpInteractive();
5096 //else: connecting to the FTP server failed
5103 int nCPUs
= wxThread::GetCPUCount();
5104 printf("This system has %d CPUs\n", nCPUs
);
5106 wxThread::SetConcurrency(nCPUs
);
5108 if ( argc
> 1 && argv
[1][0] == 't' )
5109 wxLog::AddTraceMask("thread");
5112 TestDetachedThreads();
5114 TestJoinableThreads();
5116 TestThreadSuspend();
5120 #endif // TEST_THREADS
5122 #ifdef TEST_LONGLONG
5123 // seed pseudo random generator
5124 srand((unsigned)time(NULL
));
5132 TestMultiplication();
5135 TestLongLongConversion();
5136 TestBitOperations();
5137 TestLongLongComparison();
5139 TestLongLongPrint();
5140 #endif // TEST_LONGLONG
5147 wxLog::AddTraceMask(_T("mime"));
5155 TestMimeAssociate();
5158 #ifdef TEST_INFO_FUNCTIONS
5165 #endif // TEST_INFO_FUNCTIONS
5167 #ifdef TEST_PATHLIST
5169 #endif // TEST_PATHLIST
5173 #endif // TEST_REGCONF
5176 // TODO: write a real test using src/regex/tests file
5181 TestRegExSubmatch();
5182 TestRegExInteractive();
5184 TestRegExReplacement();
5185 #endif // TEST_REGEX
5187 #ifdef TEST_REGISTRY
5190 TestRegistryAssociation();
5191 #endif // TEST_REGISTRY
5199 #endif // TEST_SOCKETS
5205 #endif // TEST_STREAMS
5209 #endif // TEST_TIMER
5211 #ifdef TEST_DATETIME
5224 TestTimeArithmetics();
5231 TestTimeSpanFormat();
5233 TestDateTimeInteractive();
5234 #endif // TEST_DATETIME
5237 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5239 #endif // TEST_USLEEP
5245 #endif // TEST_VCARD
5249 #endif // TEST_WCHAR
5253 TestZipStreamRead();
5254 TestZipFileSystem();
5259 TestZlibStreamWrite();
5260 TestZlibStreamRead();