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 // ----------------------------------------------------------------------------
22 #include <wx/string.h>
26 // without this pragma, the stupid compiler precompiles #defines below so that
27 // changing them doesn't "take place" later!
32 // ----------------------------------------------------------------------------
33 // conditional compilation
34 // ----------------------------------------------------------------------------
36 // what to test (in alphabetic order)?
39 //#define TEST_CMDLINE
40 //#define TEST_DATETIME
42 //#define TEST_DLLLOADER
43 //#define TEST_ENVIRON
44 //#define TEST_EXECUTE
46 //#define TEST_FILECONF
51 //#define TEST_LONGLONG
53 //#define TEST_INFO_FUNCTIONS
54 //#define TEST_REGISTRY
55 //#define TEST_SOCKETS
56 //#define TEST_STREAMS
57 //#define TEST_STRINGS
58 //#define TEST_THREADS
60 //#define TEST_VCARD -- don't enable this (VZ)
65 // ----------------------------------------------------------------------------
66 // test class for container objects
67 // ----------------------------------------------------------------------------
69 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
71 class Bar
// Foo is already taken in the hash test
74 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
77 static size_t GetNumber() { return ms_bars
; }
79 const char *GetName() const { return m_name
; }
84 static size_t ms_bars
;
87 size_t Bar::ms_bars
= 0;
89 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
91 // ============================================================================
93 // ============================================================================
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
99 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
101 // replace TABs with \t and CRs with \n
102 static wxString
MakePrintable(const wxChar
*s
)
105 (void)str
.Replace(_T("\t"), _T("\\t"));
106 (void)str
.Replace(_T("\n"), _T("\\n"));
107 (void)str
.Replace(_T("\r"), _T("\\r"));
112 #endif // MakePrintable() is used
114 // ----------------------------------------------------------------------------
116 // ----------------------------------------------------------------------------
120 #include <wx/cmdline.h>
121 #include <wx/datetime.h>
123 static void ShowCmdLine(const wxCmdLineParser
& parser
)
125 wxString s
= "Input files: ";
127 size_t count
= parser
.GetParamCount();
128 for ( size_t param
= 0; param
< count
; param
++ )
130 s
<< parser
.GetParam(param
) << ' ';
134 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
135 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
140 if ( parser
.Found("o", &strVal
) )
141 s
<< "Output file:\t" << strVal
<< '\n';
142 if ( parser
.Found("i", &strVal
) )
143 s
<< "Input dir:\t" << strVal
<< '\n';
144 if ( parser
.Found("s", &lVal
) )
145 s
<< "Size:\t" << lVal
<< '\n';
146 if ( parser
.Found("d", &dt
) )
147 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
148 if ( parser
.Found("project_name", &strVal
) )
149 s
<< "Project:\t" << strVal
<< '\n';
154 #endif // TEST_CMDLINE
156 // ----------------------------------------------------------------------------
158 // ----------------------------------------------------------------------------
164 static void TestDirEnumHelper(wxDir
& dir
,
165 int flags
= wxDIR_DEFAULT
,
166 const wxString
& filespec
= wxEmptyString
)
170 if ( !dir
.IsOpened() )
173 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
176 printf("\t%s\n", filename
.c_str());
178 cont
= dir
.GetNext(&filename
);
184 static void TestDirEnum()
186 wxDir
dir(wxGetCwd());
188 puts("Enumerating everything in current directory:");
189 TestDirEnumHelper(dir
);
191 puts("Enumerating really everything in current directory:");
192 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
194 puts("Enumerating object files in current directory:");
195 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
197 puts("Enumerating directories in current directory:");
198 TestDirEnumHelper(dir
, wxDIR_DIRS
);
200 puts("Enumerating files in current directory:");
201 TestDirEnumHelper(dir
, wxDIR_FILES
);
203 puts("Enumerating files including hidden in current directory:");
204 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
208 #elif defined(__WXMSW__)
211 #error "don't know where the root directory is"
214 puts("Enumerating everything in root directory:");
215 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
217 puts("Enumerating directories in root directory:");
218 TestDirEnumHelper(dir
, wxDIR_DIRS
);
220 puts("Enumerating files in root directory:");
221 TestDirEnumHelper(dir
, wxDIR_FILES
);
223 puts("Enumerating files including hidden in root directory:");
224 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
226 puts("Enumerating files in non existing directory:");
227 wxDir
dirNo("nosuchdir");
228 TestDirEnumHelper(dirNo
);
233 // ----------------------------------------------------------------------------
235 // ----------------------------------------------------------------------------
237 #ifdef TEST_DLLLOADER
239 #include <wx/dynlib.h>
241 static void TestDllLoad()
243 #if defined(__WXMSW__)
244 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
245 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
246 #elif defined(__UNIX__)
247 // weird: using just libc.so does *not* work!
248 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
249 static const wxChar
*FUNC_NAME
= _T("strlen");
251 #error "don't know how to test wxDllLoader on this platform"
254 puts("*** testing wxDllLoader ***\n");
256 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
259 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
263 typedef int (*strlenType
)(char *);
264 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
267 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
268 FUNC_NAME
, LIB_NAME
);
272 if ( pfnStrlen("foo") != 3 )
274 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
282 wxDllLoader::UnloadLibrary(dllHandle
);
286 #endif // TEST_DLLLOADER
288 // ----------------------------------------------------------------------------
290 // ----------------------------------------------------------------------------
294 #include <wx/utils.h>
296 static wxString
MyGetEnv(const wxString
& var
)
299 if ( !wxGetEnv(var
, &val
) )
302 val
= wxString(_T('\'')) + val
+ _T('\'');
307 static void TestEnvironment()
309 const wxChar
*var
= _T("wxTestVar");
311 puts("*** testing environment access functions ***");
313 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
314 wxSetEnv(var
, _T("value for wxTestVar"));
315 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
316 wxSetEnv(var
, _T("another value"));
317 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
319 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
320 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
323 #endif // TEST_ENVIRON
325 // ----------------------------------------------------------------------------
327 // ----------------------------------------------------------------------------
331 #include <wx/utils.h>
333 static void TestExecute()
335 puts("*** testing wxExecute ***");
338 #define COMMAND "cat -n ../../Makefile" // "echo hi"
339 #define SHELL_COMMAND "echo hi from shell"
340 #define REDIRECT_COMMAND COMMAND // "date"
341 #elif defined(__WXMSW__)
342 #define COMMAND "command.com -c 'echo hi'"
343 #define SHELL_COMMAND "echo hi"
344 #define REDIRECT_COMMAND COMMAND
346 #error "no command to exec"
349 printf("Testing wxShell: ");
351 if ( wxShell(SHELL_COMMAND
) )
356 printf("Testing wxExecute: ");
358 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
363 #if 0 // no, it doesn't work (yet?)
364 printf("Testing async wxExecute: ");
366 if ( wxExecute(COMMAND
) != 0 )
367 puts("Ok (command launched).");
372 printf("Testing wxExecute with redirection:\n");
373 wxArrayString output
;
374 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
380 size_t count
= output
.GetCount();
381 for ( size_t n
= 0; n
< count
; n
++ )
383 printf("\t%s\n", output
[n
].c_str());
390 #endif // TEST_EXECUTE
392 // ----------------------------------------------------------------------------
394 // ----------------------------------------------------------------------------
399 #include <wx/ffile.h>
400 #include <wx/textfile.h>
402 static void TestFileRead()
404 puts("*** wxFile read test ***");
406 wxFile
file(_T("testdata.fc"));
407 if ( file
.IsOpened() )
409 printf("File length: %lu\n", file
.Length());
411 puts("File dump:\n----------");
413 static const off_t len
= 1024;
417 off_t nRead
= file
.Read(buf
, len
);
418 if ( nRead
== wxInvalidOffset
)
420 printf("Failed to read the file.");
424 fwrite(buf
, nRead
, 1, stdout
);
434 printf("ERROR: can't open test file.\n");
440 static void TestTextFileRead()
442 puts("*** wxTextFile read test ***");
444 wxTextFile
file(_T("testdata.fc"));
447 printf("Number of lines: %u\n", file
.GetLineCount());
448 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
452 puts("\nDumping the entire file:");
453 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
455 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
457 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
459 puts("\nAnd now backwards:");
460 for ( s
= file
.GetLastLine();
461 file
.GetCurrentLine() != 0;
462 s
= file
.GetPrevLine() )
464 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
466 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
470 printf("ERROR: can't open '%s'\n", file
.GetName());
476 static void TestFileCopy()
478 puts("*** Testing wxCopyFile ***");
480 static const wxChar
*filename1
= _T("testdata.fc");
481 static const wxChar
*filename2
= _T("test2");
482 if ( !wxCopyFile(filename1
, filename2
) )
484 puts("ERROR: failed to copy file");
488 wxFFile
f1(filename1
, "rb"),
491 if ( !f1
.IsOpened() || !f2
.IsOpened() )
493 puts("ERROR: failed to open file(s)");
498 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
500 puts("ERROR: failed to read file(s)");
504 if ( (s1
.length() != s2
.length()) ||
505 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
507 puts("ERROR: copy error!");
511 puts("File was copied ok.");
517 if ( !wxRemoveFile(filename2
) )
519 puts("ERROR: failed to remove the file");
527 // ----------------------------------------------------------------------------
529 // ----------------------------------------------------------------------------
533 #include <wx/confbase.h>
534 #include <wx/fileconf.h>
536 static const struct FileConfTestData
538 const wxChar
*name
; // value name
539 const wxChar
*value
; // the value from the file
542 { _T("value1"), _T("one") },
543 { _T("value2"), _T("two") },
544 { _T("novalue"), _T("default") },
547 static void TestFileConfRead()
549 puts("*** testing wxFileConfig loading/reading ***");
551 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
552 _T("testdata.fc"), wxEmptyString
,
553 wxCONFIG_USE_RELATIVE_PATH
);
555 // test simple reading
556 puts("\nReading config file:");
557 wxString
defValue(_T("default")), value
;
558 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
560 const FileConfTestData
& data
= fcTestData
[n
];
561 value
= fileconf
.Read(data
.name
, defValue
);
562 printf("\t%s = %s ", data
.name
, value
.c_str());
563 if ( value
== data
.value
)
569 printf("(ERROR: should be %s)\n", data
.value
);
573 // test enumerating the entries
574 puts("\nEnumerating all root entries:");
577 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
580 printf("\t%s = %s\n",
582 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
584 cont
= fileconf
.GetNextEntry(name
, dummy
);
588 #endif // TEST_FILECONF
590 // ----------------------------------------------------------------------------
592 // ----------------------------------------------------------------------------
600 Foo(int n_
) { n
= n_
; count
++; }
608 size_t Foo::count
= 0;
610 WX_DECLARE_LIST(Foo
, wxListFoos
);
611 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
613 #include <wx/listimpl.cpp>
615 WX_DEFINE_LIST(wxListFoos
);
617 static void TestHash()
619 puts("*** Testing wxHashTable ***\n");
623 hash
.DeleteContents(TRUE
);
625 printf("Hash created: %u foos in hash, %u foos totally\n",
626 hash
.GetCount(), Foo::count
);
628 static const int hashTestData
[] =
630 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
634 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
636 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
639 printf("Hash filled: %u foos in hash, %u foos totally\n",
640 hash
.GetCount(), Foo::count
);
642 puts("Hash access test:");
643 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
645 printf("\tGetting element with key %d, value %d: ",
647 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
650 printf("ERROR, not found.\n");
654 printf("%d (%s)\n", foo
->n
,
655 (size_t)foo
->n
== n
? "ok" : "ERROR");
659 printf("\nTrying to get an element not in hash: ");
661 if ( hash
.Get(1234) || hash
.Get(1, 0) )
663 puts("ERROR: found!");
667 puts("ok (not found)");
671 printf("Hash destroyed: %u foos left\n", Foo::count
);
676 // ----------------------------------------------------------------------------
678 // ----------------------------------------------------------------------------
684 WX_DECLARE_LIST(Bar
, wxListBars
);
685 #include <wx/listimpl.cpp>
686 WX_DEFINE_LIST(wxListBars
);
688 static void TestListCtor()
690 puts("*** Testing wxList construction ***\n");
694 list1
.Append(new Bar(_T("first")));
695 list1
.Append(new Bar(_T("second")));
697 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
698 list1
.GetCount(), Bar::GetNumber());
703 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
704 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
706 list1
.DeleteContents(TRUE
);
709 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
714 // ----------------------------------------------------------------------------
716 // ----------------------------------------------------------------------------
720 #include <wx/mimetype.h>
722 static wxMimeTypesManager g_mimeManager
;
724 static void TestMimeEnum()
726 wxArrayString mimetypes
;
728 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
730 printf("*** All %u known filetypes: ***\n", count
);
735 for ( size_t n
= 0; n
< count
; n
++ )
737 wxFileType
*filetype
= g_mimeManager
.GetFileTypeFromMimeType(mimetypes
[n
]);
740 printf("nothing known about the filetype '%s'!\n",
741 mimetypes
[n
].c_str());
745 filetype
->GetDescription(&desc
);
746 filetype
->GetExtensions(exts
);
748 filetype
->GetIcon(NULL
);
751 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
758 printf("\t%s: %s (%s)\n",
759 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
763 static void TestMimeOverride()
765 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
767 wxString mailcap
= _T("/tmp/mailcap"),
768 mimetypes
= _T("/tmp/mime.types");
770 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
772 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
773 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
775 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
778 static void TestMimeFilename()
780 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
782 static const wxChar
*filenames
[] =
789 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
791 const wxString fname
= filenames
[n
];
792 wxString ext
= fname
.AfterLast(_T('.'));
793 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
796 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
801 if ( !ft
->GetDescription(&desc
) )
802 desc
= _T("<no description>");
805 if ( !ft
->GetOpenCommand(&cmd
,
806 wxFileType::MessageParameters(fname
, _T(""))) )
807 cmd
= _T("<no command available>");
809 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
810 fname
.c_str(), desc
.c_str(), cmd
.c_str());
817 static void TestMimeAssociate()
819 wxPuts(_T("*** Testing creation of filetype association ***\n"));
821 wxFileType
*ft
= g_mimeManager
.Associate
824 _T("application/x-xyz"),
825 _T("XYZFile"), // filetype (MSW only)
826 _T("XYZ File") // description (Unix only)
830 wxPuts(_T("ERROR: failed to create association!"));
834 if ( !ft
->SetOpenCommand(_T("myprogram")) )
836 wxPuts(_T("ERROR: failed to set open command!"));
845 // ----------------------------------------------------------------------------
846 // misc information functions
847 // ----------------------------------------------------------------------------
849 #ifdef TEST_INFO_FUNCTIONS
851 #include <wx/utils.h>
853 static void TestOsInfo()
855 puts("*** Testing OS info functions ***\n");
858 wxGetOsVersion(&major
, &minor
);
859 printf("Running under: %s, version %d.%d\n",
860 wxGetOsDescription().c_str(), major
, minor
);
862 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
864 printf("Host name is %s (%s).\n",
865 wxGetHostName().c_str(), wxGetFullHostName().c_str());
870 static void TestUserInfo()
872 puts("*** Testing user info functions ***\n");
874 printf("User id is:\t%s\n", wxGetUserId().c_str());
875 printf("User name is:\t%s\n", wxGetUserName().c_str());
876 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
877 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
882 #endif // TEST_INFO_FUNCTIONS
884 // ----------------------------------------------------------------------------
886 // ----------------------------------------------------------------------------
890 #include <wx/longlong.h>
891 #include <wx/timer.h>
893 // make a 64 bit number from 4 16 bit ones
894 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
896 // get a random 64 bit number
897 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
899 #if wxUSE_LONGLONG_WX
900 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
901 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
902 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
903 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
904 #endif // wxUSE_LONGLONG_WX
906 static void TestSpeed()
908 static const long max
= 100000000;
915 for ( n
= 0; n
< max
; n
++ )
920 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
923 #if wxUSE_LONGLONG_NATIVE
928 for ( n
= 0; n
< max
; n
++ )
933 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
935 #endif // wxUSE_LONGLONG_NATIVE
941 for ( n
= 0; n
< max
; n
++ )
946 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
950 static void TestLongLongConversion()
952 puts("*** Testing wxLongLong conversions ***\n");
956 for ( size_t n
= 0; n
< 100000; n
++ )
960 #if wxUSE_LONGLONG_NATIVE
961 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
963 wxASSERT_MSG( a
== b
, "conversions failure" );
965 puts("Can't do it without native long long type, test skipped.");
968 #endif // wxUSE_LONGLONG_NATIVE
970 if ( !(nTested
% 1000) )
982 static void TestMultiplication()
984 puts("*** Testing wxLongLong multiplication ***\n");
988 for ( size_t n
= 0; n
< 100000; n
++ )
993 #if wxUSE_LONGLONG_NATIVE
994 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
995 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
997 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
998 #else // !wxUSE_LONGLONG_NATIVE
999 puts("Can't do it without native long long type, test skipped.");
1002 #endif // wxUSE_LONGLONG_NATIVE
1004 if ( !(nTested
% 1000) )
1016 static void TestDivision()
1018 puts("*** Testing wxLongLong division ***\n");
1022 for ( size_t n
= 0; n
< 100000; n
++ )
1024 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1025 // multiplication will not overflow)
1026 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1028 // get a random long (not wxLongLong for now) to divide it with
1033 #if wxUSE_LONGLONG_NATIVE
1034 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1036 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1037 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1038 #else // !wxUSE_LONGLONG_NATIVE
1039 // verify the result
1040 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1041 #endif // wxUSE_LONGLONG_NATIVE
1043 if ( !(nTested
% 1000) )
1055 static void TestAddition()
1057 puts("*** Testing wxLongLong addition ***\n");
1061 for ( size_t n
= 0; n
< 100000; n
++ )
1067 #if wxUSE_LONGLONG_NATIVE
1068 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1069 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1070 "addition failure" );
1071 #else // !wxUSE_LONGLONG_NATIVE
1072 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1073 #endif // wxUSE_LONGLONG_NATIVE
1075 if ( !(nTested
% 1000) )
1087 static void TestBitOperations()
1089 puts("*** Testing wxLongLong bit operation ***\n");
1093 for ( size_t n
= 0; n
< 100000; n
++ )
1097 #if wxUSE_LONGLONG_NATIVE
1098 for ( size_t n
= 0; n
< 33; n
++ )
1101 #else // !wxUSE_LONGLONG_NATIVE
1102 puts("Can't do it without native long long type, test skipped.");
1105 #endif // wxUSE_LONGLONG_NATIVE
1107 if ( !(nTested
% 1000) )
1119 static void TestLongLongComparison()
1121 puts("*** Testing wxLongLong comparison ***\n");
1123 static const long testLongs
[] =
1134 static const long ls
[2] =
1140 wxLongLongWx lls
[2];
1144 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1148 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1150 res
= lls
[m
] > testLongs
[n
];
1151 printf("0x%lx > 0x%lx is %s (%s)\n",
1152 ls
[m
], testLongs
[n
], res
? "true" : "false",
1153 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1155 res
= lls
[m
] < testLongs
[n
];
1156 printf("0x%lx < 0x%lx is %s (%s)\n",
1157 ls
[m
], testLongs
[n
], res
? "true" : "false",
1158 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1160 res
= lls
[m
] == testLongs
[n
];
1161 printf("0x%lx == 0x%lx is %s (%s)\n",
1162 ls
[m
], testLongs
[n
], res
? "true" : "false",
1163 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1171 #endif // TEST_LONGLONG
1173 // ----------------------------------------------------------------------------
1175 // ----------------------------------------------------------------------------
1177 // this is for MSW only
1179 #undef TEST_REGISTRY
1182 #ifdef TEST_REGISTRY
1184 #include <wx/msw/registry.h>
1186 // I chose this one because I liked its name, but it probably only exists under
1188 static const wxChar
*TESTKEY
=
1189 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1191 static void TestRegistryRead()
1193 puts("*** testing registry reading ***");
1195 wxRegKey
key(TESTKEY
);
1196 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1199 puts("ERROR: test key can't be opened, aborting test.");
1204 size_t nSubKeys
, nValues
;
1205 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1207 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1210 printf("Enumerating values:\n");
1214 bool cont
= key
.GetFirstValue(value
, dummy
);
1217 printf("Value '%s': type ", value
.c_str());
1218 switch ( key
.GetValueType(value
) )
1220 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1221 case wxRegKey::Type_String
: printf("SZ"); break;
1222 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1223 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1224 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1225 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1226 default: printf("other (unknown)"); break;
1229 printf(", value = ");
1230 if ( key
.IsNumericValue(value
) )
1233 key
.QueryValue(value
, &val
);
1239 key
.QueryValue(value
, val
);
1240 printf("'%s'", val
.c_str());
1242 key
.QueryRawValue(value
, val
);
1243 printf(" (raw value '%s')", val
.c_str());
1248 cont
= key
.GetNextValue(value
, dummy
);
1252 static void TestRegistryAssociation()
1255 The second call to deleteself genertaes an error message, with a
1256 messagebox saying .flo is crucial to system operation, while the .ddf
1257 call also fails, but with no error message
1262 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1264 key
= "ddxf_auto_file" ;
1265 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1267 key
= "ddxf_auto_file" ;
1268 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1271 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1273 key
= "program \"%1\"" ;
1275 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1277 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1279 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1281 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1285 #endif // TEST_REGISTRY
1287 // ----------------------------------------------------------------------------
1289 // ----------------------------------------------------------------------------
1293 #include <wx/socket.h>
1294 #include <wx/protocol/protocol.h>
1295 #include <wx/protocol/http.h>
1297 static void TestSocketServer()
1299 puts("*** Testing wxSocketServer ***\n");
1301 static const int PORT
= 3000;
1306 wxSocketServer
*server
= new wxSocketServer(addr
);
1307 if ( !server
->Ok() )
1309 puts("ERROR: failed to bind");
1316 printf("Server: waiting for connection on port %d...\n", PORT
);
1318 wxSocketBase
*socket
= server
->Accept();
1321 puts("ERROR: wxSocketServer::Accept() failed.");
1325 puts("Server: got a client.");
1327 server
->SetTimeout(60); // 1 min
1329 while ( socket
->IsConnected() )
1335 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1337 // don't log error if the client just close the connection
1338 if ( socket
->IsConnected() )
1340 puts("ERROR: in wxSocket::Read.");
1360 printf("Server: got '%s'.\n", s
.c_str());
1361 if ( s
== _T("bye") )
1368 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1369 socket
->Write("\r\n", 2);
1370 printf("Server: wrote '%s'.\n", s
.c_str());
1373 puts("Server: lost a client.");
1378 // same as "delete server" but is consistent with GUI programs
1382 static void TestSocketClient()
1384 puts("*** Testing wxSocketClient ***\n");
1386 static const char *hostname
= "www.wxwindows.org";
1389 addr
.Hostname(hostname
);
1392 printf("--- Attempting to connect to %s:80...\n", hostname
);
1394 wxSocketClient client
;
1395 if ( !client
.Connect(addr
) )
1397 printf("ERROR: failed to connect to %s\n", hostname
);
1401 printf("--- Connected to %s:%u...\n",
1402 addr
.Hostname().c_str(), addr
.Service());
1406 // could use simply "GET" here I suppose
1408 wxString::Format("GET http://%s/\r\n", hostname
);
1409 client
.Write(cmdGet
, cmdGet
.length());
1410 printf("--- Sent command '%s' to the server\n",
1411 MakePrintable(cmdGet
).c_str());
1412 client
.Read(buf
, WXSIZEOF(buf
));
1413 printf("--- Server replied:\n%s", buf
);
1417 #endif // TEST_SOCKETS
1421 #include <wx/protocol/ftp.h>
1423 static void TestProtocolFtp()
1425 puts("*** Testing wxFTP download ***\n");
1429 static const char *hostname
= "ftp.wxwindows.org";
1430 static const char *directory
= "pub";
1432 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1434 static const char *hostname
= "localhost";
1435 static const char *user
= "zeitlin";
1436 static const char *directory
= "/tmp";
1439 ftp
.SetPassword("password");
1441 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1444 if ( !ftp
.Connect(hostname
) )
1446 printf("ERROR: failed to connect to %s\n", hostname
);
1450 printf("--- Connected to %s, current directory is '%s'\n",
1451 hostname
, ftp
.Pwd().c_str());
1454 if ( !ftp
.ChDir(directory
) )
1456 printf("ERROR: failed to cd to %s\n", directory
);
1459 // test NLIST and LIST
1460 wxArrayString files
;
1461 if ( !ftp
.GetFilesList(files
) )
1463 puts("ERROR: failed to get NLIST of files");
1467 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1468 size_t count
= files
.GetCount();
1469 for ( size_t n
= 0; n
< count
; n
++ )
1471 printf("\t%s\n", files
[n
].c_str());
1473 puts("End of the file list");
1476 if ( !ftp
.GetDirList(files
) )
1478 puts("ERROR: failed to get LIST of files");
1482 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1483 size_t count
= files
.GetCount();
1484 for ( size_t n
= 0; n
< count
; n
++ )
1486 printf("\t%s\n", files
[n
].c_str());
1488 puts("End of the file list");
1491 if ( !ftp
.ChDir(_T("..")) )
1493 puts("ERROR: failed to cd to ..");
1497 static const char *filename
= "welcome.msg";
1498 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1501 printf("ERROR: couldn't get input stream for %s\n", filename
);
1505 size_t size
= in
->StreamSize();
1506 printf("Reading file %s (%u bytes)...", filename
, size
);
1508 char *data
= new char[size
];
1509 if ( !in
->Read(data
, size
) )
1511 puts("ERROR: read error");
1515 printf("\nContents of %s:\n%s\n", filename
, data
);
1522 // test some other FTP commands
1523 if ( ftp
.SendCommand("STAT") != '2' )
1525 puts("ERROR: STAT failed");
1529 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1532 if ( ftp
.SendCommand("HELP SITE") != '2' )
1534 puts("ERROR: HELP SITE failed");
1538 printf("The list of site-specific commands:\n\n%s\n",
1539 ftp
.GetLastResult().c_str());
1544 static void TestProtocolFtpUpload()
1546 puts("*** Testing wxFTP uploading ***\n");
1548 static const char *hostname
= "localhost";
1550 printf("--- Attempting to connect to %s:21...\n", hostname
);
1553 ftp
.SetUser("zeitlin");
1554 ftp
.SetPassword("password");
1555 if ( !ftp
.Connect(hostname
) )
1557 printf("ERROR: failed to connect to %s\n", hostname
);
1561 printf("--- Connected to %s, current directory is '%s'\n",
1562 hostname
, ftp
.Pwd().c_str());
1565 static const char *file1
= "test1";
1566 static const char *file2
= "test2";
1567 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1570 printf("--- Uploading to %s ---\n", file1
);
1571 out
->Write("First hello", 11);
1575 // send a command to check the remote file
1576 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1578 printf("ERROR: STAT %s failed\n", file1
);
1582 printf("STAT %s returned:\n\n%s\n",
1583 file1
, ftp
.GetLastResult().c_str());
1586 out
= ftp
.GetOutputStream(file2
);
1589 printf("--- Uploading to %s ---\n", file1
);
1590 out
->Write("Second hello", 12);
1598 // ----------------------------------------------------------------------------
1600 // ----------------------------------------------------------------------------
1604 #include <wx/mstream.h>
1606 static void TestMemoryStream()
1608 puts("*** Testing wxMemoryInputStream ***");
1611 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1613 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1614 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1615 while ( !memInpStream
.Eof() )
1617 putchar(memInpStream
.GetC());
1620 puts("\n*** wxMemoryInputStream test done ***");
1623 #endif // TEST_STREAMS
1625 // ----------------------------------------------------------------------------
1627 // ----------------------------------------------------------------------------
1631 #include <wx/timer.h>
1632 #include <wx/utils.h>
1634 static void TestStopWatch()
1636 puts("*** Testing wxStopWatch ***\n");
1639 printf("Sleeping 3 seconds...");
1641 printf("\telapsed time: %ldms\n", sw
.Time());
1644 printf("Sleeping 2 more seconds...");
1646 printf("\telapsed time: %ldms\n", sw
.Time());
1649 printf("And 3 more seconds...");
1651 printf("\telapsed time: %ldms\n", sw
.Time());
1654 puts("\nChecking for 'backwards clock' bug...");
1655 for ( size_t n
= 0; n
< 70; n
++ )
1659 for ( size_t m
= 0; m
< 100000; m
++ )
1661 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1663 puts("\ntime is negative - ERROR!");
1673 #endif // TEST_TIMER
1675 // ----------------------------------------------------------------------------
1677 // ----------------------------------------------------------------------------
1681 #include <wx/vcard.h>
1683 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1686 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1690 wxString(_T('\t'), level
).c_str(),
1691 vcObj
->GetName().c_str());
1694 switch ( vcObj
->GetType() )
1696 case wxVCardObject::String
:
1697 case wxVCardObject::UString
:
1700 vcObj
->GetValue(&val
);
1701 value
<< _T('"') << val
<< _T('"');
1705 case wxVCardObject::Int
:
1708 vcObj
->GetValue(&i
);
1709 value
.Printf(_T("%u"), i
);
1713 case wxVCardObject::Long
:
1716 vcObj
->GetValue(&l
);
1717 value
.Printf(_T("%lu"), l
);
1721 case wxVCardObject::None
:
1724 case wxVCardObject::Object
:
1725 value
= _T("<node>");
1729 value
= _T("<unknown value type>");
1733 printf(" = %s", value
.c_str());
1736 DumpVObject(level
+ 1, *vcObj
);
1739 vcObj
= vcard
.GetNextProp(&cookie
);
1743 static void DumpVCardAddresses(const wxVCard
& vcard
)
1745 puts("\nShowing all addresses from vCard:\n");
1749 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1753 int flags
= addr
->GetFlags();
1754 if ( flags
& wxVCardAddress::Domestic
)
1756 flagsStr
<< _T("domestic ");
1758 if ( flags
& wxVCardAddress::Intl
)
1760 flagsStr
<< _T("international ");
1762 if ( flags
& wxVCardAddress::Postal
)
1764 flagsStr
<< _T("postal ");
1766 if ( flags
& wxVCardAddress::Parcel
)
1768 flagsStr
<< _T("parcel ");
1770 if ( flags
& wxVCardAddress::Home
)
1772 flagsStr
<< _T("home ");
1774 if ( flags
& wxVCardAddress::Work
)
1776 flagsStr
<< _T("work ");
1779 printf("Address %u:\n"
1781 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1784 addr
->GetPostOffice().c_str(),
1785 addr
->GetExtAddress().c_str(),
1786 addr
->GetStreet().c_str(),
1787 addr
->GetLocality().c_str(),
1788 addr
->GetRegion().c_str(),
1789 addr
->GetPostalCode().c_str(),
1790 addr
->GetCountry().c_str()
1794 addr
= vcard
.GetNextAddress(&cookie
);
1798 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
1800 puts("\nShowing all phone numbers from vCard:\n");
1804 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
1808 int flags
= phone
->GetFlags();
1809 if ( flags
& wxVCardPhoneNumber::Voice
)
1811 flagsStr
<< _T("voice ");
1813 if ( flags
& wxVCardPhoneNumber::Fax
)
1815 flagsStr
<< _T("fax ");
1817 if ( flags
& wxVCardPhoneNumber::Cellular
)
1819 flagsStr
<< _T("cellular ");
1821 if ( flags
& wxVCardPhoneNumber::Modem
)
1823 flagsStr
<< _T("modem ");
1825 if ( flags
& wxVCardPhoneNumber::Home
)
1827 flagsStr
<< _T("home ");
1829 if ( flags
& wxVCardPhoneNumber::Work
)
1831 flagsStr
<< _T("work ");
1834 printf("Phone number %u:\n"
1839 phone
->GetNumber().c_str()
1843 phone
= vcard
.GetNextPhoneNumber(&cookie
);
1847 static void TestVCardRead()
1849 puts("*** Testing wxVCard reading ***\n");
1851 wxVCard
vcard(_T("vcard.vcf"));
1852 if ( !vcard
.IsOk() )
1854 puts("ERROR: couldn't load vCard.");
1858 // read individual vCard properties
1859 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
1863 vcObj
->GetValue(&value
);
1868 value
= _T("<none>");
1871 printf("Full name retrieved directly: %s\n", value
.c_str());
1874 if ( !vcard
.GetFullName(&value
) )
1876 value
= _T("<none>");
1879 printf("Full name from wxVCard API: %s\n", value
.c_str());
1881 // now show how to deal with multiply occuring properties
1882 DumpVCardAddresses(vcard
);
1883 DumpVCardPhoneNumbers(vcard
);
1885 // and finally show all
1886 puts("\nNow dumping the entire vCard:\n"
1887 "-----------------------------\n");
1889 DumpVObject(0, vcard
);
1893 static void TestVCardWrite()
1895 puts("*** Testing wxVCard writing ***\n");
1898 if ( !vcard
.IsOk() )
1900 puts("ERROR: couldn't create vCard.");
1905 vcard
.SetName("Zeitlin", "Vadim");
1906 vcard
.SetFullName("Vadim Zeitlin");
1907 vcard
.SetOrganization("wxWindows", "R&D");
1909 // just dump the vCard back
1910 puts("Entire vCard follows:\n");
1911 puts(vcard
.Write());
1915 #endif // TEST_VCARD
1917 // ----------------------------------------------------------------------------
1918 // wide char (Unicode) support
1919 // ----------------------------------------------------------------------------
1923 #include <wx/strconv.h>
1924 #include <wx/buffer.h>
1926 static void TestUtf8()
1928 puts("*** Testing UTF8 support ***\n");
1930 wxString testString
= "français";
1932 "************ French - Français ****************"
1933 "Juste un petit exemple pour dire que les français aussi"
1934 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
1937 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
1938 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
1939 wxString
testString2(pwz
, wxConvLocal
);
1941 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
1943 char *psz
= "fran" "\xe7" "ais";
1944 size_t len
= strlen(psz
);
1945 wchar_t *pwz2
= new wchar_t[len
+ 1];
1946 for ( size_t n
= 0; n
<= len
; n
++ )
1948 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
1951 wxString
testString3(pwz2
, wxConvUTF8
);
1954 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
1957 #endif // TEST_WCHAR
1959 // ----------------------------------------------------------------------------
1961 // ----------------------------------------------------------------------------
1965 #include "wx/zipstrm.h"
1967 static void TestZipStreamRead()
1969 puts("*** Testing ZIP reading ***\n");
1971 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
1972 printf("Archive size: %u\n", istr
.GetSize());
1974 puts("Dumping the file:");
1975 while ( !istr
.Eof() )
1977 putchar(istr
.GetC());
1981 puts("\n----- done ------");
1986 // ----------------------------------------------------------------------------
1988 // ----------------------------------------------------------------------------
1992 #include <wx/zstream.h>
1993 #include <wx/wfstream.h>
1995 static const wxChar
*FILENAME_GZ
= _T("test.gz");
1996 static const char *TEST_DATA
= "hello and hello again";
1998 static void TestZlibStreamWrite()
2000 puts("*** Testing Zlib stream reading ***\n");
2002 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2003 wxZlibOutputStream
ostr(fileOutStream
, 0);
2004 printf("Compressing the test string... ");
2005 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2008 puts("(ERROR: failed)");
2015 puts("\n----- done ------");
2018 static void TestZlibStreamRead()
2020 puts("*** Testing Zlib stream reading ***\n");
2022 wxFileInputStream
fileInStream(FILENAME_GZ
);
2023 wxZlibInputStream
istr(fileInStream
);
2024 printf("Archive size: %u\n", istr
.GetSize());
2026 puts("Dumping the file:");
2027 while ( !istr
.Eof() )
2029 putchar(istr
.GetC());
2033 puts("\n----- done ------");
2038 // ----------------------------------------------------------------------------
2040 // ----------------------------------------------------------------------------
2042 #ifdef TEST_DATETIME
2044 #include <wx/date.h>
2046 #include <wx/datetime.h>
2051 wxDateTime::wxDateTime_t day
;
2052 wxDateTime::Month month
;
2054 wxDateTime::wxDateTime_t hour
, min
, sec
;
2056 wxDateTime::WeekDay wday
;
2057 time_t gmticks
, ticks
;
2059 void Init(const wxDateTime::Tm
& tm
)
2068 gmticks
= ticks
= -1;
2071 wxDateTime
DT() const
2072 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2074 bool SameDay(const wxDateTime::Tm
& tm
) const
2076 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2079 wxString
Format() const
2082 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2084 wxDateTime::GetMonthName(month
).c_str(),
2086 abs(wxDateTime::ConvertYearToBC(year
)),
2087 year
> 0 ? "AD" : "BC");
2091 wxString
FormatDate() const
2094 s
.Printf("%02d-%s-%4d%s",
2096 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2097 abs(wxDateTime::ConvertYearToBC(year
)),
2098 year
> 0 ? "AD" : "BC");
2103 static const Date testDates
[] =
2105 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2106 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2107 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2108 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2109 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2110 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2111 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2112 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2113 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2114 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2115 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2116 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2117 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2118 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2119 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2122 // this test miscellaneous static wxDateTime functions
2123 static void TestTimeStatic()
2125 puts("\n*** wxDateTime static methods test ***");
2127 // some info about the current date
2128 int year
= wxDateTime::GetCurrentYear();
2129 printf("Current year %d is %sa leap one and has %d days.\n",
2131 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2132 wxDateTime::GetNumberOfDays(year
));
2134 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2135 printf("Current month is '%s' ('%s') and it has %d days\n",
2136 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2137 wxDateTime::GetMonthName(month
).c_str(),
2138 wxDateTime::GetNumberOfDays(month
));
2141 static const size_t nYears
= 5;
2142 static const size_t years
[2][nYears
] =
2144 // first line: the years to test
2145 { 1990, 1976, 2000, 2030, 1984, },
2147 // second line: TRUE if leap, FALSE otherwise
2148 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2151 for ( size_t n
= 0; n
< nYears
; n
++ )
2153 int year
= years
[0][n
];
2154 bool should
= years
[1][n
] != 0,
2155 is
= wxDateTime::IsLeapYear(year
);
2157 printf("Year %d is %sa leap year (%s)\n",
2160 should
== is
? "ok" : "ERROR");
2162 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2166 // test constructing wxDateTime objects
2167 static void TestTimeSet()
2169 puts("\n*** wxDateTime construction test ***");
2171 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2173 const Date
& d1
= testDates
[n
];
2174 wxDateTime dt
= d1
.DT();
2177 d2
.Init(dt
.GetTm());
2179 wxString s1
= d1
.Format(),
2182 printf("Date: %s == %s (%s)\n",
2183 s1
.c_str(), s2
.c_str(),
2184 s1
== s2
? "ok" : "ERROR");
2188 // test time zones stuff
2189 static void TestTimeZones()
2191 puts("\n*** wxDateTime timezone test ***");
2193 wxDateTime now
= wxDateTime::Now();
2195 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2196 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2197 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2198 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2199 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2200 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2202 wxDateTime::Tm tm
= now
.GetTm();
2203 if ( wxDateTime(tm
) != now
)
2205 printf("ERROR: got %s instead of %s\n",
2206 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2210 // test some minimal support for the dates outside the standard range
2211 static void TestTimeRange()
2213 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2215 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2217 printf("Unix epoch:\t%s\n",
2218 wxDateTime(2440587.5).Format(fmt
).c_str());
2219 printf("Feb 29, 0: \t%s\n",
2220 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2221 printf("JDN 0: \t%s\n",
2222 wxDateTime(0.0).Format(fmt
).c_str());
2223 printf("Jan 1, 1AD:\t%s\n",
2224 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2225 printf("May 29, 2099:\t%s\n",
2226 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2229 static void TestTimeTicks()
2231 puts("\n*** wxDateTime ticks test ***");
2233 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2235 const Date
& d
= testDates
[n
];
2236 if ( d
.ticks
== -1 )
2239 wxDateTime dt
= d
.DT();
2240 long ticks
= (dt
.GetValue() / 1000).ToLong();
2241 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2242 if ( ticks
== d
.ticks
)
2248 printf(" (ERROR: should be %ld, delta = %ld)\n",
2249 d
.ticks
, ticks
- d
.ticks
);
2252 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2253 ticks
= (dt
.GetValue() / 1000).ToLong();
2254 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2255 if ( ticks
== d
.gmticks
)
2261 printf(" (ERROR: should be %ld, delta = %ld)\n",
2262 d
.gmticks
, ticks
- d
.gmticks
);
2269 // test conversions to JDN &c
2270 static void TestTimeJDN()
2272 puts("\n*** wxDateTime to JDN test ***");
2274 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2276 const Date
& d
= testDates
[n
];
2277 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2278 double jdn
= dt
.GetJulianDayNumber();
2280 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2287 printf(" (ERROR: should be %f, delta = %f)\n",
2288 d
.jdn
, jdn
- d
.jdn
);
2293 // test week days computation
2294 static void TestTimeWDays()
2296 puts("\n*** wxDateTime weekday test ***");
2298 // test GetWeekDay()
2300 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2302 const Date
& d
= testDates
[n
];
2303 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2305 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2308 wxDateTime::GetWeekDayName(wday
).c_str());
2309 if ( wday
== d
.wday
)
2315 printf(" (ERROR: should be %s)\n",
2316 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2322 // test SetToWeekDay()
2323 struct WeekDateTestData
2325 Date date
; // the real date (precomputed)
2326 int nWeek
; // its week index in the month
2327 wxDateTime::WeekDay wday
; // the weekday
2328 wxDateTime::Month month
; // the month
2329 int year
; // and the year
2331 wxString
Format() const
2334 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2336 case 1: which
= "first"; break;
2337 case 2: which
= "second"; break;
2338 case 3: which
= "third"; break;
2339 case 4: which
= "fourth"; break;
2340 case 5: which
= "fifth"; break;
2342 case -1: which
= "last"; break;
2347 which
+= " from end";
2350 s
.Printf("The %s %s of %s in %d",
2352 wxDateTime::GetWeekDayName(wday
).c_str(),
2353 wxDateTime::GetMonthName(month
).c_str(),
2360 // the array data was generated by the following python program
2362 from DateTime import *
2363 from whrandom import *
2364 from string import *
2366 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2367 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2369 week = DateTimeDelta(7)
2372 year = randint(1900, 2100)
2373 month = randint(1, 12)
2374 day = randint(1, 28)
2375 dt = DateTime(year, month, day)
2376 wday = dt.day_of_week
2378 countFromEnd = choice([-1, 1])
2381 while dt.month is month:
2382 dt = dt - countFromEnd * week
2383 weekNum = weekNum + countFromEnd
2385 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2387 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2388 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2391 static const WeekDateTestData weekDatesTestData
[] =
2393 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2394 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2395 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2396 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2397 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2398 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2399 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2400 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2401 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2402 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2403 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2404 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2405 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2406 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2407 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2408 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2409 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2410 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2411 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2412 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2415 static const char *fmt
= "%d-%b-%Y";
2418 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2420 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2422 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2424 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2426 const Date
& d
= wd
.date
;
2427 if ( d
.SameDay(dt
.GetTm()) )
2433 dt
.Set(d
.day
, d
.month
, d
.year
);
2435 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2440 // test the computation of (ISO) week numbers
2441 static void TestTimeWNumber()
2443 puts("\n*** wxDateTime week number test ***");
2445 struct WeekNumberTestData
2447 Date date
; // the date
2448 wxDateTime::wxDateTime_t week
; // the week number in the year
2449 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2450 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2451 wxDateTime::wxDateTime_t dnum
; // day number in the year
2454 // data generated with the following python script:
2456 from DateTime import *
2457 from whrandom import *
2458 from string import *
2460 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2461 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2463 def GetMonthWeek(dt):
2464 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2465 if weekNumMonth < 0:
2466 weekNumMonth = weekNumMonth + 53
2469 def GetLastSundayBefore(dt):
2470 if dt.iso_week[2] == 7:
2473 return dt - DateTimeDelta(dt.iso_week[2])
2476 year = randint(1900, 2100)
2477 month = randint(1, 12)
2478 day = randint(1, 28)
2479 dt = DateTime(year, month, day)
2480 dayNum = dt.day_of_year
2481 weekNum = dt.iso_week[1]
2482 weekNumMonth = GetMonthWeek(dt)
2485 dtSunday = GetLastSundayBefore(dt)
2487 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2488 weekNumMonth2 = weekNumMonth2 + 1
2489 dtSunday = dtSunday - DateTimeDelta(7)
2491 data = { 'day': rjust(`day`, 2), \
2492 'month': monthNames[month - 1], \
2494 'weekNum': rjust(`weekNum`, 2), \
2495 'weekNumMonth': weekNumMonth, \
2496 'weekNumMonth2': weekNumMonth2, \
2497 'dayNum': rjust(`dayNum`, 3) }
2499 print " { { %(day)s, "\
2500 "wxDateTime::%(month)s, "\
2503 "%(weekNumMonth)s, "\
2504 "%(weekNumMonth2)s, "\
2505 "%(dayNum)s }," % data
2508 static const WeekNumberTestData weekNumberTestDates
[] =
2510 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2511 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2512 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2513 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2514 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2515 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2516 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2517 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2518 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2519 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2520 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2521 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2522 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2523 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2524 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2525 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2526 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2527 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2528 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2529 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2532 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2534 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2535 const Date
& d
= wn
.date
;
2537 wxDateTime dt
= d
.DT();
2539 wxDateTime::wxDateTime_t
2540 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2541 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2542 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2543 dnum
= dt
.GetDayOfYear();
2545 printf("%s: the day number is %d",
2546 d
.FormatDate().c_str(), dnum
);
2547 if ( dnum
== wn
.dnum
)
2553 printf(" (ERROR: should be %d)", wn
.dnum
);
2556 printf(", week in month is %d", wmon
);
2557 if ( wmon
== wn
.wmon
)
2563 printf(" (ERROR: should be %d)", wn
.wmon
);
2566 printf(" or %d", wmon2
);
2567 if ( wmon2
== wn
.wmon2
)
2573 printf(" (ERROR: should be %d)", wn
.wmon2
);
2576 printf(", week in year is %d", week
);
2577 if ( week
== wn
.week
)
2583 printf(" (ERROR: should be %d)\n", wn
.week
);
2588 // test DST calculations
2589 static void TestTimeDST()
2591 puts("\n*** wxDateTime DST test ***");
2593 printf("DST is%s in effect now.\n\n",
2594 wxDateTime::Now().IsDST() ? "" : " not");
2596 // taken from http://www.energy.ca.gov/daylightsaving.html
2597 static const Date datesDST
[2][2004 - 1900 + 1] =
2600 { 1, wxDateTime::Apr
, 1990 },
2601 { 7, wxDateTime::Apr
, 1991 },
2602 { 5, wxDateTime::Apr
, 1992 },
2603 { 4, wxDateTime::Apr
, 1993 },
2604 { 3, wxDateTime::Apr
, 1994 },
2605 { 2, wxDateTime::Apr
, 1995 },
2606 { 7, wxDateTime::Apr
, 1996 },
2607 { 6, wxDateTime::Apr
, 1997 },
2608 { 5, wxDateTime::Apr
, 1998 },
2609 { 4, wxDateTime::Apr
, 1999 },
2610 { 2, wxDateTime::Apr
, 2000 },
2611 { 1, wxDateTime::Apr
, 2001 },
2612 { 7, wxDateTime::Apr
, 2002 },
2613 { 6, wxDateTime::Apr
, 2003 },
2614 { 4, wxDateTime::Apr
, 2004 },
2617 { 28, wxDateTime::Oct
, 1990 },
2618 { 27, wxDateTime::Oct
, 1991 },
2619 { 25, wxDateTime::Oct
, 1992 },
2620 { 31, wxDateTime::Oct
, 1993 },
2621 { 30, wxDateTime::Oct
, 1994 },
2622 { 29, wxDateTime::Oct
, 1995 },
2623 { 27, wxDateTime::Oct
, 1996 },
2624 { 26, wxDateTime::Oct
, 1997 },
2625 { 25, wxDateTime::Oct
, 1998 },
2626 { 31, wxDateTime::Oct
, 1999 },
2627 { 29, wxDateTime::Oct
, 2000 },
2628 { 28, wxDateTime::Oct
, 2001 },
2629 { 27, wxDateTime::Oct
, 2002 },
2630 { 26, wxDateTime::Oct
, 2003 },
2631 { 31, wxDateTime::Oct
, 2004 },
2636 for ( year
= 1990; year
< 2005; year
++ )
2638 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2639 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2641 printf("DST period in the US for year %d: from %s to %s",
2642 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2644 size_t n
= year
- 1990;
2645 const Date
& dBegin
= datesDST
[0][n
];
2646 const Date
& dEnd
= datesDST
[1][n
];
2648 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2654 printf(" (ERROR: should be %s %d to %s %d)\n",
2655 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2656 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2662 for ( year
= 1990; year
< 2005; year
++ )
2664 printf("DST period in Europe for year %d: from %s to %s\n",
2666 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2667 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2671 // test wxDateTime -> text conversion
2672 static void TestTimeFormat()
2674 puts("\n*** wxDateTime formatting test ***");
2676 // some information may be lost during conversion, so store what kind
2677 // of info should we recover after a round trip
2680 CompareNone
, // don't try comparing
2681 CompareBoth
, // dates and times should be identical
2682 CompareDate
, // dates only
2683 CompareTime
// time only
2688 CompareKind compareKind
;
2690 } formatTestFormats
[] =
2692 { CompareBoth
, "---> %c" },
2693 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2694 { CompareBoth
, "Date is %x, time is %X" },
2695 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2696 { CompareNone
, "The day of year: %j, the week of year: %W" },
2697 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2700 static const Date formatTestDates
[] =
2702 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2703 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2705 // this test can't work for other centuries because it uses two digit
2706 // years in formats, so don't even try it
2707 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2708 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2709 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2713 // an extra test (as it doesn't depend on date, don't do it in the loop)
2714 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2716 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2720 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2721 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2723 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2724 printf("%s", s
.c_str());
2726 // what can we recover?
2727 int kind
= formatTestFormats
[n
].compareKind
;
2731 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2734 // converion failed - should it have?
2735 if ( kind
== CompareNone
)
2738 puts(" (ERROR: conversion back failed)");
2742 // should have parsed the entire string
2743 puts(" (ERROR: conversion back stopped too soon)");
2747 bool equal
= FALSE
; // suppress compilaer warning
2755 equal
= dt
.IsSameDate(dt2
);
2759 equal
= dt
.IsSameTime(dt2
);
2765 printf(" (ERROR: got back '%s' instead of '%s')\n",
2766 dt2
.Format().c_str(), dt
.Format().c_str());
2777 // test text -> wxDateTime conversion
2778 static void TestTimeParse()
2780 puts("\n*** wxDateTime parse test ***");
2782 struct ParseTestData
2789 static const ParseTestData parseTestDates
[] =
2791 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
2792 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
2795 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
2797 const char *format
= parseTestDates
[n
].format
;
2799 printf("%s => ", format
);
2802 if ( dt
.ParseRfc822Date(format
) )
2804 printf("%s ", dt
.Format().c_str());
2806 if ( parseTestDates
[n
].good
)
2808 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
2815 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
2820 puts("(ERROR: bad format)");
2825 printf("bad format (%s)\n",
2826 parseTestDates
[n
].good
? "ERROR" : "ok");
2831 static void TestInteractive()
2833 puts("\n*** interactive wxDateTime tests ***");
2839 printf("Enter a date: ");
2840 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2843 // kill the last '\n'
2844 buf
[strlen(buf
) - 1] = 0;
2847 const char *p
= dt
.ParseDate(buf
);
2850 printf("ERROR: failed to parse the date '%s'.\n", buf
);
2856 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
2859 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2860 dt
.Format("%b %d, %Y").c_str(),
2862 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2863 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2864 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
2867 puts("\n*** done ***");
2870 static void TestTimeMS()
2872 puts("*** testing millisecond-resolution support in wxDateTime ***");
2874 wxDateTime dt1
= wxDateTime::Now(),
2875 dt2
= wxDateTime::UNow();
2877 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
2878 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2879 printf("Dummy loop: ");
2880 for ( int i
= 0; i
< 6000; i
++ )
2882 //for ( int j = 0; j < 10; j++ )
2885 s
.Printf("%g", sqrt(i
));
2894 dt2
= wxDateTime::UNow();
2895 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2897 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
2899 puts("\n*** done ***");
2902 static void TestTimeArithmetics()
2904 puts("\n*** testing arithmetic operations on wxDateTime ***");
2906 static const struct ArithmData
2908 ArithmData(const wxDateSpan
& sp
, const char *nam
)
2909 : span(sp
), name(nam
) { }
2913 } testArithmData
[] =
2915 ArithmData(wxDateSpan::Day(), "day"),
2916 ArithmData(wxDateSpan::Week(), "week"),
2917 ArithmData(wxDateSpan::Month(), "month"),
2918 ArithmData(wxDateSpan::Year(), "year"),
2919 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
2922 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
2924 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
2926 wxDateSpan span
= testArithmData
[n
].span
;
2930 const char *name
= testArithmData
[n
].name
;
2931 printf("%s + %s = %s, %s - %s = %s\n",
2932 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
2933 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
2935 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
2936 if ( dt1
- span
== dt
)
2942 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
2945 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
2946 if ( dt2
+ span
== dt
)
2952 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
2955 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
2956 if ( dt2
+ 2*span
== dt1
)
2962 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
2969 static void TestTimeHolidays()
2971 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
2973 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
2974 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
2975 dtEnd
= dtStart
.GetLastMonthDay();
2977 wxDateTimeArray hol
;
2978 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
2980 const wxChar
*format
= "%d-%b-%Y (%a)";
2982 printf("All holidays between %s and %s:\n",
2983 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
2985 size_t count
= hol
.GetCount();
2986 for ( size_t n
= 0; n
< count
; n
++ )
2988 printf("\t%s\n", hol
[n
].Format(format
).c_str());
2994 static void TestTimeZoneBug()
2996 puts("\n*** testing for DST/timezone bug ***\n");
2998 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
2999 for ( int i
= 0; i
< 31; i
++ )
3001 printf("Date %s: week day %s.\n",
3002 date
.Format(_T("%d-%m-%Y")).c_str(),
3003 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3005 date
+= wxDateSpan::Day();
3013 // test compatibility with the old wxDate/wxTime classes
3014 static void TestTimeCompatibility()
3016 puts("\n*** wxDateTime compatibility test ***");
3018 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3019 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3021 double jdnNow
= wxDateTime::Now().GetJDN();
3022 long jdnMidnight
= (long)(jdnNow
- 0.5);
3023 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3025 jdnMidnight
= wxDate().Set().GetJulianDate();
3026 printf("wxDateTime for today: %s\n",
3027 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3029 int flags
= wxEUROPEAN
;//wxFULL;
3032 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3033 for ( int n
= 0; n
< 7; n
++ )
3035 printf("Previous %s is %s\n",
3036 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3037 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3043 #endif // TEST_DATETIME
3045 // ----------------------------------------------------------------------------
3047 // ----------------------------------------------------------------------------
3051 #include <wx/thread.h>
3053 static size_t gs_counter
= (size_t)-1;
3054 static wxCriticalSection gs_critsect
;
3055 static wxCondition gs_cond
;
3057 class MyJoinableThread
: public wxThread
3060 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3061 { m_n
= n
; Create(); }
3063 // thread execution starts here
3064 virtual ExitCode
Entry();
3070 wxThread::ExitCode
MyJoinableThread::Entry()
3072 unsigned long res
= 1;
3073 for ( size_t n
= 1; n
< m_n
; n
++ )
3077 // it's a loooong calculation :-)
3081 return (ExitCode
)res
;
3084 class MyDetachedThread
: public wxThread
3087 MyDetachedThread(size_t n
, char ch
)
3091 m_cancelled
= FALSE
;
3096 // thread execution starts here
3097 virtual ExitCode
Entry();
3100 virtual void OnExit();
3103 size_t m_n
; // number of characters to write
3104 char m_ch
; // character to write
3106 bool m_cancelled
; // FALSE if we exit normally
3109 wxThread::ExitCode
MyDetachedThread::Entry()
3112 wxCriticalSectionLocker
lock(gs_critsect
);
3113 if ( gs_counter
== (size_t)-1 )
3119 for ( size_t n
= 0; n
< m_n
; n
++ )
3121 if ( TestDestroy() )
3131 wxThread::Sleep(100);
3137 void MyDetachedThread::OnExit()
3139 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3141 wxCriticalSectionLocker
lock(gs_critsect
);
3142 if ( !--gs_counter
&& !m_cancelled
)
3146 void TestDetachedThreads()
3148 puts("\n*** Testing detached threads ***");
3150 static const size_t nThreads
= 3;
3151 MyDetachedThread
*threads
[nThreads
];
3153 for ( n
= 0; n
< nThreads
; n
++ )
3155 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3158 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3159 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3161 for ( n
= 0; n
< nThreads
; n
++ )
3166 // wait until all threads terminate
3172 void TestJoinableThreads()
3174 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3176 // calc 10! in the background
3177 MyJoinableThread
thread(10);
3180 printf("\nThread terminated with exit code %lu.\n",
3181 (unsigned long)thread
.Wait());
3184 void TestThreadSuspend()
3186 puts("\n*** Testing thread suspend/resume functions ***");
3188 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3192 // this is for this demo only, in a real life program we'd use another
3193 // condition variable which would be signaled from wxThread::Entry() to
3194 // tell us that the thread really started running - but here just wait a
3195 // bit and hope that it will be enough (the problem is, of course, that
3196 // the thread might still not run when we call Pause() which will result
3198 wxThread::Sleep(300);
3200 for ( size_t n
= 0; n
< 3; n
++ )
3204 puts("\nThread suspended");
3207 // don't sleep but resume immediately the first time
3208 wxThread::Sleep(300);
3210 puts("Going to resume the thread");
3215 puts("Waiting until it terminates now");
3217 // wait until the thread terminates
3223 void TestThreadDelete()
3225 // As above, using Sleep() is only for testing here - we must use some
3226 // synchronisation object instead to ensure that the thread is still
3227 // running when we delete it - deleting a detached thread which already
3228 // terminated will lead to a crash!
3230 puts("\n*** Testing thread delete function ***");
3232 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3236 puts("\nDeleted a thread which didn't start to run yet.");
3238 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3242 wxThread::Sleep(300);
3246 puts("\nDeleted a running thread.");
3248 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3252 wxThread::Sleep(300);
3258 puts("\nDeleted a sleeping thread.");
3260 MyJoinableThread
thread3(20);
3265 puts("\nDeleted a joinable thread.");
3267 MyJoinableThread
thread4(2);
3270 wxThread::Sleep(300);
3274 puts("\nDeleted a joinable thread which already terminated.");
3279 #endif // TEST_THREADS
3281 // ----------------------------------------------------------------------------
3283 // ----------------------------------------------------------------------------
3287 static void PrintArray(const char* name
, const wxArrayString
& array
)
3289 printf("Dump of the array '%s'\n", name
);
3291 size_t nCount
= array
.GetCount();
3292 for ( size_t n
= 0; n
< nCount
; n
++ )
3294 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3298 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3300 printf("Dump of the array '%s'\n", name
);
3302 size_t nCount
= array
.GetCount();
3303 for ( size_t n
= 0; n
< nCount
; n
++ )
3305 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3309 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3310 const wxString
& second
)
3312 return first
.length() - second
.length();
3315 int wxCMPFUNC_CONV
IntCompare(int *first
,
3318 return *first
- *second
;
3321 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3324 return *second
- *first
;
3327 static void TestArrayOfInts()
3329 puts("*** Testing wxArrayInt ***\n");
3340 puts("After sort:");
3344 puts("After reverse sort:");
3345 a
.Sort(IntRevCompare
);
3349 #include "wx/dynarray.h"
3351 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3352 #include "wx/arrimpl.cpp"
3353 WX_DEFINE_OBJARRAY(ArrayBars
);
3355 static void TestArrayOfObjects()
3357 puts("*** Testing wxObjArray ***\n");
3361 Bar
bar("second bar");
3363 printf("Initially: %u objects in the array, %u objects total.\n",
3364 bars
.GetCount(), Bar::GetNumber());
3366 bars
.Add(new Bar("first bar"));
3369 printf("Now: %u objects in the array, %u objects total.\n",
3370 bars
.GetCount(), Bar::GetNumber());
3374 printf("After Empty(): %u objects in the array, %u objects total.\n",
3375 bars
.GetCount(), Bar::GetNumber());
3378 printf("Finally: no more objects in the array, %u objects total.\n",
3382 #endif // TEST_ARRAYS
3384 // ----------------------------------------------------------------------------
3386 // ----------------------------------------------------------------------------
3390 #include "wx/timer.h"
3391 #include "wx/tokenzr.h"
3393 static void TestStringConstruction()
3395 puts("*** Testing wxString constructores ***");
3397 #define TEST_CTOR(args, res) \
3400 printf("wxString%s = %s ", #args, s.c_str()); \
3407 printf("(ERROR: should be %s)\n", res); \
3411 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3412 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3413 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3414 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3416 static const wxChar
*s
= _T("?really!");
3417 const wxChar
*start
= wxStrchr(s
, _T('r'));
3418 const wxChar
*end
= wxStrchr(s
, _T('!'));
3419 TEST_CTOR((start
, end
), _T("really"));
3424 static void TestString()
3434 for (int i
= 0; i
< 1000000; ++i
)
3438 c
= "! How'ya doin'?";
3441 c
= "Hello world! What's up?";
3446 printf ("TestString elapsed time: %ld\n", sw
.Time());
3449 static void TestPChar()
3457 for (int i
= 0; i
< 1000000; ++i
)
3459 strcpy (a
, "Hello");
3460 strcpy (b
, " world");
3461 strcpy (c
, "! How'ya doin'?");
3464 strcpy (c
, "Hello world! What's up?");
3465 if (strcmp (c
, a
) == 0)
3469 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3472 static void TestStringSub()
3474 wxString
s("Hello, world!");
3476 puts("*** Testing wxString substring extraction ***");
3478 printf("String = '%s'\n", s
.c_str());
3479 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3480 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3481 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3482 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3483 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3484 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3486 static const wxChar
*prefixes
[] =
3490 _T("Hello, world!"),
3491 _T("Hello, world!!!"),
3497 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3499 wxString prefix
= prefixes
[n
], rest
;
3500 bool rc
= s
.StartsWith(prefix
, &rest
);
3501 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3504 printf(" (the rest is '%s')\n", rest
.c_str());
3515 static void TestStringFormat()
3517 puts("*** Testing wxString formatting ***");
3520 s
.Printf("%03d", 18);
3522 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3523 printf("Number 18: %s\n", s
.c_str());
3528 // returns "not found" for npos, value for all others
3529 static wxString
PosToString(size_t res
)
3531 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3532 : wxString::Format(_T("%u"), res
);
3536 static void TestStringFind()
3538 puts("*** Testing wxString find() functions ***");
3540 static const wxChar
*strToFind
= _T("ell");
3541 static const struct StringFindTest
3545 result
; // of searching "ell" in str
3548 { _T("Well, hello world"), 0, 1 },
3549 { _T("Well, hello world"), 6, 7 },
3550 { _T("Well, hello world"), 9, wxString::npos
},
3553 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3555 const StringFindTest
& ft
= findTestData
[n
];
3556 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3558 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3559 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3561 size_t resTrue
= ft
.result
;
3562 if ( res
== resTrue
)
3568 printf(_T("(ERROR: should be %s)\n"),
3569 PosToString(resTrue
).c_str());
3576 static void TestStringTokenizer()
3578 puts("*** Testing wxStringTokenizer ***");
3580 static const wxChar
*modeNames
[] =
3584 _T("return all empty"),
3589 static const struct StringTokenizerTest
3591 const wxChar
*str
; // string to tokenize
3592 const wxChar
*delims
; // delimiters to use
3593 size_t count
; // count of token
3594 wxStringTokenizerMode mode
; // how should we tokenize it
3595 } tokenizerTestData
[] =
3597 { _T(""), _T(" "), 0 },
3598 { _T("Hello, world"), _T(" "), 2 },
3599 { _T("Hello, world "), _T(" "), 2 },
3600 { _T("Hello, world"), _T(","), 2 },
3601 { _T("Hello, world!"), _T(",!"), 2 },
3602 { _T("Hello,, world!"), _T(",!"), 3 },
3603 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3604 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3605 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3606 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3607 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3608 { _T("01/02/99"), _T("/-"), 3 },
3609 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3612 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3614 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3615 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3617 size_t count
= tkz
.CountTokens();
3618 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3619 MakePrintable(tt
.str
).c_str(),
3621 MakePrintable(tt
.delims
).c_str(),
3622 modeNames
[tkz
.GetMode()]);
3623 if ( count
== tt
.count
)
3629 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3634 // if we emulate strtok(), check that we do it correctly
3635 wxChar
*buf
, *s
= NULL
, *last
;
3637 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3639 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3640 wxStrcpy(buf
, tt
.str
);
3642 s
= wxStrtok(buf
, tt
.delims
, &last
);
3649 // now show the tokens themselves
3651 while ( tkz
.HasMoreTokens() )
3653 wxString token
= tkz
.GetNextToken();
3655 printf(_T("\ttoken %u: '%s'"),
3657 MakePrintable(token
).c_str());
3667 printf(" (ERROR: should be %s)\n", s
);
3670 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3674 // nothing to compare with
3679 if ( count2
!= count
)
3681 puts(_T("\tERROR: token count mismatch"));
3690 static void TestStringReplace()
3692 puts("*** Testing wxString::replace ***");
3694 static const struct StringReplaceTestData
3696 const wxChar
*original
; // original test string
3697 size_t start
, len
; // the part to replace
3698 const wxChar
*replacement
; // the replacement string
3699 const wxChar
*result
; // and the expected result
3700 } stringReplaceTestData
[] =
3702 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3703 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3704 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3705 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3706 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3709 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3711 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3713 wxString original
= data
.original
;
3714 original
.replace(data
.start
, data
.len
, data
.replacement
);
3716 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3717 data
.original
, data
.start
, data
.len
, data
.replacement
,
3720 if ( original
== data
.result
)
3726 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3733 #endif // TEST_STRINGS
3735 // ----------------------------------------------------------------------------
3737 // ----------------------------------------------------------------------------
3739 int main(int argc
, char **argv
)
3741 if ( !wxInitialize() )
3743 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3747 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3749 #endif // TEST_USLEEP
3752 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3754 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3755 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3757 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3758 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3759 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3760 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3762 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
3763 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
3768 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
3770 parser
.AddOption("project_name", "", "full path to project file",
3771 wxCMD_LINE_VAL_STRING
,
3772 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
3774 switch ( parser
.Parse() )
3777 wxLogMessage("Help was given, terminating.");
3781 ShowCmdLine(parser
);
3785 wxLogMessage("Syntax error detected, aborting.");
3788 #endif // TEST_CMDLINE
3799 TestStringConstruction();
3802 TestStringTokenizer();
3803 TestStringReplace();
3805 #endif // TEST_STRINGS
3818 puts("*** Initially:");
3820 PrintArray("a1", a1
);
3822 wxArrayString
a2(a1
);
3823 PrintArray("a2", a2
);
3825 wxSortedArrayString
a3(a1
);
3826 PrintArray("a3", a3
);
3828 puts("*** After deleting a string from a1");
3831 PrintArray("a1", a1
);
3832 PrintArray("a2", a2
);
3833 PrintArray("a3", a3
);
3835 puts("*** After reassigning a1 to a2 and a3");
3837 PrintArray("a2", a2
);
3838 PrintArray("a3", a3
);
3840 puts("*** After sorting a1");
3842 PrintArray("a1", a1
);
3844 puts("*** After sorting a1 in reverse order");
3846 PrintArray("a1", a1
);
3848 puts("*** After sorting a1 by the string length");
3849 a1
.Sort(StringLenCompare
);
3850 PrintArray("a1", a1
);
3852 TestArrayOfObjects();
3855 #endif // TEST_ARRAYS
3861 #ifdef TEST_DLLLOADER
3863 #endif // TEST_DLLLOADER
3867 #endif // TEST_ENVIRON
3871 #endif // TEST_EXECUTE
3873 #ifdef TEST_FILECONF
3875 #endif // TEST_FILECONF
3883 for ( size_t n
= 0; n
< 8000; n
++ )
3885 s
<< (char)('A' + (n
% 26));
3889 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
3891 // this one shouldn't be truncated
3894 // but this one will because log functions use fixed size buffer
3895 // (note that it doesn't need '\n' at the end neither - will be added
3897 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
3910 int nCPUs
= wxThread::GetCPUCount();
3911 printf("This system has %d CPUs\n", nCPUs
);
3913 wxThread::SetConcurrency(nCPUs
);
3915 if ( argc
> 1 && argv
[1][0] == 't' )
3916 wxLog::AddTraceMask("thread");
3919 TestDetachedThreads();
3921 TestJoinableThreads();
3923 TestThreadSuspend();
3927 #endif // TEST_THREADS
3929 #ifdef TEST_LONGLONG
3930 // seed pseudo random generator
3931 srand((unsigned)time(NULL
));
3939 TestMultiplication();
3942 TestLongLongConversion();
3943 TestBitOperations();
3945 TestLongLongComparison();
3946 #endif // TEST_LONGLONG
3953 wxLog::AddTraceMask(_T("mime"));
3960 TestMimeAssociate();
3963 #ifdef TEST_INFO_FUNCTIONS
3966 #endif // TEST_INFO_FUNCTIONS
3968 #ifdef TEST_REGISTRY
3971 TestRegistryAssociation();
3972 #endif // TEST_REGISTRY
3980 #endif // TEST_SOCKETS
3983 wxLog::AddTraceMask(_T("ftp"));
3986 TestProtocolFtpUpload();
3991 #endif // TEST_STREAMS
3995 #endif // TEST_TIMER
3997 #ifdef TEST_DATETIME
4010 TestTimeArithmetics();
4019 #endif // TEST_DATETIME
4025 #endif // TEST_VCARD
4029 #endif // TEST_WCHAR
4032 TestZipStreamRead();
4037 TestZlibStreamWrite();
4038 TestZlibStreamRead();