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
52 //#define TEST_LONGLONG
54 //#define TEST_INFO_FUNCTIONS
55 //#define TEST_REGISTRY
56 //#define TEST_SOCKETS
57 //#define TEST_STREAMS
58 //#define TEST_STRINGS
59 //#define TEST_THREADS
61 //#define TEST_VCARD -- don't enable this (VZ)
66 // ----------------------------------------------------------------------------
67 // test class for container objects
68 // ----------------------------------------------------------------------------
70 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
72 class Bar
// Foo is already taken in the hash test
75 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
78 static size_t GetNumber() { return ms_bars
; }
80 const char *GetName() const { return m_name
; }
85 static size_t ms_bars
;
88 size_t Bar::ms_bars
= 0;
90 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
92 // ============================================================================
94 // ============================================================================
96 // ----------------------------------------------------------------------------
98 // ----------------------------------------------------------------------------
100 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
102 // replace TABs with \t and CRs with \n
103 static wxString
MakePrintable(const wxChar
*s
)
106 (void)str
.Replace(_T("\t"), _T("\\t"));
107 (void)str
.Replace(_T("\n"), _T("\\n"));
108 (void)str
.Replace(_T("\r"), _T("\\r"));
113 #endif // MakePrintable() is used
115 // ----------------------------------------------------------------------------
117 // ----------------------------------------------------------------------------
121 #include <wx/cmdline.h>
122 #include <wx/datetime.h>
124 static void ShowCmdLine(const wxCmdLineParser
& parser
)
126 wxString s
= "Input files: ";
128 size_t count
= parser
.GetParamCount();
129 for ( size_t param
= 0; param
< count
; param
++ )
131 s
<< parser
.GetParam(param
) << ' ';
135 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
136 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
141 if ( parser
.Found("o", &strVal
) )
142 s
<< "Output file:\t" << strVal
<< '\n';
143 if ( parser
.Found("i", &strVal
) )
144 s
<< "Input dir:\t" << strVal
<< '\n';
145 if ( parser
.Found("s", &lVal
) )
146 s
<< "Size:\t" << lVal
<< '\n';
147 if ( parser
.Found("d", &dt
) )
148 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
149 if ( parser
.Found("project_name", &strVal
) )
150 s
<< "Project:\t" << strVal
<< '\n';
155 #endif // TEST_CMDLINE
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
165 static void TestDirEnumHelper(wxDir
& dir
,
166 int flags
= wxDIR_DEFAULT
,
167 const wxString
& filespec
= wxEmptyString
)
171 if ( !dir
.IsOpened() )
174 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
177 printf("\t%s\n", filename
.c_str());
179 cont
= dir
.GetNext(&filename
);
185 static void TestDirEnum()
187 wxDir
dir(wxGetCwd());
189 puts("Enumerating everything in current directory:");
190 TestDirEnumHelper(dir
);
192 puts("Enumerating really everything in current directory:");
193 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
195 puts("Enumerating object files in current directory:");
196 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
198 puts("Enumerating directories in current directory:");
199 TestDirEnumHelper(dir
, wxDIR_DIRS
);
201 puts("Enumerating files in current directory:");
202 TestDirEnumHelper(dir
, wxDIR_FILES
);
204 puts("Enumerating files including hidden in current directory:");
205 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
209 #elif defined(__WXMSW__)
212 #error "don't know where the root directory is"
215 puts("Enumerating everything in root directory:");
216 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
218 puts("Enumerating directories in root directory:");
219 TestDirEnumHelper(dir
, wxDIR_DIRS
);
221 puts("Enumerating files in root directory:");
222 TestDirEnumHelper(dir
, wxDIR_FILES
);
224 puts("Enumerating files including hidden in root directory:");
225 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
227 puts("Enumerating files in non existing directory:");
228 wxDir
dirNo("nosuchdir");
229 TestDirEnumHelper(dirNo
);
234 // ----------------------------------------------------------------------------
236 // ----------------------------------------------------------------------------
238 #ifdef TEST_DLLLOADER
240 #include <wx/dynlib.h>
242 static void TestDllLoad()
244 #if defined(__WXMSW__)
245 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
246 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
247 #elif defined(__UNIX__)
248 // weird: using just libc.so does *not* work!
249 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
250 static const wxChar
*FUNC_NAME
= _T("strlen");
252 #error "don't know how to test wxDllLoader on this platform"
255 puts("*** testing wxDllLoader ***\n");
257 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
260 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
264 typedef int (*strlenType
)(char *);
265 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
268 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
269 FUNC_NAME
, LIB_NAME
);
273 if ( pfnStrlen("foo") != 3 )
275 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
283 wxDllLoader::UnloadLibrary(dllHandle
);
287 #endif // TEST_DLLLOADER
289 // ----------------------------------------------------------------------------
291 // ----------------------------------------------------------------------------
295 #include <wx/utils.h>
297 static wxString
MyGetEnv(const wxString
& var
)
300 if ( !wxGetEnv(var
, &val
) )
303 val
= wxString(_T('\'')) + val
+ _T('\'');
308 static void TestEnvironment()
310 const wxChar
*var
= _T("wxTestVar");
312 puts("*** testing environment access functions ***");
314 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
315 wxSetEnv(var
, _T("value for wxTestVar"));
316 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
317 wxSetEnv(var
, _T("another value"));
318 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
320 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
321 printf("PATH = %s\n", MyGetEnv(_T("PATH")));
324 #endif // TEST_ENVIRON
326 // ----------------------------------------------------------------------------
328 // ----------------------------------------------------------------------------
332 #include <wx/utils.h>
334 static void TestExecute()
336 puts("*** testing wxExecute ***");
339 #define COMMAND "cat -n ../../Makefile" // "echo hi"
340 #define SHELL_COMMAND "echo hi from shell"
341 #define REDIRECT_COMMAND COMMAND // "date"
342 #elif defined(__WXMSW__)
343 #define COMMAND "command.com -c 'echo hi'"
344 #define SHELL_COMMAND "echo hi"
345 #define REDIRECT_COMMAND COMMAND
347 #error "no command to exec"
350 printf("Testing wxShell: ");
352 if ( wxShell(SHELL_COMMAND
) )
357 printf("Testing wxExecute: ");
359 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
364 #if 0 // no, it doesn't work (yet?)
365 printf("Testing async wxExecute: ");
367 if ( wxExecute(COMMAND
) != 0 )
368 puts("Ok (command launched).");
373 printf("Testing wxExecute with redirection:\n");
374 wxArrayString output
;
375 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
381 size_t count
= output
.GetCount();
382 for ( size_t n
= 0; n
< count
; n
++ )
384 printf("\t%s\n", output
[n
].c_str());
391 #endif // TEST_EXECUTE
393 // ----------------------------------------------------------------------------
395 // ----------------------------------------------------------------------------
400 #include <wx/ffile.h>
401 #include <wx/textfile.h>
403 static void TestFileRead()
405 puts("*** wxFile read test ***");
407 wxFile
file(_T("testdata.fc"));
408 if ( file
.IsOpened() )
410 printf("File length: %lu\n", file
.Length());
412 puts("File dump:\n----------");
414 static const off_t len
= 1024;
418 off_t nRead
= file
.Read(buf
, len
);
419 if ( nRead
== wxInvalidOffset
)
421 printf("Failed to read the file.");
425 fwrite(buf
, nRead
, 1, stdout
);
435 printf("ERROR: can't open test file.\n");
441 static void TestTextFileRead()
443 puts("*** wxTextFile read test ***");
445 wxTextFile
file(_T("testdata.fc"));
448 printf("Number of lines: %u\n", file
.GetLineCount());
449 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
453 puts("\nDumping the entire file:");
454 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
456 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
458 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
460 puts("\nAnd now backwards:");
461 for ( s
= file
.GetLastLine();
462 file
.GetCurrentLine() != 0;
463 s
= file
.GetPrevLine() )
465 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
467 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
471 printf("ERROR: can't open '%s'\n", file
.GetName());
477 static void TestFileCopy()
479 puts("*** Testing wxCopyFile ***");
481 static const wxChar
*filename1
= _T("testdata.fc");
482 static const wxChar
*filename2
= _T("test2");
483 if ( !wxCopyFile(filename1
, filename2
) )
485 puts("ERROR: failed to copy file");
489 wxFFile
f1(filename1
, "rb"),
492 if ( !f1
.IsOpened() || !f2
.IsOpened() )
494 puts("ERROR: failed to open file(s)");
499 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
501 puts("ERROR: failed to read file(s)");
505 if ( (s1
.length() != s2
.length()) ||
506 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
508 puts("ERROR: copy error!");
512 puts("File was copied ok.");
518 if ( !wxRemoveFile(filename2
) )
520 puts("ERROR: failed to remove the file");
528 // ----------------------------------------------------------------------------
530 // ----------------------------------------------------------------------------
534 #include <wx/confbase.h>
535 #include <wx/fileconf.h>
537 static const struct FileConfTestData
539 const wxChar
*name
; // value name
540 const wxChar
*value
; // the value from the file
543 { _T("value1"), _T("one") },
544 { _T("value2"), _T("two") },
545 { _T("novalue"), _T("default") },
548 static void TestFileConfRead()
550 puts("*** testing wxFileConfig loading/reading ***");
552 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
553 _T("testdata.fc"), wxEmptyString
,
554 wxCONFIG_USE_RELATIVE_PATH
);
556 // test simple reading
557 puts("\nReading config file:");
558 wxString
defValue(_T("default")), value
;
559 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
561 const FileConfTestData
& data
= fcTestData
[n
];
562 value
= fileconf
.Read(data
.name
, defValue
);
563 printf("\t%s = %s ", data
.name
, value
.c_str());
564 if ( value
== data
.value
)
570 printf("(ERROR: should be %s)\n", data
.value
);
574 // test enumerating the entries
575 puts("\nEnumerating all root entries:");
578 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
581 printf("\t%s = %s\n",
583 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
585 cont
= fileconf
.GetNextEntry(name
, dummy
);
589 #endif // TEST_FILECONF
591 // ----------------------------------------------------------------------------
593 // ----------------------------------------------------------------------------
597 #include <wx/filename.h>
599 static const wxChar
*filenames
[] =
606 _T("/tmp/wxwin.tar.bz"),
609 static void TestFileNameConstruction()
611 puts("*** testing wxFileName construction ***");
613 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
615 wxFileName
fn(filenames
[n
], wxPATH_UNIX
);
617 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
618 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
620 puts("ERROR (couldn't be normalized)");
624 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
631 static void TestFileNameSplit()
633 puts("*** testing wxFileName splitting ***");
635 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
637 wxString path
, name
, ext
;
638 wxFileName::SplitPath(filenames
[n
], &path
, &name
, &ext
);
639 printf("%s -> path = '%s', name = '%s', ext = '%s'\n",
640 filenames
[n
], path
.c_str(), name
.c_str(), ext
.c_str());
646 static void TestFileNameComparison()
651 static void TestFileNameOperations()
656 static void TestFileNameCwd()
661 #endif // TEST_FILENAME
663 // ----------------------------------------------------------------------------
665 // ----------------------------------------------------------------------------
673 Foo(int n_
) { n
= n_
; count
++; }
681 size_t Foo::count
= 0;
683 WX_DECLARE_LIST(Foo
, wxListFoos
);
684 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
686 #include <wx/listimpl.cpp>
688 WX_DEFINE_LIST(wxListFoos
);
690 static void TestHash()
692 puts("*** Testing wxHashTable ***\n");
696 hash
.DeleteContents(TRUE
);
698 printf("Hash created: %u foos in hash, %u foos totally\n",
699 hash
.GetCount(), Foo::count
);
701 static const int hashTestData
[] =
703 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
707 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
709 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
712 printf("Hash filled: %u foos in hash, %u foos totally\n",
713 hash
.GetCount(), Foo::count
);
715 puts("Hash access test:");
716 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
718 printf("\tGetting element with key %d, value %d: ",
720 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
723 printf("ERROR, not found.\n");
727 printf("%d (%s)\n", foo
->n
,
728 (size_t)foo
->n
== n
? "ok" : "ERROR");
732 printf("\nTrying to get an element not in hash: ");
734 if ( hash
.Get(1234) || hash
.Get(1, 0) )
736 puts("ERROR: found!");
740 puts("ok (not found)");
744 printf("Hash destroyed: %u foos left\n", Foo::count
);
749 // ----------------------------------------------------------------------------
751 // ----------------------------------------------------------------------------
757 WX_DECLARE_LIST(Bar
, wxListBars
);
758 #include <wx/listimpl.cpp>
759 WX_DEFINE_LIST(wxListBars
);
761 static void TestListCtor()
763 puts("*** Testing wxList construction ***\n");
767 list1
.Append(new Bar(_T("first")));
768 list1
.Append(new Bar(_T("second")));
770 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
771 list1
.GetCount(), Bar::GetNumber());
776 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
777 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
779 list1
.DeleteContents(TRUE
);
782 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
787 // ----------------------------------------------------------------------------
789 // ----------------------------------------------------------------------------
793 #include <wx/mimetype.h>
795 static wxMimeTypesManager g_mimeManager
;
797 static void TestMimeEnum()
799 wxArrayString mimetypes
;
801 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
803 printf("*** All %u known filetypes: ***\n", count
);
808 for ( size_t n
= 0; n
< count
; n
++ )
810 wxFileType
*filetype
= g_mimeManager
.GetFileTypeFromMimeType(mimetypes
[n
]);
813 printf("nothing known about the filetype '%s'!\n",
814 mimetypes
[n
].c_str());
818 filetype
->GetDescription(&desc
);
819 filetype
->GetExtensions(exts
);
821 filetype
->GetIcon(NULL
);
824 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
831 printf("\t%s: %s (%s)\n",
832 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
836 static void TestMimeOverride()
838 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
840 wxString mailcap
= _T("/tmp/mailcap"),
841 mimetypes
= _T("/tmp/mime.types");
843 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
845 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
846 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
848 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
851 static void TestMimeFilename()
853 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
855 static const wxChar
*filenames
[] =
862 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
864 const wxString fname
= filenames
[n
];
865 wxString ext
= fname
.AfterLast(_T('.'));
866 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
869 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
874 if ( !ft
->GetDescription(&desc
) )
875 desc
= _T("<no description>");
878 if ( !ft
->GetOpenCommand(&cmd
,
879 wxFileType::MessageParameters(fname
, _T(""))) )
880 cmd
= _T("<no command available>");
882 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
883 fname
.c_str(), desc
.c_str(), cmd
.c_str());
890 static void TestMimeAssociate()
892 wxPuts(_T("*** Testing creation of filetype association ***\n"));
894 wxFileType
*ft
= g_mimeManager
.Associate
897 _T("application/x-xyz"),
898 _T("XYZFile"), // filetype (MSW only)
899 _T("XYZ File") // description (Unix only)
903 wxPuts(_T("ERROR: failed to create association!"));
907 if ( !ft
->SetOpenCommand(_T("myprogram")) )
909 wxPuts(_T("ERROR: failed to set open command!"));
918 // ----------------------------------------------------------------------------
919 // misc information functions
920 // ----------------------------------------------------------------------------
922 #ifdef TEST_INFO_FUNCTIONS
924 #include <wx/utils.h>
926 static void TestOsInfo()
928 puts("*** Testing OS info functions ***\n");
931 wxGetOsVersion(&major
, &minor
);
932 printf("Running under: %s, version %d.%d\n",
933 wxGetOsDescription().c_str(), major
, minor
);
935 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
937 printf("Host name is %s (%s).\n",
938 wxGetHostName().c_str(), wxGetFullHostName().c_str());
943 static void TestUserInfo()
945 puts("*** Testing user info functions ***\n");
947 printf("User id is:\t%s\n", wxGetUserId().c_str());
948 printf("User name is:\t%s\n", wxGetUserName().c_str());
949 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
950 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
955 #endif // TEST_INFO_FUNCTIONS
957 // ----------------------------------------------------------------------------
959 // ----------------------------------------------------------------------------
963 #include <wx/longlong.h>
964 #include <wx/timer.h>
966 // make a 64 bit number from 4 16 bit ones
967 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
969 // get a random 64 bit number
970 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
972 #if wxUSE_LONGLONG_WX
973 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
974 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
975 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
976 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
977 #endif // wxUSE_LONGLONG_WX
979 static void TestSpeed()
981 static const long max
= 100000000;
988 for ( n
= 0; n
< max
; n
++ )
993 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
996 #if wxUSE_LONGLONG_NATIVE
1001 for ( n
= 0; n
< max
; n
++ )
1006 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1008 #endif // wxUSE_LONGLONG_NATIVE
1014 for ( n
= 0; n
< max
; n
++ )
1019 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1023 static void TestLongLongConversion()
1025 puts("*** Testing wxLongLong conversions ***\n");
1029 for ( size_t n
= 0; n
< 100000; n
++ )
1033 #if wxUSE_LONGLONG_NATIVE
1034 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1036 wxASSERT_MSG( a
== b
, "conversions failure" );
1038 puts("Can't do it without native long long type, test skipped.");
1041 #endif // wxUSE_LONGLONG_NATIVE
1043 if ( !(nTested
% 1000) )
1055 static void TestMultiplication()
1057 puts("*** Testing wxLongLong multiplication ***\n");
1061 for ( size_t n
= 0; n
< 100000; n
++ )
1066 #if wxUSE_LONGLONG_NATIVE
1067 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1068 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1070 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1071 #else // !wxUSE_LONGLONG_NATIVE
1072 puts("Can't do it without native long long type, test skipped.");
1075 #endif // wxUSE_LONGLONG_NATIVE
1077 if ( !(nTested
% 1000) )
1089 static void TestDivision()
1091 puts("*** Testing wxLongLong division ***\n");
1095 for ( size_t n
= 0; n
< 100000; n
++ )
1097 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1098 // multiplication will not overflow)
1099 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1101 // get a random long (not wxLongLong for now) to divide it with
1106 #if wxUSE_LONGLONG_NATIVE
1107 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1109 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1110 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1111 #else // !wxUSE_LONGLONG_NATIVE
1112 // verify the result
1113 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1114 #endif // wxUSE_LONGLONG_NATIVE
1116 if ( !(nTested
% 1000) )
1128 static void TestAddition()
1130 puts("*** Testing wxLongLong addition ***\n");
1134 for ( size_t n
= 0; n
< 100000; n
++ )
1140 #if wxUSE_LONGLONG_NATIVE
1141 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1142 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1143 "addition failure" );
1144 #else // !wxUSE_LONGLONG_NATIVE
1145 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1146 #endif // wxUSE_LONGLONG_NATIVE
1148 if ( !(nTested
% 1000) )
1160 static void TestBitOperations()
1162 puts("*** Testing wxLongLong bit operation ***\n");
1166 for ( size_t n
= 0; n
< 100000; n
++ )
1170 #if wxUSE_LONGLONG_NATIVE
1171 for ( size_t n
= 0; n
< 33; n
++ )
1174 #else // !wxUSE_LONGLONG_NATIVE
1175 puts("Can't do it without native long long type, test skipped.");
1178 #endif // wxUSE_LONGLONG_NATIVE
1180 if ( !(nTested
% 1000) )
1192 static void TestLongLongComparison()
1194 puts("*** Testing wxLongLong comparison ***\n");
1196 static const long testLongs
[] =
1207 static const long ls
[2] =
1213 wxLongLongWx lls
[2];
1217 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1221 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1223 res
= lls
[m
] > testLongs
[n
];
1224 printf("0x%lx > 0x%lx is %s (%s)\n",
1225 ls
[m
], testLongs
[n
], res
? "true" : "false",
1226 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1228 res
= lls
[m
] < testLongs
[n
];
1229 printf("0x%lx < 0x%lx is %s (%s)\n",
1230 ls
[m
], testLongs
[n
], res
? "true" : "false",
1231 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1233 res
= lls
[m
] == testLongs
[n
];
1234 printf("0x%lx == 0x%lx is %s (%s)\n",
1235 ls
[m
], testLongs
[n
], res
? "true" : "false",
1236 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1244 #endif // TEST_LONGLONG
1246 // ----------------------------------------------------------------------------
1248 // ----------------------------------------------------------------------------
1250 // this is for MSW only
1252 #undef TEST_REGISTRY
1255 #ifdef TEST_REGISTRY
1257 #include <wx/msw/registry.h>
1259 // I chose this one because I liked its name, but it probably only exists under
1261 static const wxChar
*TESTKEY
=
1262 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1264 static void TestRegistryRead()
1266 puts("*** testing registry reading ***");
1268 wxRegKey
key(TESTKEY
);
1269 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1272 puts("ERROR: test key can't be opened, aborting test.");
1277 size_t nSubKeys
, nValues
;
1278 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1280 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1283 printf("Enumerating values:\n");
1287 bool cont
= key
.GetFirstValue(value
, dummy
);
1290 printf("Value '%s': type ", value
.c_str());
1291 switch ( key
.GetValueType(value
) )
1293 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1294 case wxRegKey::Type_String
: printf("SZ"); break;
1295 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1296 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1297 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1298 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1299 default: printf("other (unknown)"); break;
1302 printf(", value = ");
1303 if ( key
.IsNumericValue(value
) )
1306 key
.QueryValue(value
, &val
);
1312 key
.QueryValue(value
, val
);
1313 printf("'%s'", val
.c_str());
1315 key
.QueryRawValue(value
, val
);
1316 printf(" (raw value '%s')", val
.c_str());
1321 cont
= key
.GetNextValue(value
, dummy
);
1325 static void TestRegistryAssociation()
1328 The second call to deleteself genertaes an error message, with a
1329 messagebox saying .flo is crucial to system operation, while the .ddf
1330 call also fails, but with no error message
1335 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1337 key
= "ddxf_auto_file" ;
1338 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1340 key
= "ddxf_auto_file" ;
1341 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1344 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1346 key
= "program \"%1\"" ;
1348 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1350 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1352 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1354 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1358 #endif // TEST_REGISTRY
1360 // ----------------------------------------------------------------------------
1362 // ----------------------------------------------------------------------------
1366 #include <wx/socket.h>
1367 #include <wx/protocol/protocol.h>
1368 #include <wx/protocol/http.h>
1370 static void TestSocketServer()
1372 puts("*** Testing wxSocketServer ***\n");
1374 static const int PORT
= 3000;
1379 wxSocketServer
*server
= new wxSocketServer(addr
);
1380 if ( !server
->Ok() )
1382 puts("ERROR: failed to bind");
1389 printf("Server: waiting for connection on port %d...\n", PORT
);
1391 wxSocketBase
*socket
= server
->Accept();
1394 puts("ERROR: wxSocketServer::Accept() failed.");
1398 puts("Server: got a client.");
1400 server
->SetTimeout(60); // 1 min
1402 while ( socket
->IsConnected() )
1408 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1410 // don't log error if the client just close the connection
1411 if ( socket
->IsConnected() )
1413 puts("ERROR: in wxSocket::Read.");
1433 printf("Server: got '%s'.\n", s
.c_str());
1434 if ( s
== _T("bye") )
1441 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1442 socket
->Write("\r\n", 2);
1443 printf("Server: wrote '%s'.\n", s
.c_str());
1446 puts("Server: lost a client.");
1451 // same as "delete server" but is consistent with GUI programs
1455 static void TestSocketClient()
1457 puts("*** Testing wxSocketClient ***\n");
1459 static const char *hostname
= "www.wxwindows.org";
1462 addr
.Hostname(hostname
);
1465 printf("--- Attempting to connect to %s:80...\n", hostname
);
1467 wxSocketClient client
;
1468 if ( !client
.Connect(addr
) )
1470 printf("ERROR: failed to connect to %s\n", hostname
);
1474 printf("--- Connected to %s:%u...\n",
1475 addr
.Hostname().c_str(), addr
.Service());
1479 // could use simply "GET" here I suppose
1481 wxString::Format("GET http://%s/\r\n", hostname
);
1482 client
.Write(cmdGet
, cmdGet
.length());
1483 printf("--- Sent command '%s' to the server\n",
1484 MakePrintable(cmdGet
).c_str());
1485 client
.Read(buf
, WXSIZEOF(buf
));
1486 printf("--- Server replied:\n%s", buf
);
1490 #endif // TEST_SOCKETS
1494 #include <wx/protocol/ftp.h>
1496 static void TestProtocolFtp()
1498 puts("*** Testing wxFTP download ***\n");
1502 #ifdef TEST_WUFTPD // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1503 static const char *hostname
= "ftp.eudora.com";
1504 if ( !ftp
.Connect(hostname
) )
1506 printf("ERROR: failed to connect to %s\n", hostname
);
1510 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1511 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1514 printf("ERROR: couldn't get input stream for %s\n", filename
);
1518 size_t size
= in
->StreamSize();
1519 printf("Reading file %s (%u bytes)...", filename
, size
);
1521 char *data
= new char[size
];
1522 if ( !in
->Read(data
, size
) )
1524 puts("ERROR: read error");
1528 printf("Successfully retrieved the file.\n");
1535 #else // !TEST_WUFTPD
1538 static const char *hostname
= "ftp.wxwindows.org";
1539 static const char *directory
= "pub";
1540 static const char *filename
= "welcome.msg";
1542 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1544 static const char *hostname
= "localhost";
1545 static const char *user
= "zeitlin";
1546 static const char *directory
= "/tmp";
1549 ftp
.SetPassword("password");
1551 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1554 if ( !ftp
.Connect(hostname
) )
1556 printf("ERROR: failed to connect to %s\n", hostname
);
1560 printf("--- Connected to %s, current directory is '%s'\n",
1561 hostname
, ftp
.Pwd().c_str());
1564 if ( !ftp
.ChDir(directory
) )
1566 printf("ERROR: failed to cd to %s\n", directory
);
1569 // test NLIST and LIST
1570 wxArrayString files
;
1571 if ( !ftp
.GetFilesList(files
) )
1573 puts("ERROR: failed to get NLIST of files");
1577 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1578 size_t count
= files
.GetCount();
1579 for ( size_t n
= 0; n
< count
; n
++ )
1581 printf("\t%s\n", files
[n
].c_str());
1583 puts("End of the file list");
1586 if ( !ftp
.GetDirList(files
) )
1588 puts("ERROR: failed to get LIST of files");
1592 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1593 size_t count
= files
.GetCount();
1594 for ( size_t n
= 0; n
< count
; n
++ )
1596 printf("\t%s\n", files
[n
].c_str());
1598 puts("End of the file list");
1601 if ( !ftp
.ChDir(_T("..")) )
1603 puts("ERROR: failed to cd to ..");
1607 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1610 printf("ERROR: couldn't get input stream for %s\n", filename
);
1614 size_t size
= in
->StreamSize();
1615 printf("Reading file %s (%u bytes)...", filename
, size
);
1617 char *data
= new char[size
];
1618 if ( !in
->Read(data
, size
) )
1620 puts("ERROR: read error");
1624 printf("\nContents of %s:\n%s\n", filename
, data
);
1631 // test some other FTP commands
1632 if ( ftp
.SendCommand("STAT") != '2' )
1634 puts("ERROR: STAT failed");
1638 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1641 if ( ftp
.SendCommand("HELP SITE") != '2' )
1643 puts("ERROR: HELP SITE failed");
1647 printf("The list of site-specific commands:\n\n%s\n",
1648 ftp
.GetLastResult().c_str());
1651 #endif // TEST_WUFTPD/!TEST_WUFTPD
1654 static void TestProtocolFtpUpload()
1656 puts("*** Testing wxFTP uploading ***\n");
1658 static const char *hostname
= "localhost";
1660 printf("--- Attempting to connect to %s:21...\n", hostname
);
1663 ftp
.SetUser("zeitlin");
1664 ftp
.SetPassword("password");
1665 if ( !ftp
.Connect(hostname
) )
1667 printf("ERROR: failed to connect to %s\n", hostname
);
1671 printf("--- Connected to %s, current directory is '%s'\n",
1672 hostname
, ftp
.Pwd().c_str());
1675 static const char *file1
= "test1";
1676 static const char *file2
= "test2";
1677 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1680 printf("--- Uploading to %s ---\n", file1
);
1681 out
->Write("First hello", 11);
1685 // send a command to check the remote file
1686 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1688 printf("ERROR: STAT %s failed\n", file1
);
1692 printf("STAT %s returned:\n\n%s\n",
1693 file1
, ftp
.GetLastResult().c_str());
1696 out
= ftp
.GetOutputStream(file2
);
1699 printf("--- Uploading to %s ---\n", file1
);
1700 out
->Write("Second hello", 12);
1708 // ----------------------------------------------------------------------------
1710 // ----------------------------------------------------------------------------
1714 #include <wx/mstream.h>
1716 static void TestMemoryStream()
1718 puts("*** Testing wxMemoryInputStream ***");
1721 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1723 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1724 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1725 while ( !memInpStream
.Eof() )
1727 putchar(memInpStream
.GetC());
1730 puts("\n*** wxMemoryInputStream test done ***");
1733 #endif // TEST_STREAMS
1735 // ----------------------------------------------------------------------------
1737 // ----------------------------------------------------------------------------
1741 #include <wx/timer.h>
1742 #include <wx/utils.h>
1744 static void TestStopWatch()
1746 puts("*** Testing wxStopWatch ***\n");
1749 printf("Sleeping 3 seconds...");
1751 printf("\telapsed time: %ldms\n", sw
.Time());
1754 printf("Sleeping 2 more seconds...");
1756 printf("\telapsed time: %ldms\n", sw
.Time());
1759 printf("And 3 more seconds...");
1761 printf("\telapsed time: %ldms\n", sw
.Time());
1764 puts("\nChecking for 'backwards clock' bug...");
1765 for ( size_t n
= 0; n
< 70; n
++ )
1769 for ( size_t m
= 0; m
< 100000; m
++ )
1771 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1773 puts("\ntime is negative - ERROR!");
1783 #endif // TEST_TIMER
1785 // ----------------------------------------------------------------------------
1787 // ----------------------------------------------------------------------------
1791 #include <wx/vcard.h>
1793 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1796 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1800 wxString(_T('\t'), level
).c_str(),
1801 vcObj
->GetName().c_str());
1804 switch ( vcObj
->GetType() )
1806 case wxVCardObject::String
:
1807 case wxVCardObject::UString
:
1810 vcObj
->GetValue(&val
);
1811 value
<< _T('"') << val
<< _T('"');
1815 case wxVCardObject::Int
:
1818 vcObj
->GetValue(&i
);
1819 value
.Printf(_T("%u"), i
);
1823 case wxVCardObject::Long
:
1826 vcObj
->GetValue(&l
);
1827 value
.Printf(_T("%lu"), l
);
1831 case wxVCardObject::None
:
1834 case wxVCardObject::Object
:
1835 value
= _T("<node>");
1839 value
= _T("<unknown value type>");
1843 printf(" = %s", value
.c_str());
1846 DumpVObject(level
+ 1, *vcObj
);
1849 vcObj
= vcard
.GetNextProp(&cookie
);
1853 static void DumpVCardAddresses(const wxVCard
& vcard
)
1855 puts("\nShowing all addresses from vCard:\n");
1859 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1863 int flags
= addr
->GetFlags();
1864 if ( flags
& wxVCardAddress::Domestic
)
1866 flagsStr
<< _T("domestic ");
1868 if ( flags
& wxVCardAddress::Intl
)
1870 flagsStr
<< _T("international ");
1872 if ( flags
& wxVCardAddress::Postal
)
1874 flagsStr
<< _T("postal ");
1876 if ( flags
& wxVCardAddress::Parcel
)
1878 flagsStr
<< _T("parcel ");
1880 if ( flags
& wxVCardAddress::Home
)
1882 flagsStr
<< _T("home ");
1884 if ( flags
& wxVCardAddress::Work
)
1886 flagsStr
<< _T("work ");
1889 printf("Address %u:\n"
1891 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1894 addr
->GetPostOffice().c_str(),
1895 addr
->GetExtAddress().c_str(),
1896 addr
->GetStreet().c_str(),
1897 addr
->GetLocality().c_str(),
1898 addr
->GetRegion().c_str(),
1899 addr
->GetPostalCode().c_str(),
1900 addr
->GetCountry().c_str()
1904 addr
= vcard
.GetNextAddress(&cookie
);
1908 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
1910 puts("\nShowing all phone numbers from vCard:\n");
1914 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
1918 int flags
= phone
->GetFlags();
1919 if ( flags
& wxVCardPhoneNumber::Voice
)
1921 flagsStr
<< _T("voice ");
1923 if ( flags
& wxVCardPhoneNumber::Fax
)
1925 flagsStr
<< _T("fax ");
1927 if ( flags
& wxVCardPhoneNumber::Cellular
)
1929 flagsStr
<< _T("cellular ");
1931 if ( flags
& wxVCardPhoneNumber::Modem
)
1933 flagsStr
<< _T("modem ");
1935 if ( flags
& wxVCardPhoneNumber::Home
)
1937 flagsStr
<< _T("home ");
1939 if ( flags
& wxVCardPhoneNumber::Work
)
1941 flagsStr
<< _T("work ");
1944 printf("Phone number %u:\n"
1949 phone
->GetNumber().c_str()
1953 phone
= vcard
.GetNextPhoneNumber(&cookie
);
1957 static void TestVCardRead()
1959 puts("*** Testing wxVCard reading ***\n");
1961 wxVCard
vcard(_T("vcard.vcf"));
1962 if ( !vcard
.IsOk() )
1964 puts("ERROR: couldn't load vCard.");
1968 // read individual vCard properties
1969 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
1973 vcObj
->GetValue(&value
);
1978 value
= _T("<none>");
1981 printf("Full name retrieved directly: %s\n", value
.c_str());
1984 if ( !vcard
.GetFullName(&value
) )
1986 value
= _T("<none>");
1989 printf("Full name from wxVCard API: %s\n", value
.c_str());
1991 // now show how to deal with multiply occuring properties
1992 DumpVCardAddresses(vcard
);
1993 DumpVCardPhoneNumbers(vcard
);
1995 // and finally show all
1996 puts("\nNow dumping the entire vCard:\n"
1997 "-----------------------------\n");
1999 DumpVObject(0, vcard
);
2003 static void TestVCardWrite()
2005 puts("*** Testing wxVCard writing ***\n");
2008 if ( !vcard
.IsOk() )
2010 puts("ERROR: couldn't create vCard.");
2015 vcard
.SetName("Zeitlin", "Vadim");
2016 vcard
.SetFullName("Vadim Zeitlin");
2017 vcard
.SetOrganization("wxWindows", "R&D");
2019 // just dump the vCard back
2020 puts("Entire vCard follows:\n");
2021 puts(vcard
.Write());
2025 #endif // TEST_VCARD
2027 // ----------------------------------------------------------------------------
2028 // wide char (Unicode) support
2029 // ----------------------------------------------------------------------------
2033 #include <wx/strconv.h>
2034 #include <wx/buffer.h>
2036 static void TestUtf8()
2038 puts("*** Testing UTF8 support ***\n");
2040 wxString testString
= "français";
2042 "************ French - Français ****************"
2043 "Juste un petit exemple pour dire que les français aussi"
2044 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
2047 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
2048 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
2049 wxString
testString2(pwz
, wxConvLocal
);
2051 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
2053 char *psz
= "fran" "\xe7" "ais";
2054 size_t len
= strlen(psz
);
2055 wchar_t *pwz2
= new wchar_t[len
+ 1];
2056 for ( size_t n
= 0; n
<= len
; n
++ )
2058 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
2061 wxString
testString3(pwz2
, wxConvUTF8
);
2064 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
2067 #endif // TEST_WCHAR
2069 // ----------------------------------------------------------------------------
2071 // ----------------------------------------------------------------------------
2075 #include "wx/zipstrm.h"
2077 static void TestZipStreamRead()
2079 puts("*** Testing ZIP reading ***\n");
2081 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
2082 printf("Archive size: %u\n", istr
.GetSize());
2084 puts("Dumping the file:");
2085 while ( !istr
.Eof() )
2087 putchar(istr
.GetC());
2091 puts("\n----- done ------");
2096 // ----------------------------------------------------------------------------
2098 // ----------------------------------------------------------------------------
2102 #include <wx/zstream.h>
2103 #include <wx/wfstream.h>
2105 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2106 static const char *TEST_DATA
= "hello and hello again";
2108 static void TestZlibStreamWrite()
2110 puts("*** Testing Zlib stream reading ***\n");
2112 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2113 wxZlibOutputStream
ostr(fileOutStream
, 0);
2114 printf("Compressing the test string... ");
2115 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2118 puts("(ERROR: failed)");
2125 puts("\n----- done ------");
2128 static void TestZlibStreamRead()
2130 puts("*** Testing Zlib stream reading ***\n");
2132 wxFileInputStream
fileInStream(FILENAME_GZ
);
2133 wxZlibInputStream
istr(fileInStream
);
2134 printf("Archive size: %u\n", istr
.GetSize());
2136 puts("Dumping the file:");
2137 while ( !istr
.Eof() )
2139 putchar(istr
.GetC());
2143 puts("\n----- done ------");
2148 // ----------------------------------------------------------------------------
2150 // ----------------------------------------------------------------------------
2152 #ifdef TEST_DATETIME
2154 #include <wx/date.h>
2156 #include <wx/datetime.h>
2161 wxDateTime::wxDateTime_t day
;
2162 wxDateTime::Month month
;
2164 wxDateTime::wxDateTime_t hour
, min
, sec
;
2166 wxDateTime::WeekDay wday
;
2167 time_t gmticks
, ticks
;
2169 void Init(const wxDateTime::Tm
& tm
)
2178 gmticks
= ticks
= -1;
2181 wxDateTime
DT() const
2182 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2184 bool SameDay(const wxDateTime::Tm
& tm
) const
2186 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2189 wxString
Format() const
2192 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2194 wxDateTime::GetMonthName(month
).c_str(),
2196 abs(wxDateTime::ConvertYearToBC(year
)),
2197 year
> 0 ? "AD" : "BC");
2201 wxString
FormatDate() const
2204 s
.Printf("%02d-%s-%4d%s",
2206 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2207 abs(wxDateTime::ConvertYearToBC(year
)),
2208 year
> 0 ? "AD" : "BC");
2213 static const Date testDates
[] =
2215 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2216 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2217 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2218 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2219 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2220 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2221 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2222 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2223 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2224 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2225 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2226 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2227 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2228 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2229 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2232 // this test miscellaneous static wxDateTime functions
2233 static void TestTimeStatic()
2235 puts("\n*** wxDateTime static methods test ***");
2237 // some info about the current date
2238 int year
= wxDateTime::GetCurrentYear();
2239 printf("Current year %d is %sa leap one and has %d days.\n",
2241 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2242 wxDateTime::GetNumberOfDays(year
));
2244 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2245 printf("Current month is '%s' ('%s') and it has %d days\n",
2246 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2247 wxDateTime::GetMonthName(month
).c_str(),
2248 wxDateTime::GetNumberOfDays(month
));
2251 static const size_t nYears
= 5;
2252 static const size_t years
[2][nYears
] =
2254 // first line: the years to test
2255 { 1990, 1976, 2000, 2030, 1984, },
2257 // second line: TRUE if leap, FALSE otherwise
2258 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2261 for ( size_t n
= 0; n
< nYears
; n
++ )
2263 int year
= years
[0][n
];
2264 bool should
= years
[1][n
] != 0,
2265 is
= wxDateTime::IsLeapYear(year
);
2267 printf("Year %d is %sa leap year (%s)\n",
2270 should
== is
? "ok" : "ERROR");
2272 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2276 // test constructing wxDateTime objects
2277 static void TestTimeSet()
2279 puts("\n*** wxDateTime construction test ***");
2281 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2283 const Date
& d1
= testDates
[n
];
2284 wxDateTime dt
= d1
.DT();
2287 d2
.Init(dt
.GetTm());
2289 wxString s1
= d1
.Format(),
2292 printf("Date: %s == %s (%s)\n",
2293 s1
.c_str(), s2
.c_str(),
2294 s1
== s2
? "ok" : "ERROR");
2298 // test time zones stuff
2299 static void TestTimeZones()
2301 puts("\n*** wxDateTime timezone test ***");
2303 wxDateTime now
= wxDateTime::Now();
2305 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2306 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2307 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2308 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2309 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2310 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2312 wxDateTime::Tm tm
= now
.GetTm();
2313 if ( wxDateTime(tm
) != now
)
2315 printf("ERROR: got %s instead of %s\n",
2316 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2320 // test some minimal support for the dates outside the standard range
2321 static void TestTimeRange()
2323 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2325 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2327 printf("Unix epoch:\t%s\n",
2328 wxDateTime(2440587.5).Format(fmt
).c_str());
2329 printf("Feb 29, 0: \t%s\n",
2330 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2331 printf("JDN 0: \t%s\n",
2332 wxDateTime(0.0).Format(fmt
).c_str());
2333 printf("Jan 1, 1AD:\t%s\n",
2334 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2335 printf("May 29, 2099:\t%s\n",
2336 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2339 static void TestTimeTicks()
2341 puts("\n*** wxDateTime ticks test ***");
2343 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2345 const Date
& d
= testDates
[n
];
2346 if ( d
.ticks
== -1 )
2349 wxDateTime dt
= d
.DT();
2350 long ticks
= (dt
.GetValue() / 1000).ToLong();
2351 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2352 if ( ticks
== d
.ticks
)
2358 printf(" (ERROR: should be %ld, delta = %ld)\n",
2359 d
.ticks
, ticks
- d
.ticks
);
2362 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2363 ticks
= (dt
.GetValue() / 1000).ToLong();
2364 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2365 if ( ticks
== d
.gmticks
)
2371 printf(" (ERROR: should be %ld, delta = %ld)\n",
2372 d
.gmticks
, ticks
- d
.gmticks
);
2379 // test conversions to JDN &c
2380 static void TestTimeJDN()
2382 puts("\n*** wxDateTime to JDN test ***");
2384 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2386 const Date
& d
= testDates
[n
];
2387 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2388 double jdn
= dt
.GetJulianDayNumber();
2390 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2397 printf(" (ERROR: should be %f, delta = %f)\n",
2398 d
.jdn
, jdn
- d
.jdn
);
2403 // test week days computation
2404 static void TestTimeWDays()
2406 puts("\n*** wxDateTime weekday test ***");
2408 // test GetWeekDay()
2410 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2412 const Date
& d
= testDates
[n
];
2413 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2415 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2418 wxDateTime::GetWeekDayName(wday
).c_str());
2419 if ( wday
== d
.wday
)
2425 printf(" (ERROR: should be %s)\n",
2426 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2432 // test SetToWeekDay()
2433 struct WeekDateTestData
2435 Date date
; // the real date (precomputed)
2436 int nWeek
; // its week index in the month
2437 wxDateTime::WeekDay wday
; // the weekday
2438 wxDateTime::Month month
; // the month
2439 int year
; // and the year
2441 wxString
Format() const
2444 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2446 case 1: which
= "first"; break;
2447 case 2: which
= "second"; break;
2448 case 3: which
= "third"; break;
2449 case 4: which
= "fourth"; break;
2450 case 5: which
= "fifth"; break;
2452 case -1: which
= "last"; break;
2457 which
+= " from end";
2460 s
.Printf("The %s %s of %s in %d",
2462 wxDateTime::GetWeekDayName(wday
).c_str(),
2463 wxDateTime::GetMonthName(month
).c_str(),
2470 // the array data was generated by the following python program
2472 from DateTime import *
2473 from whrandom import *
2474 from string import *
2476 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2477 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2479 week = DateTimeDelta(7)
2482 year = randint(1900, 2100)
2483 month = randint(1, 12)
2484 day = randint(1, 28)
2485 dt = DateTime(year, month, day)
2486 wday = dt.day_of_week
2488 countFromEnd = choice([-1, 1])
2491 while dt.month is month:
2492 dt = dt - countFromEnd * week
2493 weekNum = weekNum + countFromEnd
2495 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2497 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2498 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2501 static const WeekDateTestData weekDatesTestData
[] =
2503 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2504 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2505 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2506 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2507 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2508 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2509 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2510 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2511 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2512 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2513 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2514 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2515 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2516 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2517 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2518 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2519 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2520 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2521 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2522 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2525 static const char *fmt
= "%d-%b-%Y";
2528 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2530 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2532 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2534 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2536 const Date
& d
= wd
.date
;
2537 if ( d
.SameDay(dt
.GetTm()) )
2543 dt
.Set(d
.day
, d
.month
, d
.year
);
2545 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2550 // test the computation of (ISO) week numbers
2551 static void TestTimeWNumber()
2553 puts("\n*** wxDateTime week number test ***");
2555 struct WeekNumberTestData
2557 Date date
; // the date
2558 wxDateTime::wxDateTime_t week
; // the week number in the year
2559 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2560 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2561 wxDateTime::wxDateTime_t dnum
; // day number in the year
2564 // data generated with the following python script:
2566 from DateTime import *
2567 from whrandom import *
2568 from string import *
2570 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2571 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2573 def GetMonthWeek(dt):
2574 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2575 if weekNumMonth < 0:
2576 weekNumMonth = weekNumMonth + 53
2579 def GetLastSundayBefore(dt):
2580 if dt.iso_week[2] == 7:
2583 return dt - DateTimeDelta(dt.iso_week[2])
2586 year = randint(1900, 2100)
2587 month = randint(1, 12)
2588 day = randint(1, 28)
2589 dt = DateTime(year, month, day)
2590 dayNum = dt.day_of_year
2591 weekNum = dt.iso_week[1]
2592 weekNumMonth = GetMonthWeek(dt)
2595 dtSunday = GetLastSundayBefore(dt)
2597 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2598 weekNumMonth2 = weekNumMonth2 + 1
2599 dtSunday = dtSunday - DateTimeDelta(7)
2601 data = { 'day': rjust(`day`, 2), \
2602 'month': monthNames[month - 1], \
2604 'weekNum': rjust(`weekNum`, 2), \
2605 'weekNumMonth': weekNumMonth, \
2606 'weekNumMonth2': weekNumMonth2, \
2607 'dayNum': rjust(`dayNum`, 3) }
2609 print " { { %(day)s, "\
2610 "wxDateTime::%(month)s, "\
2613 "%(weekNumMonth)s, "\
2614 "%(weekNumMonth2)s, "\
2615 "%(dayNum)s }," % data
2618 static const WeekNumberTestData weekNumberTestDates
[] =
2620 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2621 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2622 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2623 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2624 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2625 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2626 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2627 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2628 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2629 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2630 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2631 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2632 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2633 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2634 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2635 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2636 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2637 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2638 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2639 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2642 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2644 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2645 const Date
& d
= wn
.date
;
2647 wxDateTime dt
= d
.DT();
2649 wxDateTime::wxDateTime_t
2650 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2651 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2652 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2653 dnum
= dt
.GetDayOfYear();
2655 printf("%s: the day number is %d",
2656 d
.FormatDate().c_str(), dnum
);
2657 if ( dnum
== wn
.dnum
)
2663 printf(" (ERROR: should be %d)", wn
.dnum
);
2666 printf(", week in month is %d", wmon
);
2667 if ( wmon
== wn
.wmon
)
2673 printf(" (ERROR: should be %d)", wn
.wmon
);
2676 printf(" or %d", wmon2
);
2677 if ( wmon2
== wn
.wmon2
)
2683 printf(" (ERROR: should be %d)", wn
.wmon2
);
2686 printf(", week in year is %d", week
);
2687 if ( week
== wn
.week
)
2693 printf(" (ERROR: should be %d)\n", wn
.week
);
2698 // test DST calculations
2699 static void TestTimeDST()
2701 puts("\n*** wxDateTime DST test ***");
2703 printf("DST is%s in effect now.\n\n",
2704 wxDateTime::Now().IsDST() ? "" : " not");
2706 // taken from http://www.energy.ca.gov/daylightsaving.html
2707 static const Date datesDST
[2][2004 - 1900 + 1] =
2710 { 1, wxDateTime::Apr
, 1990 },
2711 { 7, wxDateTime::Apr
, 1991 },
2712 { 5, wxDateTime::Apr
, 1992 },
2713 { 4, wxDateTime::Apr
, 1993 },
2714 { 3, wxDateTime::Apr
, 1994 },
2715 { 2, wxDateTime::Apr
, 1995 },
2716 { 7, wxDateTime::Apr
, 1996 },
2717 { 6, wxDateTime::Apr
, 1997 },
2718 { 5, wxDateTime::Apr
, 1998 },
2719 { 4, wxDateTime::Apr
, 1999 },
2720 { 2, wxDateTime::Apr
, 2000 },
2721 { 1, wxDateTime::Apr
, 2001 },
2722 { 7, wxDateTime::Apr
, 2002 },
2723 { 6, wxDateTime::Apr
, 2003 },
2724 { 4, wxDateTime::Apr
, 2004 },
2727 { 28, wxDateTime::Oct
, 1990 },
2728 { 27, wxDateTime::Oct
, 1991 },
2729 { 25, wxDateTime::Oct
, 1992 },
2730 { 31, wxDateTime::Oct
, 1993 },
2731 { 30, wxDateTime::Oct
, 1994 },
2732 { 29, wxDateTime::Oct
, 1995 },
2733 { 27, wxDateTime::Oct
, 1996 },
2734 { 26, wxDateTime::Oct
, 1997 },
2735 { 25, wxDateTime::Oct
, 1998 },
2736 { 31, wxDateTime::Oct
, 1999 },
2737 { 29, wxDateTime::Oct
, 2000 },
2738 { 28, wxDateTime::Oct
, 2001 },
2739 { 27, wxDateTime::Oct
, 2002 },
2740 { 26, wxDateTime::Oct
, 2003 },
2741 { 31, wxDateTime::Oct
, 2004 },
2746 for ( year
= 1990; year
< 2005; year
++ )
2748 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2749 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2751 printf("DST period in the US for year %d: from %s to %s",
2752 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2754 size_t n
= year
- 1990;
2755 const Date
& dBegin
= datesDST
[0][n
];
2756 const Date
& dEnd
= datesDST
[1][n
];
2758 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2764 printf(" (ERROR: should be %s %d to %s %d)\n",
2765 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2766 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2772 for ( year
= 1990; year
< 2005; year
++ )
2774 printf("DST period in Europe for year %d: from %s to %s\n",
2776 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2777 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2781 // test wxDateTime -> text conversion
2782 static void TestTimeFormat()
2784 puts("\n*** wxDateTime formatting test ***");
2786 // some information may be lost during conversion, so store what kind
2787 // of info should we recover after a round trip
2790 CompareNone
, // don't try comparing
2791 CompareBoth
, // dates and times should be identical
2792 CompareDate
, // dates only
2793 CompareTime
// time only
2798 CompareKind compareKind
;
2800 } formatTestFormats
[] =
2802 { CompareBoth
, "---> %c" },
2803 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2804 { CompareBoth
, "Date is %x, time is %X" },
2805 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2806 { CompareNone
, "The day of year: %j, the week of year: %W" },
2807 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2810 static const Date formatTestDates
[] =
2812 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2813 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2815 // this test can't work for other centuries because it uses two digit
2816 // years in formats, so don't even try it
2817 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2818 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2819 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2823 // an extra test (as it doesn't depend on date, don't do it in the loop)
2824 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2826 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2830 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2831 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2833 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2834 printf("%s", s
.c_str());
2836 // what can we recover?
2837 int kind
= formatTestFormats
[n
].compareKind
;
2841 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2844 // converion failed - should it have?
2845 if ( kind
== CompareNone
)
2848 puts(" (ERROR: conversion back failed)");
2852 // should have parsed the entire string
2853 puts(" (ERROR: conversion back stopped too soon)");
2857 bool equal
= FALSE
; // suppress compilaer warning
2865 equal
= dt
.IsSameDate(dt2
);
2869 equal
= dt
.IsSameTime(dt2
);
2875 printf(" (ERROR: got back '%s' instead of '%s')\n",
2876 dt2
.Format().c_str(), dt
.Format().c_str());
2887 // test text -> wxDateTime conversion
2888 static void TestTimeParse()
2890 puts("\n*** wxDateTime parse test ***");
2892 struct ParseTestData
2899 static const ParseTestData parseTestDates
[] =
2901 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
2902 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
2905 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
2907 const char *format
= parseTestDates
[n
].format
;
2909 printf("%s => ", format
);
2912 if ( dt
.ParseRfc822Date(format
) )
2914 printf("%s ", dt
.Format().c_str());
2916 if ( parseTestDates
[n
].good
)
2918 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
2925 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
2930 puts("(ERROR: bad format)");
2935 printf("bad format (%s)\n",
2936 parseTestDates
[n
].good
? "ERROR" : "ok");
2941 static void TestInteractive()
2943 puts("\n*** interactive wxDateTime tests ***");
2949 printf("Enter a date: ");
2950 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2953 // kill the last '\n'
2954 buf
[strlen(buf
) - 1] = 0;
2957 const char *p
= dt
.ParseDate(buf
);
2960 printf("ERROR: failed to parse the date '%s'.\n", buf
);
2966 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
2969 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2970 dt
.Format("%b %d, %Y").c_str(),
2972 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2973 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2974 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
2977 puts("\n*** done ***");
2980 static void TestTimeMS()
2982 puts("*** testing millisecond-resolution support in wxDateTime ***");
2984 wxDateTime dt1
= wxDateTime::Now(),
2985 dt2
= wxDateTime::UNow();
2987 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
2988 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2989 printf("Dummy loop: ");
2990 for ( int i
= 0; i
< 6000; i
++ )
2992 //for ( int j = 0; j < 10; j++ )
2995 s
.Printf("%g", sqrt(i
));
3004 dt2
= wxDateTime::UNow();
3005 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3007 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3009 puts("\n*** done ***");
3012 static void TestTimeArithmetics()
3014 puts("\n*** testing arithmetic operations on wxDateTime ***");
3016 static const struct ArithmData
3018 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3019 : span(sp
), name(nam
) { }
3023 } testArithmData
[] =
3025 ArithmData(wxDateSpan::Day(), "day"),
3026 ArithmData(wxDateSpan::Week(), "week"),
3027 ArithmData(wxDateSpan::Month(), "month"),
3028 ArithmData(wxDateSpan::Year(), "year"),
3029 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3032 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3034 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3036 wxDateSpan span
= testArithmData
[n
].span
;
3040 const char *name
= testArithmData
[n
].name
;
3041 printf("%s + %s = %s, %s - %s = %s\n",
3042 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3043 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3045 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3046 if ( dt1
- span
== dt
)
3052 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3055 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3056 if ( dt2
+ span
== dt
)
3062 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3065 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3066 if ( dt2
+ 2*span
== dt1
)
3072 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3079 static void TestTimeHolidays()
3081 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3083 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3084 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3085 dtEnd
= dtStart
.GetLastMonthDay();
3087 wxDateTimeArray hol
;
3088 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3090 const wxChar
*format
= "%d-%b-%Y (%a)";
3092 printf("All holidays between %s and %s:\n",
3093 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3095 size_t count
= hol
.GetCount();
3096 for ( size_t n
= 0; n
< count
; n
++ )
3098 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3104 static void TestTimeZoneBug()
3106 puts("\n*** testing for DST/timezone bug ***\n");
3108 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3109 for ( int i
= 0; i
< 31; i
++ )
3111 printf("Date %s: week day %s.\n",
3112 date
.Format(_T("%d-%m-%Y")).c_str(),
3113 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3115 date
+= wxDateSpan::Day();
3123 // test compatibility with the old wxDate/wxTime classes
3124 static void TestTimeCompatibility()
3126 puts("\n*** wxDateTime compatibility test ***");
3128 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3129 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3131 double jdnNow
= wxDateTime::Now().GetJDN();
3132 long jdnMidnight
= (long)(jdnNow
- 0.5);
3133 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3135 jdnMidnight
= wxDate().Set().GetJulianDate();
3136 printf("wxDateTime for today: %s\n",
3137 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3139 int flags
= wxEUROPEAN
;//wxFULL;
3142 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3143 for ( int n
= 0; n
< 7; n
++ )
3145 printf("Previous %s is %s\n",
3146 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3147 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3153 #endif // TEST_DATETIME
3155 // ----------------------------------------------------------------------------
3157 // ----------------------------------------------------------------------------
3161 #include <wx/thread.h>
3163 static size_t gs_counter
= (size_t)-1;
3164 static wxCriticalSection gs_critsect
;
3165 static wxCondition gs_cond
;
3167 class MyJoinableThread
: public wxThread
3170 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3171 { m_n
= n
; Create(); }
3173 // thread execution starts here
3174 virtual ExitCode
Entry();
3180 wxThread::ExitCode
MyJoinableThread::Entry()
3182 unsigned long res
= 1;
3183 for ( size_t n
= 1; n
< m_n
; n
++ )
3187 // it's a loooong calculation :-)
3191 return (ExitCode
)res
;
3194 class MyDetachedThread
: public wxThread
3197 MyDetachedThread(size_t n
, char ch
)
3201 m_cancelled
= FALSE
;
3206 // thread execution starts here
3207 virtual ExitCode
Entry();
3210 virtual void OnExit();
3213 size_t m_n
; // number of characters to write
3214 char m_ch
; // character to write
3216 bool m_cancelled
; // FALSE if we exit normally
3219 wxThread::ExitCode
MyDetachedThread::Entry()
3222 wxCriticalSectionLocker
lock(gs_critsect
);
3223 if ( gs_counter
== (size_t)-1 )
3229 for ( size_t n
= 0; n
< m_n
; n
++ )
3231 if ( TestDestroy() )
3241 wxThread::Sleep(100);
3247 void MyDetachedThread::OnExit()
3249 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3251 wxCriticalSectionLocker
lock(gs_critsect
);
3252 if ( !--gs_counter
&& !m_cancelled
)
3256 void TestDetachedThreads()
3258 puts("\n*** Testing detached threads ***");
3260 static const size_t nThreads
= 3;
3261 MyDetachedThread
*threads
[nThreads
];
3263 for ( n
= 0; n
< nThreads
; n
++ )
3265 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3268 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3269 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3271 for ( n
= 0; n
< nThreads
; n
++ )
3276 // wait until all threads terminate
3282 void TestJoinableThreads()
3284 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3286 // calc 10! in the background
3287 MyJoinableThread
thread(10);
3290 printf("\nThread terminated with exit code %lu.\n",
3291 (unsigned long)thread
.Wait());
3294 void TestThreadSuspend()
3296 puts("\n*** Testing thread suspend/resume functions ***");
3298 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3302 // this is for this demo only, in a real life program we'd use another
3303 // condition variable which would be signaled from wxThread::Entry() to
3304 // tell us that the thread really started running - but here just wait a
3305 // bit and hope that it will be enough (the problem is, of course, that
3306 // the thread might still not run when we call Pause() which will result
3308 wxThread::Sleep(300);
3310 for ( size_t n
= 0; n
< 3; n
++ )
3314 puts("\nThread suspended");
3317 // don't sleep but resume immediately the first time
3318 wxThread::Sleep(300);
3320 puts("Going to resume the thread");
3325 puts("Waiting until it terminates now");
3327 // wait until the thread terminates
3333 void TestThreadDelete()
3335 // As above, using Sleep() is only for testing here - we must use some
3336 // synchronisation object instead to ensure that the thread is still
3337 // running when we delete it - deleting a detached thread which already
3338 // terminated will lead to a crash!
3340 puts("\n*** Testing thread delete function ***");
3342 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3346 puts("\nDeleted a thread which didn't start to run yet.");
3348 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3352 wxThread::Sleep(300);
3356 puts("\nDeleted a running thread.");
3358 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3362 wxThread::Sleep(300);
3368 puts("\nDeleted a sleeping thread.");
3370 MyJoinableThread
thread3(20);
3375 puts("\nDeleted a joinable thread.");
3377 MyJoinableThread
thread4(2);
3380 wxThread::Sleep(300);
3384 puts("\nDeleted a joinable thread which already terminated.");
3389 #endif // TEST_THREADS
3391 // ----------------------------------------------------------------------------
3393 // ----------------------------------------------------------------------------
3397 static void PrintArray(const char* name
, const wxArrayString
& array
)
3399 printf("Dump of the array '%s'\n", name
);
3401 size_t nCount
= array
.GetCount();
3402 for ( size_t n
= 0; n
< nCount
; n
++ )
3404 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3408 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3410 printf("Dump of the array '%s'\n", name
);
3412 size_t nCount
= array
.GetCount();
3413 for ( size_t n
= 0; n
< nCount
; n
++ )
3415 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3419 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3420 const wxString
& second
)
3422 return first
.length() - second
.length();
3425 int wxCMPFUNC_CONV
IntCompare(int *first
,
3428 return *first
- *second
;
3431 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3434 return *second
- *first
;
3437 static void TestArrayOfInts()
3439 puts("*** Testing wxArrayInt ***\n");
3450 puts("After sort:");
3454 puts("After reverse sort:");
3455 a
.Sort(IntRevCompare
);
3459 #include "wx/dynarray.h"
3461 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3462 #include "wx/arrimpl.cpp"
3463 WX_DEFINE_OBJARRAY(ArrayBars
);
3465 static void TestArrayOfObjects()
3467 puts("*** Testing wxObjArray ***\n");
3471 Bar
bar("second bar");
3473 printf("Initially: %u objects in the array, %u objects total.\n",
3474 bars
.GetCount(), Bar::GetNumber());
3476 bars
.Add(new Bar("first bar"));
3479 printf("Now: %u objects in the array, %u objects total.\n",
3480 bars
.GetCount(), Bar::GetNumber());
3484 printf("After Empty(): %u objects in the array, %u objects total.\n",
3485 bars
.GetCount(), Bar::GetNumber());
3488 printf("Finally: no more objects in the array, %u objects total.\n",
3492 #endif // TEST_ARRAYS
3494 // ----------------------------------------------------------------------------
3496 // ----------------------------------------------------------------------------
3500 #include "wx/timer.h"
3501 #include "wx/tokenzr.h"
3503 static void TestStringConstruction()
3505 puts("*** Testing wxString constructores ***");
3507 #define TEST_CTOR(args, res) \
3510 printf("wxString%s = %s ", #args, s.c_str()); \
3517 printf("(ERROR: should be %s)\n", res); \
3521 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3522 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3523 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3524 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3526 static const wxChar
*s
= _T("?really!");
3527 const wxChar
*start
= wxStrchr(s
, _T('r'));
3528 const wxChar
*end
= wxStrchr(s
, _T('!'));
3529 TEST_CTOR((start
, end
), _T("really"));
3534 static void TestString()
3544 for (int i
= 0; i
< 1000000; ++i
)
3548 c
= "! How'ya doin'?";
3551 c
= "Hello world! What's up?";
3556 printf ("TestString elapsed time: %ld\n", sw
.Time());
3559 static void TestPChar()
3567 for (int i
= 0; i
< 1000000; ++i
)
3569 strcpy (a
, "Hello");
3570 strcpy (b
, " world");
3571 strcpy (c
, "! How'ya doin'?");
3574 strcpy (c
, "Hello world! What's up?");
3575 if (strcmp (c
, a
) == 0)
3579 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3582 static void TestStringSub()
3584 wxString
s("Hello, world!");
3586 puts("*** Testing wxString substring extraction ***");
3588 printf("String = '%s'\n", s
.c_str());
3589 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3590 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3591 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3592 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3593 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3594 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3596 static const wxChar
*prefixes
[] =
3600 _T("Hello, world!"),
3601 _T("Hello, world!!!"),
3607 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3609 wxString prefix
= prefixes
[n
], rest
;
3610 bool rc
= s
.StartsWith(prefix
, &rest
);
3611 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3614 printf(" (the rest is '%s')\n", rest
.c_str());
3625 static void TestStringFormat()
3627 puts("*** Testing wxString formatting ***");
3630 s
.Printf("%03d", 18);
3632 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3633 printf("Number 18: %s\n", s
.c_str());
3638 // returns "not found" for npos, value for all others
3639 static wxString
PosToString(size_t res
)
3641 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3642 : wxString::Format(_T("%u"), res
);
3646 static void TestStringFind()
3648 puts("*** Testing wxString find() functions ***");
3650 static const wxChar
*strToFind
= _T("ell");
3651 static const struct StringFindTest
3655 result
; // of searching "ell" in str
3658 { _T("Well, hello world"), 0, 1 },
3659 { _T("Well, hello world"), 6, 7 },
3660 { _T("Well, hello world"), 9, wxString::npos
},
3663 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3665 const StringFindTest
& ft
= findTestData
[n
];
3666 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3668 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3669 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3671 size_t resTrue
= ft
.result
;
3672 if ( res
== resTrue
)
3678 printf(_T("(ERROR: should be %s)\n"),
3679 PosToString(resTrue
).c_str());
3686 static void TestStringTokenizer()
3688 puts("*** Testing wxStringTokenizer ***");
3690 static const wxChar
*modeNames
[] =
3694 _T("return all empty"),
3699 static const struct StringTokenizerTest
3701 const wxChar
*str
; // string to tokenize
3702 const wxChar
*delims
; // delimiters to use
3703 size_t count
; // count of token
3704 wxStringTokenizerMode mode
; // how should we tokenize it
3705 } tokenizerTestData
[] =
3707 { _T(""), _T(" "), 0 },
3708 { _T("Hello, world"), _T(" "), 2 },
3709 { _T("Hello, world "), _T(" "), 2 },
3710 { _T("Hello, world"), _T(","), 2 },
3711 { _T("Hello, world!"), _T(",!"), 2 },
3712 { _T("Hello,, world!"), _T(",!"), 3 },
3713 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3714 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3715 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3716 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3717 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3718 { _T("01/02/99"), _T("/-"), 3 },
3719 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3722 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3724 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3725 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3727 size_t count
= tkz
.CountTokens();
3728 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3729 MakePrintable(tt
.str
).c_str(),
3731 MakePrintable(tt
.delims
).c_str(),
3732 modeNames
[tkz
.GetMode()]);
3733 if ( count
== tt
.count
)
3739 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3744 // if we emulate strtok(), check that we do it correctly
3745 wxChar
*buf
, *s
= NULL
, *last
;
3747 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3749 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3750 wxStrcpy(buf
, tt
.str
);
3752 s
= wxStrtok(buf
, tt
.delims
, &last
);
3759 // now show the tokens themselves
3761 while ( tkz
.HasMoreTokens() )
3763 wxString token
= tkz
.GetNextToken();
3765 printf(_T("\ttoken %u: '%s'"),
3767 MakePrintable(token
).c_str());
3777 printf(" (ERROR: should be %s)\n", s
);
3780 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3784 // nothing to compare with
3789 if ( count2
!= count
)
3791 puts(_T("\tERROR: token count mismatch"));
3800 static void TestStringReplace()
3802 puts("*** Testing wxString::replace ***");
3804 static const struct StringReplaceTestData
3806 const wxChar
*original
; // original test string
3807 size_t start
, len
; // the part to replace
3808 const wxChar
*replacement
; // the replacement string
3809 const wxChar
*result
; // and the expected result
3810 } stringReplaceTestData
[] =
3812 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3813 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3814 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3815 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3816 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3819 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3821 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3823 wxString original
= data
.original
;
3824 original
.replace(data
.start
, data
.len
, data
.replacement
);
3826 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3827 data
.original
, data
.start
, data
.len
, data
.replacement
,
3830 if ( original
== data
.result
)
3836 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3843 #endif // TEST_STRINGS
3845 // ----------------------------------------------------------------------------
3847 // ----------------------------------------------------------------------------
3849 int main(int argc
, char **argv
)
3851 if ( !wxInitialize() )
3853 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3857 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3859 #endif // TEST_USLEEP
3862 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3864 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3865 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3867 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3868 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3869 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3870 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3872 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
3873 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
3878 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
3880 parser
.AddOption("project_name", "", "full path to project file",
3881 wxCMD_LINE_VAL_STRING
,
3882 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
3884 switch ( parser
.Parse() )
3887 wxLogMessage("Help was given, terminating.");
3891 ShowCmdLine(parser
);
3895 wxLogMessage("Syntax error detected, aborting.");
3898 #endif // TEST_CMDLINE
3909 TestStringConstruction();
3912 TestStringTokenizer();
3913 TestStringReplace();
3915 #endif // TEST_STRINGS
3928 puts("*** Initially:");
3930 PrintArray("a1", a1
);
3932 wxArrayString
a2(a1
);
3933 PrintArray("a2", a2
);
3935 wxSortedArrayString
a3(a1
);
3936 PrintArray("a3", a3
);
3938 puts("*** After deleting a string from a1");
3941 PrintArray("a1", a1
);
3942 PrintArray("a2", a2
);
3943 PrintArray("a3", a3
);
3945 puts("*** After reassigning a1 to a2 and a3");
3947 PrintArray("a2", a2
);
3948 PrintArray("a3", a3
);
3950 puts("*** After sorting a1");
3952 PrintArray("a1", a1
);
3954 puts("*** After sorting a1 in reverse order");
3956 PrintArray("a1", a1
);
3958 puts("*** After sorting a1 by the string length");
3959 a1
.Sort(StringLenCompare
);
3960 PrintArray("a1", a1
);
3962 TestArrayOfObjects();
3965 #endif // TEST_ARRAYS
3971 #ifdef TEST_DLLLOADER
3973 #endif // TEST_DLLLOADER
3977 #endif // TEST_ENVIRON
3981 #endif // TEST_EXECUTE
3983 #ifdef TEST_FILECONF
3985 #endif // TEST_FILECONF
3993 for ( size_t n
= 0; n
< 8000; n
++ )
3995 s
<< (char)('A' + (n
% 26));
3999 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4001 // this one shouldn't be truncated
4004 // but this one will because log functions use fixed size buffer
4005 // (note that it doesn't need '\n' at the end neither - will be added
4007 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4019 #ifdef TEST_FILENAME
4020 TestFileNameSplit();
4023 TestFileNameConstruction();
4025 TestFileNameComparison();
4026 TestFileNameOperations();
4028 #endif // TEST_FILENAME
4031 int nCPUs
= wxThread::GetCPUCount();
4032 printf("This system has %d CPUs\n", nCPUs
);
4034 wxThread::SetConcurrency(nCPUs
);
4036 if ( argc
> 1 && argv
[1][0] == 't' )
4037 wxLog::AddTraceMask("thread");
4040 TestDetachedThreads();
4042 TestJoinableThreads();
4044 TestThreadSuspend();
4048 #endif // TEST_THREADS
4050 #ifdef TEST_LONGLONG
4051 // seed pseudo random generator
4052 srand((unsigned)time(NULL
));
4060 TestMultiplication();
4063 TestLongLongConversion();
4064 TestBitOperations();
4066 TestLongLongComparison();
4067 #endif // TEST_LONGLONG
4074 wxLog::AddTraceMask(_T("mime"));
4081 TestMimeAssociate();
4084 #ifdef TEST_INFO_FUNCTIONS
4087 #endif // TEST_INFO_FUNCTIONS
4089 #ifdef TEST_REGISTRY
4092 TestRegistryAssociation();
4093 #endif // TEST_REGISTRY
4101 #endif // TEST_SOCKETS
4104 wxLog::AddTraceMask(_T("ftp"));
4107 TestProtocolFtpUpload();
4112 #endif // TEST_STREAMS
4116 #endif // TEST_TIMER
4118 #ifdef TEST_DATETIME
4131 TestTimeArithmetics();
4140 #endif // TEST_DATETIME
4146 #endif // TEST_VCARD
4150 #endif // TEST_WCHAR
4153 TestZipStreamRead();
4158 TestZlibStreamWrite();
4159 TestZlibStreamRead();