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 struct FileNameInfo
601 const wxChar
*fullname
;
607 { _T("/usr/bin/ls"), _T("/usr/bin"), _T("ls"), _T("") },
608 { _T("/usr/bin/"), _T("/usr/bin"), _T(""), _T("") },
609 { _T("~/.zshrc"), _T("~"), _T(".zshrc"), _T("") },
610 { _T("../../foo"), _T("../.."), _T("foo"), _T("") },
611 { _T("foo.bar"), _T(""), _T("foo"), _T("bar") },
612 { _T("~/foo.bar"), _T("~"), _T("foo"), _T("bar") },
613 { _T("Mahogany-0.60/foo.bar"), _T("Mahogany-0.60"), _T("foo"), _T("bar") },
614 { _T("/tmp/wxwin.tar.bz"), _T("/tmp"), _T("wxwin.tar"), _T("bz") },
617 static void TestFileNameConstruction()
619 puts("*** testing wxFileName construction ***");
621 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
623 wxFileName
fn(filenames
[n
].fullname
, wxPATH_UNIX
);
625 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
626 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
628 puts("ERROR (couldn't be normalized)");
632 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
639 static void TestFileNameSplit()
641 puts("*** testing wxFileName splitting ***");
643 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
645 const FileNameInfo
&fni
= filenames
[n
];
646 wxString path
, name
, ext
;
647 wxFileName::SplitPath(fni
.fullname
, &path
, &name
, &ext
);
649 printf("%s -> path = '%s', name = '%s', ext = '%s'",
650 fni
.fullname
, path
.c_str(), name
.c_str(), ext
.c_str());
651 if ( path
!= fni
.path
)
652 printf(" (ERROR: path = '%s')", fni
.path
);
653 if ( name
!= fni
.name
)
654 printf(" (ERROR: name = '%s')", fni
.name
);
655 if ( ext
!= fni
.ext
)
656 printf(" (ERROR: ext = '%s')", fni
.ext
);
663 static void TestFileNameComparison()
668 static void TestFileNameOperations()
673 static void TestFileNameCwd()
678 #endif // TEST_FILENAME
680 // ----------------------------------------------------------------------------
682 // ----------------------------------------------------------------------------
690 Foo(int n_
) { n
= n_
; count
++; }
698 size_t Foo::count
= 0;
700 WX_DECLARE_LIST(Foo
, wxListFoos
);
701 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
703 #include <wx/listimpl.cpp>
705 WX_DEFINE_LIST(wxListFoos
);
707 static void TestHash()
709 puts("*** Testing wxHashTable ***\n");
713 hash
.DeleteContents(TRUE
);
715 printf("Hash created: %u foos in hash, %u foos totally\n",
716 hash
.GetCount(), Foo::count
);
718 static const int hashTestData
[] =
720 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
724 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
726 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
729 printf("Hash filled: %u foos in hash, %u foos totally\n",
730 hash
.GetCount(), Foo::count
);
732 puts("Hash access test:");
733 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
735 printf("\tGetting element with key %d, value %d: ",
737 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
740 printf("ERROR, not found.\n");
744 printf("%d (%s)\n", foo
->n
,
745 (size_t)foo
->n
== n
? "ok" : "ERROR");
749 printf("\nTrying to get an element not in hash: ");
751 if ( hash
.Get(1234) || hash
.Get(1, 0) )
753 puts("ERROR: found!");
757 puts("ok (not found)");
761 printf("Hash destroyed: %u foos left\n", Foo::count
);
766 // ----------------------------------------------------------------------------
768 // ----------------------------------------------------------------------------
774 WX_DECLARE_LIST(Bar
, wxListBars
);
775 #include <wx/listimpl.cpp>
776 WX_DEFINE_LIST(wxListBars
);
778 static void TestListCtor()
780 puts("*** Testing wxList construction ***\n");
784 list1
.Append(new Bar(_T("first")));
785 list1
.Append(new Bar(_T("second")));
787 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
788 list1
.GetCount(), Bar::GetNumber());
793 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
794 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
796 list1
.DeleteContents(TRUE
);
799 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
804 // ----------------------------------------------------------------------------
806 // ----------------------------------------------------------------------------
810 #include <wx/mimetype.h>
812 static wxMimeTypesManager g_mimeManager
;
814 static void TestMimeEnum()
816 wxArrayString mimetypes
;
818 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
820 printf("*** All %u known filetypes: ***\n", count
);
825 for ( size_t n
= 0; n
< count
; n
++ )
827 wxFileType
*filetype
= g_mimeManager
.GetFileTypeFromMimeType(mimetypes
[n
]);
830 printf("nothing known about the filetype '%s'!\n",
831 mimetypes
[n
].c_str());
835 filetype
->GetDescription(&desc
);
836 filetype
->GetExtensions(exts
);
838 filetype
->GetIcon(NULL
);
841 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
848 printf("\t%s: %s (%s)\n",
849 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
853 static void TestMimeOverride()
855 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
857 wxString mailcap
= _T("/tmp/mailcap"),
858 mimetypes
= _T("/tmp/mime.types");
860 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
862 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
863 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
865 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
868 static void TestMimeFilename()
870 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
872 static const wxChar
*filenames
[] =
879 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
881 const wxString fname
= filenames
[n
];
882 wxString ext
= fname
.AfterLast(_T('.'));
883 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
886 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
891 if ( !ft
->GetDescription(&desc
) )
892 desc
= _T("<no description>");
895 if ( !ft
->GetOpenCommand(&cmd
,
896 wxFileType::MessageParameters(fname
, _T(""))) )
897 cmd
= _T("<no command available>");
899 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
900 fname
.c_str(), desc
.c_str(), cmd
.c_str());
907 static void TestMimeAssociate()
909 wxPuts(_T("*** Testing creation of filetype association ***\n"));
911 wxFileType
*ft
= g_mimeManager
.Associate
914 _T("application/x-xyz"),
915 _T("XYZFile"), // filetype (MSW only)
916 _T("XYZ File") // description (Unix only)
920 wxPuts(_T("ERROR: failed to create association!"));
924 if ( !ft
->SetOpenCommand(_T("myprogram")) )
926 wxPuts(_T("ERROR: failed to set open command!"));
935 // ----------------------------------------------------------------------------
936 // misc information functions
937 // ----------------------------------------------------------------------------
939 #ifdef TEST_INFO_FUNCTIONS
941 #include <wx/utils.h>
943 static void TestOsInfo()
945 puts("*** Testing OS info functions ***\n");
948 wxGetOsVersion(&major
, &minor
);
949 printf("Running under: %s, version %d.%d\n",
950 wxGetOsDescription().c_str(), major
, minor
);
952 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
954 printf("Host name is %s (%s).\n",
955 wxGetHostName().c_str(), wxGetFullHostName().c_str());
960 static void TestUserInfo()
962 puts("*** Testing user info functions ***\n");
964 printf("User id is:\t%s\n", wxGetUserId().c_str());
965 printf("User name is:\t%s\n", wxGetUserName().c_str());
966 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
967 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
972 #endif // TEST_INFO_FUNCTIONS
974 // ----------------------------------------------------------------------------
976 // ----------------------------------------------------------------------------
980 #include <wx/longlong.h>
981 #include <wx/timer.h>
983 // make a 64 bit number from 4 16 bit ones
984 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
986 // get a random 64 bit number
987 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
989 #if wxUSE_LONGLONG_WX
990 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
991 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
992 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
993 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
994 #endif // wxUSE_LONGLONG_WX
996 static void TestSpeed()
998 static const long max
= 100000000;
1005 for ( n
= 0; n
< max
; n
++ )
1010 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1013 #if wxUSE_LONGLONG_NATIVE
1018 for ( n
= 0; n
< max
; n
++ )
1023 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1025 #endif // wxUSE_LONGLONG_NATIVE
1031 for ( n
= 0; n
< max
; n
++ )
1036 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1040 static void TestLongLongConversion()
1042 puts("*** Testing wxLongLong conversions ***\n");
1046 for ( size_t n
= 0; n
< 100000; n
++ )
1050 #if wxUSE_LONGLONG_NATIVE
1051 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1053 wxASSERT_MSG( a
== b
, "conversions failure" );
1055 puts("Can't do it without native long long type, test skipped.");
1058 #endif // wxUSE_LONGLONG_NATIVE
1060 if ( !(nTested
% 1000) )
1072 static void TestMultiplication()
1074 puts("*** Testing wxLongLong multiplication ***\n");
1078 for ( size_t n
= 0; n
< 100000; n
++ )
1083 #if wxUSE_LONGLONG_NATIVE
1084 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1085 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1087 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1088 #else // !wxUSE_LONGLONG_NATIVE
1089 puts("Can't do it without native long long type, test skipped.");
1092 #endif // wxUSE_LONGLONG_NATIVE
1094 if ( !(nTested
% 1000) )
1106 static void TestDivision()
1108 puts("*** Testing wxLongLong division ***\n");
1112 for ( size_t n
= 0; n
< 100000; n
++ )
1114 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1115 // multiplication will not overflow)
1116 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1118 // get a random long (not wxLongLong for now) to divide it with
1123 #if wxUSE_LONGLONG_NATIVE
1124 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1126 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1127 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1128 #else // !wxUSE_LONGLONG_NATIVE
1129 // verify the result
1130 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1131 #endif // wxUSE_LONGLONG_NATIVE
1133 if ( !(nTested
% 1000) )
1145 static void TestAddition()
1147 puts("*** Testing wxLongLong addition ***\n");
1151 for ( size_t n
= 0; n
< 100000; n
++ )
1157 #if wxUSE_LONGLONG_NATIVE
1158 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1159 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1160 "addition failure" );
1161 #else // !wxUSE_LONGLONG_NATIVE
1162 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1163 #endif // wxUSE_LONGLONG_NATIVE
1165 if ( !(nTested
% 1000) )
1177 static void TestBitOperations()
1179 puts("*** Testing wxLongLong bit operation ***\n");
1183 for ( size_t n
= 0; n
< 100000; n
++ )
1187 #if wxUSE_LONGLONG_NATIVE
1188 for ( size_t n
= 0; n
< 33; n
++ )
1191 #else // !wxUSE_LONGLONG_NATIVE
1192 puts("Can't do it without native long long type, test skipped.");
1195 #endif // wxUSE_LONGLONG_NATIVE
1197 if ( !(nTested
% 1000) )
1209 static void TestLongLongComparison()
1211 puts("*** Testing wxLongLong comparison ***\n");
1213 static const long testLongs
[] =
1224 static const long ls
[2] =
1230 wxLongLongWx lls
[2];
1234 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1238 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1240 res
= lls
[m
] > testLongs
[n
];
1241 printf("0x%lx > 0x%lx is %s (%s)\n",
1242 ls
[m
], testLongs
[n
], res
? "true" : "false",
1243 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1245 res
= lls
[m
] < testLongs
[n
];
1246 printf("0x%lx < 0x%lx is %s (%s)\n",
1247 ls
[m
], testLongs
[n
], res
? "true" : "false",
1248 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1250 res
= lls
[m
] == testLongs
[n
];
1251 printf("0x%lx == 0x%lx is %s (%s)\n",
1252 ls
[m
], testLongs
[n
], res
? "true" : "false",
1253 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1261 #endif // TEST_LONGLONG
1263 // ----------------------------------------------------------------------------
1265 // ----------------------------------------------------------------------------
1267 // this is for MSW only
1269 #undef TEST_REGISTRY
1272 #ifdef TEST_REGISTRY
1274 #include <wx/msw/registry.h>
1276 // I chose this one because I liked its name, but it probably only exists under
1278 static const wxChar
*TESTKEY
=
1279 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1281 static void TestRegistryRead()
1283 puts("*** testing registry reading ***");
1285 wxRegKey
key(TESTKEY
);
1286 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1289 puts("ERROR: test key can't be opened, aborting test.");
1294 size_t nSubKeys
, nValues
;
1295 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1297 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1300 printf("Enumerating values:\n");
1304 bool cont
= key
.GetFirstValue(value
, dummy
);
1307 printf("Value '%s': type ", value
.c_str());
1308 switch ( key
.GetValueType(value
) )
1310 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1311 case wxRegKey::Type_String
: printf("SZ"); break;
1312 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1313 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1314 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1315 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1316 default: printf("other (unknown)"); break;
1319 printf(", value = ");
1320 if ( key
.IsNumericValue(value
) )
1323 key
.QueryValue(value
, &val
);
1329 key
.QueryValue(value
, val
);
1330 printf("'%s'", val
.c_str());
1332 key
.QueryRawValue(value
, val
);
1333 printf(" (raw value '%s')", val
.c_str());
1338 cont
= key
.GetNextValue(value
, dummy
);
1342 static void TestRegistryAssociation()
1345 The second call to deleteself genertaes an error message, with a
1346 messagebox saying .flo is crucial to system operation, while the .ddf
1347 call also fails, but with no error message
1352 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1354 key
= "ddxf_auto_file" ;
1355 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1357 key
= "ddxf_auto_file" ;
1358 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1361 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1363 key
= "program \"%1\"" ;
1365 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1367 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1369 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1371 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1375 #endif // TEST_REGISTRY
1377 // ----------------------------------------------------------------------------
1379 // ----------------------------------------------------------------------------
1383 #include <wx/socket.h>
1384 #include <wx/protocol/protocol.h>
1385 #include <wx/protocol/http.h>
1387 static void TestSocketServer()
1389 puts("*** Testing wxSocketServer ***\n");
1391 static const int PORT
= 3000;
1396 wxSocketServer
*server
= new wxSocketServer(addr
);
1397 if ( !server
->Ok() )
1399 puts("ERROR: failed to bind");
1406 printf("Server: waiting for connection on port %d...\n", PORT
);
1408 wxSocketBase
*socket
= server
->Accept();
1411 puts("ERROR: wxSocketServer::Accept() failed.");
1415 puts("Server: got a client.");
1417 server
->SetTimeout(60); // 1 min
1419 while ( socket
->IsConnected() )
1425 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1427 // don't log error if the client just close the connection
1428 if ( socket
->IsConnected() )
1430 puts("ERROR: in wxSocket::Read.");
1450 printf("Server: got '%s'.\n", s
.c_str());
1451 if ( s
== _T("bye") )
1458 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1459 socket
->Write("\r\n", 2);
1460 printf("Server: wrote '%s'.\n", s
.c_str());
1463 puts("Server: lost a client.");
1468 // same as "delete server" but is consistent with GUI programs
1472 static void TestSocketClient()
1474 puts("*** Testing wxSocketClient ***\n");
1476 static const char *hostname
= "www.wxwindows.org";
1479 addr
.Hostname(hostname
);
1482 printf("--- Attempting to connect to %s:80...\n", hostname
);
1484 wxSocketClient client
;
1485 if ( !client
.Connect(addr
) )
1487 printf("ERROR: failed to connect to %s\n", hostname
);
1491 printf("--- Connected to %s:%u...\n",
1492 addr
.Hostname().c_str(), addr
.Service());
1496 // could use simply "GET" here I suppose
1498 wxString::Format("GET http://%s/\r\n", hostname
);
1499 client
.Write(cmdGet
, cmdGet
.length());
1500 printf("--- Sent command '%s' to the server\n",
1501 MakePrintable(cmdGet
).c_str());
1502 client
.Read(buf
, WXSIZEOF(buf
));
1503 printf("--- Server replied:\n%s", buf
);
1507 #endif // TEST_SOCKETS
1511 #include <wx/protocol/ftp.h>
1513 static void TestProtocolFtp()
1515 puts("*** Testing wxFTP download ***\n");
1519 #ifdef TEST_WUFTPD // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1520 static const char *hostname
= "ftp.eudora.com";
1521 if ( !ftp
.Connect(hostname
) )
1523 printf("ERROR: failed to connect to %s\n", hostname
);
1527 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1528 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1531 printf("ERROR: couldn't get input stream for %s\n", filename
);
1535 size_t size
= in
->StreamSize();
1536 printf("Reading file %s (%u bytes)...", filename
, size
);
1538 char *data
= new char[size
];
1539 if ( !in
->Read(data
, size
) )
1541 puts("ERROR: read error");
1545 printf("Successfully retrieved the file.\n");
1552 #else // !TEST_WUFTPD
1555 static const char *hostname
= "ftp.wxwindows.org";
1556 static const char *directory
= "pub";
1557 static const char *filename
= "welcome.msg";
1559 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1561 static const char *hostname
= "localhost";
1562 static const char *user
= "zeitlin";
1563 static const char *directory
= "/tmp";
1566 ftp
.SetPassword("password");
1568 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1571 if ( !ftp
.Connect(hostname
) )
1573 printf("ERROR: failed to connect to %s\n", hostname
);
1577 printf("--- Connected to %s, current directory is '%s'\n",
1578 hostname
, ftp
.Pwd().c_str());
1581 if ( !ftp
.ChDir(directory
) )
1583 printf("ERROR: failed to cd to %s\n", directory
);
1586 // test NLIST and LIST
1587 wxArrayString files
;
1588 if ( !ftp
.GetFilesList(files
) )
1590 puts("ERROR: failed to get NLIST of files");
1594 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1595 size_t count
= files
.GetCount();
1596 for ( size_t n
= 0; n
< count
; n
++ )
1598 printf("\t%s\n", files
[n
].c_str());
1600 puts("End of the file list");
1603 if ( !ftp
.GetDirList(files
) )
1605 puts("ERROR: failed to get LIST of files");
1609 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1610 size_t count
= files
.GetCount();
1611 for ( size_t n
= 0; n
< count
; n
++ )
1613 printf("\t%s\n", files
[n
].c_str());
1615 puts("End of the file list");
1618 if ( !ftp
.ChDir(_T("..")) )
1620 puts("ERROR: failed to cd to ..");
1624 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1627 printf("ERROR: couldn't get input stream for %s\n", filename
);
1631 size_t size
= in
->StreamSize();
1632 printf("Reading file %s (%u bytes)...", filename
, size
);
1634 char *data
= new char[size
];
1635 if ( !in
->Read(data
, size
) )
1637 puts("ERROR: read error");
1641 printf("\nContents of %s:\n%s\n", filename
, data
);
1648 // test some other FTP commands
1649 if ( ftp
.SendCommand("STAT") != '2' )
1651 puts("ERROR: STAT failed");
1655 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1658 if ( ftp
.SendCommand("HELP SITE") != '2' )
1660 puts("ERROR: HELP SITE failed");
1664 printf("The list of site-specific commands:\n\n%s\n",
1665 ftp
.GetLastResult().c_str());
1668 #endif // TEST_WUFTPD/!TEST_WUFTPD
1671 static void TestProtocolFtpUpload()
1673 puts("*** Testing wxFTP uploading ***\n");
1675 static const char *hostname
= "localhost";
1677 printf("--- Attempting to connect to %s:21...\n", hostname
);
1680 ftp
.SetUser("zeitlin");
1681 ftp
.SetPassword("password");
1682 if ( !ftp
.Connect(hostname
) )
1684 printf("ERROR: failed to connect to %s\n", hostname
);
1688 printf("--- Connected to %s, current directory is '%s'\n",
1689 hostname
, ftp
.Pwd().c_str());
1692 static const char *file1
= "test1";
1693 static const char *file2
= "test2";
1694 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1697 printf("--- Uploading to %s ---\n", file1
);
1698 out
->Write("First hello", 11);
1702 // send a command to check the remote file
1703 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1705 printf("ERROR: STAT %s failed\n", file1
);
1709 printf("STAT %s returned:\n\n%s\n",
1710 file1
, ftp
.GetLastResult().c_str());
1713 out
= ftp
.GetOutputStream(file2
);
1716 printf("--- Uploading to %s ---\n", file1
);
1717 out
->Write("Second hello", 12);
1725 // ----------------------------------------------------------------------------
1727 // ----------------------------------------------------------------------------
1731 #include <wx/mstream.h>
1733 static void TestMemoryStream()
1735 puts("*** Testing wxMemoryInputStream ***");
1738 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1740 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1741 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1742 while ( !memInpStream
.Eof() )
1744 putchar(memInpStream
.GetC());
1747 puts("\n*** wxMemoryInputStream test done ***");
1750 #endif // TEST_STREAMS
1752 // ----------------------------------------------------------------------------
1754 // ----------------------------------------------------------------------------
1758 #include <wx/timer.h>
1759 #include <wx/utils.h>
1761 static void TestStopWatch()
1763 puts("*** Testing wxStopWatch ***\n");
1766 printf("Sleeping 3 seconds...");
1768 printf("\telapsed time: %ldms\n", sw
.Time());
1771 printf("Sleeping 2 more seconds...");
1773 printf("\telapsed time: %ldms\n", sw
.Time());
1776 printf("And 3 more seconds...");
1778 printf("\telapsed time: %ldms\n", sw
.Time());
1781 puts("\nChecking for 'backwards clock' bug...");
1782 for ( size_t n
= 0; n
< 70; n
++ )
1786 for ( size_t m
= 0; m
< 100000; m
++ )
1788 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1790 puts("\ntime is negative - ERROR!");
1800 #endif // TEST_TIMER
1802 // ----------------------------------------------------------------------------
1804 // ----------------------------------------------------------------------------
1808 #include <wx/vcard.h>
1810 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1813 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1817 wxString(_T('\t'), level
).c_str(),
1818 vcObj
->GetName().c_str());
1821 switch ( vcObj
->GetType() )
1823 case wxVCardObject::String
:
1824 case wxVCardObject::UString
:
1827 vcObj
->GetValue(&val
);
1828 value
<< _T('"') << val
<< _T('"');
1832 case wxVCardObject::Int
:
1835 vcObj
->GetValue(&i
);
1836 value
.Printf(_T("%u"), i
);
1840 case wxVCardObject::Long
:
1843 vcObj
->GetValue(&l
);
1844 value
.Printf(_T("%lu"), l
);
1848 case wxVCardObject::None
:
1851 case wxVCardObject::Object
:
1852 value
= _T("<node>");
1856 value
= _T("<unknown value type>");
1860 printf(" = %s", value
.c_str());
1863 DumpVObject(level
+ 1, *vcObj
);
1866 vcObj
= vcard
.GetNextProp(&cookie
);
1870 static void DumpVCardAddresses(const wxVCard
& vcard
)
1872 puts("\nShowing all addresses from vCard:\n");
1876 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1880 int flags
= addr
->GetFlags();
1881 if ( flags
& wxVCardAddress::Domestic
)
1883 flagsStr
<< _T("domestic ");
1885 if ( flags
& wxVCardAddress::Intl
)
1887 flagsStr
<< _T("international ");
1889 if ( flags
& wxVCardAddress::Postal
)
1891 flagsStr
<< _T("postal ");
1893 if ( flags
& wxVCardAddress::Parcel
)
1895 flagsStr
<< _T("parcel ");
1897 if ( flags
& wxVCardAddress::Home
)
1899 flagsStr
<< _T("home ");
1901 if ( flags
& wxVCardAddress::Work
)
1903 flagsStr
<< _T("work ");
1906 printf("Address %u:\n"
1908 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1911 addr
->GetPostOffice().c_str(),
1912 addr
->GetExtAddress().c_str(),
1913 addr
->GetStreet().c_str(),
1914 addr
->GetLocality().c_str(),
1915 addr
->GetRegion().c_str(),
1916 addr
->GetPostalCode().c_str(),
1917 addr
->GetCountry().c_str()
1921 addr
= vcard
.GetNextAddress(&cookie
);
1925 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
1927 puts("\nShowing all phone numbers from vCard:\n");
1931 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
1935 int flags
= phone
->GetFlags();
1936 if ( flags
& wxVCardPhoneNumber::Voice
)
1938 flagsStr
<< _T("voice ");
1940 if ( flags
& wxVCardPhoneNumber::Fax
)
1942 flagsStr
<< _T("fax ");
1944 if ( flags
& wxVCardPhoneNumber::Cellular
)
1946 flagsStr
<< _T("cellular ");
1948 if ( flags
& wxVCardPhoneNumber::Modem
)
1950 flagsStr
<< _T("modem ");
1952 if ( flags
& wxVCardPhoneNumber::Home
)
1954 flagsStr
<< _T("home ");
1956 if ( flags
& wxVCardPhoneNumber::Work
)
1958 flagsStr
<< _T("work ");
1961 printf("Phone number %u:\n"
1966 phone
->GetNumber().c_str()
1970 phone
= vcard
.GetNextPhoneNumber(&cookie
);
1974 static void TestVCardRead()
1976 puts("*** Testing wxVCard reading ***\n");
1978 wxVCard
vcard(_T("vcard.vcf"));
1979 if ( !vcard
.IsOk() )
1981 puts("ERROR: couldn't load vCard.");
1985 // read individual vCard properties
1986 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
1990 vcObj
->GetValue(&value
);
1995 value
= _T("<none>");
1998 printf("Full name retrieved directly: %s\n", value
.c_str());
2001 if ( !vcard
.GetFullName(&value
) )
2003 value
= _T("<none>");
2006 printf("Full name from wxVCard API: %s\n", value
.c_str());
2008 // now show how to deal with multiply occuring properties
2009 DumpVCardAddresses(vcard
);
2010 DumpVCardPhoneNumbers(vcard
);
2012 // and finally show all
2013 puts("\nNow dumping the entire vCard:\n"
2014 "-----------------------------\n");
2016 DumpVObject(0, vcard
);
2020 static void TestVCardWrite()
2022 puts("*** Testing wxVCard writing ***\n");
2025 if ( !vcard
.IsOk() )
2027 puts("ERROR: couldn't create vCard.");
2032 vcard
.SetName("Zeitlin", "Vadim");
2033 vcard
.SetFullName("Vadim Zeitlin");
2034 vcard
.SetOrganization("wxWindows", "R&D");
2036 // just dump the vCard back
2037 puts("Entire vCard follows:\n");
2038 puts(vcard
.Write());
2042 #endif // TEST_VCARD
2044 // ----------------------------------------------------------------------------
2045 // wide char (Unicode) support
2046 // ----------------------------------------------------------------------------
2050 #include <wx/strconv.h>
2051 #include <wx/buffer.h>
2053 static void TestUtf8()
2055 puts("*** Testing UTF8 support ***\n");
2057 wxString testString
= "français";
2059 "************ French - Français ****************"
2060 "Juste un petit exemple pour dire que les français aussi"
2061 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
2064 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
2065 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
2066 wxString
testString2(pwz
, wxConvLocal
);
2068 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
2070 char *psz
= "fran" "\xe7" "ais";
2071 size_t len
= strlen(psz
);
2072 wchar_t *pwz2
= new wchar_t[len
+ 1];
2073 for ( size_t n
= 0; n
<= len
; n
++ )
2075 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
2078 wxString
testString3(pwz2
, wxConvUTF8
);
2081 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
2084 #endif // TEST_WCHAR
2086 // ----------------------------------------------------------------------------
2088 // ----------------------------------------------------------------------------
2092 #include "wx/zipstrm.h"
2094 static void TestZipStreamRead()
2096 puts("*** Testing ZIP reading ***\n");
2098 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
2099 printf("Archive size: %u\n", istr
.GetSize());
2101 puts("Dumping the file:");
2102 while ( !istr
.Eof() )
2104 putchar(istr
.GetC());
2108 puts("\n----- done ------");
2113 // ----------------------------------------------------------------------------
2115 // ----------------------------------------------------------------------------
2119 #include <wx/zstream.h>
2120 #include <wx/wfstream.h>
2122 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2123 static const char *TEST_DATA
= "hello and hello again";
2125 static void TestZlibStreamWrite()
2127 puts("*** Testing Zlib stream reading ***\n");
2129 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2130 wxZlibOutputStream
ostr(fileOutStream
, 0);
2131 printf("Compressing the test string... ");
2132 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2135 puts("(ERROR: failed)");
2142 puts("\n----- done ------");
2145 static void TestZlibStreamRead()
2147 puts("*** Testing Zlib stream reading ***\n");
2149 wxFileInputStream
fileInStream(FILENAME_GZ
);
2150 wxZlibInputStream
istr(fileInStream
);
2151 printf("Archive size: %u\n", istr
.GetSize());
2153 puts("Dumping the file:");
2154 while ( !istr
.Eof() )
2156 putchar(istr
.GetC());
2160 puts("\n----- done ------");
2165 // ----------------------------------------------------------------------------
2167 // ----------------------------------------------------------------------------
2169 #ifdef TEST_DATETIME
2171 #include <wx/date.h>
2173 #include <wx/datetime.h>
2178 wxDateTime::wxDateTime_t day
;
2179 wxDateTime::Month month
;
2181 wxDateTime::wxDateTime_t hour
, min
, sec
;
2183 wxDateTime::WeekDay wday
;
2184 time_t gmticks
, ticks
;
2186 void Init(const wxDateTime::Tm
& tm
)
2195 gmticks
= ticks
= -1;
2198 wxDateTime
DT() const
2199 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2201 bool SameDay(const wxDateTime::Tm
& tm
) const
2203 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2206 wxString
Format() const
2209 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2211 wxDateTime::GetMonthName(month
).c_str(),
2213 abs(wxDateTime::ConvertYearToBC(year
)),
2214 year
> 0 ? "AD" : "BC");
2218 wxString
FormatDate() const
2221 s
.Printf("%02d-%s-%4d%s",
2223 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2224 abs(wxDateTime::ConvertYearToBC(year
)),
2225 year
> 0 ? "AD" : "BC");
2230 static const Date testDates
[] =
2232 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2233 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2234 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2235 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2236 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2237 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2238 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2239 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2240 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2241 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2242 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2243 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2244 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2245 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2246 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2249 // this test miscellaneous static wxDateTime functions
2250 static void TestTimeStatic()
2252 puts("\n*** wxDateTime static methods test ***");
2254 // some info about the current date
2255 int year
= wxDateTime::GetCurrentYear();
2256 printf("Current year %d is %sa leap one and has %d days.\n",
2258 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2259 wxDateTime::GetNumberOfDays(year
));
2261 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2262 printf("Current month is '%s' ('%s') and it has %d days\n",
2263 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2264 wxDateTime::GetMonthName(month
).c_str(),
2265 wxDateTime::GetNumberOfDays(month
));
2268 static const size_t nYears
= 5;
2269 static const size_t years
[2][nYears
] =
2271 // first line: the years to test
2272 { 1990, 1976, 2000, 2030, 1984, },
2274 // second line: TRUE if leap, FALSE otherwise
2275 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2278 for ( size_t n
= 0; n
< nYears
; n
++ )
2280 int year
= years
[0][n
];
2281 bool should
= years
[1][n
] != 0,
2282 is
= wxDateTime::IsLeapYear(year
);
2284 printf("Year %d is %sa leap year (%s)\n",
2287 should
== is
? "ok" : "ERROR");
2289 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2293 // test constructing wxDateTime objects
2294 static void TestTimeSet()
2296 puts("\n*** wxDateTime construction test ***");
2298 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2300 const Date
& d1
= testDates
[n
];
2301 wxDateTime dt
= d1
.DT();
2304 d2
.Init(dt
.GetTm());
2306 wxString s1
= d1
.Format(),
2309 printf("Date: %s == %s (%s)\n",
2310 s1
.c_str(), s2
.c_str(),
2311 s1
== s2
? "ok" : "ERROR");
2315 // test time zones stuff
2316 static void TestTimeZones()
2318 puts("\n*** wxDateTime timezone test ***");
2320 wxDateTime now
= wxDateTime::Now();
2322 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2323 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2324 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2325 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2326 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2327 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2329 wxDateTime::Tm tm
= now
.GetTm();
2330 if ( wxDateTime(tm
) != now
)
2332 printf("ERROR: got %s instead of %s\n",
2333 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2337 // test some minimal support for the dates outside the standard range
2338 static void TestTimeRange()
2340 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2342 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2344 printf("Unix epoch:\t%s\n",
2345 wxDateTime(2440587.5).Format(fmt
).c_str());
2346 printf("Feb 29, 0: \t%s\n",
2347 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2348 printf("JDN 0: \t%s\n",
2349 wxDateTime(0.0).Format(fmt
).c_str());
2350 printf("Jan 1, 1AD:\t%s\n",
2351 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2352 printf("May 29, 2099:\t%s\n",
2353 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2356 static void TestTimeTicks()
2358 puts("\n*** wxDateTime ticks test ***");
2360 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2362 const Date
& d
= testDates
[n
];
2363 if ( d
.ticks
== -1 )
2366 wxDateTime dt
= d
.DT();
2367 long ticks
= (dt
.GetValue() / 1000).ToLong();
2368 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2369 if ( ticks
== d
.ticks
)
2375 printf(" (ERROR: should be %ld, delta = %ld)\n",
2376 d
.ticks
, ticks
- d
.ticks
);
2379 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2380 ticks
= (dt
.GetValue() / 1000).ToLong();
2381 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2382 if ( ticks
== d
.gmticks
)
2388 printf(" (ERROR: should be %ld, delta = %ld)\n",
2389 d
.gmticks
, ticks
- d
.gmticks
);
2396 // test conversions to JDN &c
2397 static void TestTimeJDN()
2399 puts("\n*** wxDateTime to JDN test ***");
2401 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2403 const Date
& d
= testDates
[n
];
2404 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2405 double jdn
= dt
.GetJulianDayNumber();
2407 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2414 printf(" (ERROR: should be %f, delta = %f)\n",
2415 d
.jdn
, jdn
- d
.jdn
);
2420 // test week days computation
2421 static void TestTimeWDays()
2423 puts("\n*** wxDateTime weekday test ***");
2425 // test GetWeekDay()
2427 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2429 const Date
& d
= testDates
[n
];
2430 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2432 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2435 wxDateTime::GetWeekDayName(wday
).c_str());
2436 if ( wday
== d
.wday
)
2442 printf(" (ERROR: should be %s)\n",
2443 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2449 // test SetToWeekDay()
2450 struct WeekDateTestData
2452 Date date
; // the real date (precomputed)
2453 int nWeek
; // its week index in the month
2454 wxDateTime::WeekDay wday
; // the weekday
2455 wxDateTime::Month month
; // the month
2456 int year
; // and the year
2458 wxString
Format() const
2461 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2463 case 1: which
= "first"; break;
2464 case 2: which
= "second"; break;
2465 case 3: which
= "third"; break;
2466 case 4: which
= "fourth"; break;
2467 case 5: which
= "fifth"; break;
2469 case -1: which
= "last"; break;
2474 which
+= " from end";
2477 s
.Printf("The %s %s of %s in %d",
2479 wxDateTime::GetWeekDayName(wday
).c_str(),
2480 wxDateTime::GetMonthName(month
).c_str(),
2487 // the array data was generated by the following python program
2489 from DateTime import *
2490 from whrandom import *
2491 from string import *
2493 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2494 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2496 week = DateTimeDelta(7)
2499 year = randint(1900, 2100)
2500 month = randint(1, 12)
2501 day = randint(1, 28)
2502 dt = DateTime(year, month, day)
2503 wday = dt.day_of_week
2505 countFromEnd = choice([-1, 1])
2508 while dt.month is month:
2509 dt = dt - countFromEnd * week
2510 weekNum = weekNum + countFromEnd
2512 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2514 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2515 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2518 static const WeekDateTestData weekDatesTestData
[] =
2520 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2521 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2522 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2523 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2524 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2525 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2526 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2527 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2528 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2529 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2530 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2531 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2532 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2533 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2534 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2535 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2536 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2537 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2538 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2539 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2542 static const char *fmt
= "%d-%b-%Y";
2545 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2547 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2549 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2551 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2553 const Date
& d
= wd
.date
;
2554 if ( d
.SameDay(dt
.GetTm()) )
2560 dt
.Set(d
.day
, d
.month
, d
.year
);
2562 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2567 // test the computation of (ISO) week numbers
2568 static void TestTimeWNumber()
2570 puts("\n*** wxDateTime week number test ***");
2572 struct WeekNumberTestData
2574 Date date
; // the date
2575 wxDateTime::wxDateTime_t week
; // the week number in the year
2576 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2577 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2578 wxDateTime::wxDateTime_t dnum
; // day number in the year
2581 // data generated with the following python script:
2583 from DateTime import *
2584 from whrandom import *
2585 from string import *
2587 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2588 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2590 def GetMonthWeek(dt):
2591 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2592 if weekNumMonth < 0:
2593 weekNumMonth = weekNumMonth + 53
2596 def GetLastSundayBefore(dt):
2597 if dt.iso_week[2] == 7:
2600 return dt - DateTimeDelta(dt.iso_week[2])
2603 year = randint(1900, 2100)
2604 month = randint(1, 12)
2605 day = randint(1, 28)
2606 dt = DateTime(year, month, day)
2607 dayNum = dt.day_of_year
2608 weekNum = dt.iso_week[1]
2609 weekNumMonth = GetMonthWeek(dt)
2612 dtSunday = GetLastSundayBefore(dt)
2614 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2615 weekNumMonth2 = weekNumMonth2 + 1
2616 dtSunday = dtSunday - DateTimeDelta(7)
2618 data = { 'day': rjust(`day`, 2), \
2619 'month': monthNames[month - 1], \
2621 'weekNum': rjust(`weekNum`, 2), \
2622 'weekNumMonth': weekNumMonth, \
2623 'weekNumMonth2': weekNumMonth2, \
2624 'dayNum': rjust(`dayNum`, 3) }
2626 print " { { %(day)s, "\
2627 "wxDateTime::%(month)s, "\
2630 "%(weekNumMonth)s, "\
2631 "%(weekNumMonth2)s, "\
2632 "%(dayNum)s }," % data
2635 static const WeekNumberTestData weekNumberTestDates
[] =
2637 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2638 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2639 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2640 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2641 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2642 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2643 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2644 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2645 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2646 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2647 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2648 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2649 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2650 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2651 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2652 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2653 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2654 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2655 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2656 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2659 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2661 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2662 const Date
& d
= wn
.date
;
2664 wxDateTime dt
= d
.DT();
2666 wxDateTime::wxDateTime_t
2667 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2668 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2669 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2670 dnum
= dt
.GetDayOfYear();
2672 printf("%s: the day number is %d",
2673 d
.FormatDate().c_str(), dnum
);
2674 if ( dnum
== wn
.dnum
)
2680 printf(" (ERROR: should be %d)", wn
.dnum
);
2683 printf(", week in month is %d", wmon
);
2684 if ( wmon
== wn
.wmon
)
2690 printf(" (ERROR: should be %d)", wn
.wmon
);
2693 printf(" or %d", wmon2
);
2694 if ( wmon2
== wn
.wmon2
)
2700 printf(" (ERROR: should be %d)", wn
.wmon2
);
2703 printf(", week in year is %d", week
);
2704 if ( week
== wn
.week
)
2710 printf(" (ERROR: should be %d)\n", wn
.week
);
2715 // test DST calculations
2716 static void TestTimeDST()
2718 puts("\n*** wxDateTime DST test ***");
2720 printf("DST is%s in effect now.\n\n",
2721 wxDateTime::Now().IsDST() ? "" : " not");
2723 // taken from http://www.energy.ca.gov/daylightsaving.html
2724 static const Date datesDST
[2][2004 - 1900 + 1] =
2727 { 1, wxDateTime::Apr
, 1990 },
2728 { 7, wxDateTime::Apr
, 1991 },
2729 { 5, wxDateTime::Apr
, 1992 },
2730 { 4, wxDateTime::Apr
, 1993 },
2731 { 3, wxDateTime::Apr
, 1994 },
2732 { 2, wxDateTime::Apr
, 1995 },
2733 { 7, wxDateTime::Apr
, 1996 },
2734 { 6, wxDateTime::Apr
, 1997 },
2735 { 5, wxDateTime::Apr
, 1998 },
2736 { 4, wxDateTime::Apr
, 1999 },
2737 { 2, wxDateTime::Apr
, 2000 },
2738 { 1, wxDateTime::Apr
, 2001 },
2739 { 7, wxDateTime::Apr
, 2002 },
2740 { 6, wxDateTime::Apr
, 2003 },
2741 { 4, wxDateTime::Apr
, 2004 },
2744 { 28, wxDateTime::Oct
, 1990 },
2745 { 27, wxDateTime::Oct
, 1991 },
2746 { 25, wxDateTime::Oct
, 1992 },
2747 { 31, wxDateTime::Oct
, 1993 },
2748 { 30, wxDateTime::Oct
, 1994 },
2749 { 29, wxDateTime::Oct
, 1995 },
2750 { 27, wxDateTime::Oct
, 1996 },
2751 { 26, wxDateTime::Oct
, 1997 },
2752 { 25, wxDateTime::Oct
, 1998 },
2753 { 31, wxDateTime::Oct
, 1999 },
2754 { 29, wxDateTime::Oct
, 2000 },
2755 { 28, wxDateTime::Oct
, 2001 },
2756 { 27, wxDateTime::Oct
, 2002 },
2757 { 26, wxDateTime::Oct
, 2003 },
2758 { 31, wxDateTime::Oct
, 2004 },
2763 for ( year
= 1990; year
< 2005; year
++ )
2765 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2766 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2768 printf("DST period in the US for year %d: from %s to %s",
2769 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2771 size_t n
= year
- 1990;
2772 const Date
& dBegin
= datesDST
[0][n
];
2773 const Date
& dEnd
= datesDST
[1][n
];
2775 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2781 printf(" (ERROR: should be %s %d to %s %d)\n",
2782 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2783 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2789 for ( year
= 1990; year
< 2005; year
++ )
2791 printf("DST period in Europe for year %d: from %s to %s\n",
2793 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2794 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2798 // test wxDateTime -> text conversion
2799 static void TestTimeFormat()
2801 puts("\n*** wxDateTime formatting test ***");
2803 // some information may be lost during conversion, so store what kind
2804 // of info should we recover after a round trip
2807 CompareNone
, // don't try comparing
2808 CompareBoth
, // dates and times should be identical
2809 CompareDate
, // dates only
2810 CompareTime
// time only
2815 CompareKind compareKind
;
2817 } formatTestFormats
[] =
2819 { CompareBoth
, "---> %c" },
2820 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2821 { CompareBoth
, "Date is %x, time is %X" },
2822 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2823 { CompareNone
, "The day of year: %j, the week of year: %W" },
2824 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2827 static const Date formatTestDates
[] =
2829 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2830 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2832 // this test can't work for other centuries because it uses two digit
2833 // years in formats, so don't even try it
2834 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2835 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2836 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2840 // an extra test (as it doesn't depend on date, don't do it in the loop)
2841 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2843 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2847 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2848 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2850 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2851 printf("%s", s
.c_str());
2853 // what can we recover?
2854 int kind
= formatTestFormats
[n
].compareKind
;
2858 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2861 // converion failed - should it have?
2862 if ( kind
== CompareNone
)
2865 puts(" (ERROR: conversion back failed)");
2869 // should have parsed the entire string
2870 puts(" (ERROR: conversion back stopped too soon)");
2874 bool equal
= FALSE
; // suppress compilaer warning
2882 equal
= dt
.IsSameDate(dt2
);
2886 equal
= dt
.IsSameTime(dt2
);
2892 printf(" (ERROR: got back '%s' instead of '%s')\n",
2893 dt2
.Format().c_str(), dt
.Format().c_str());
2904 // test text -> wxDateTime conversion
2905 static void TestTimeParse()
2907 puts("\n*** wxDateTime parse test ***");
2909 struct ParseTestData
2916 static const ParseTestData parseTestDates
[] =
2918 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
2919 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
2922 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
2924 const char *format
= parseTestDates
[n
].format
;
2926 printf("%s => ", format
);
2929 if ( dt
.ParseRfc822Date(format
) )
2931 printf("%s ", dt
.Format().c_str());
2933 if ( parseTestDates
[n
].good
)
2935 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
2942 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
2947 puts("(ERROR: bad format)");
2952 printf("bad format (%s)\n",
2953 parseTestDates
[n
].good
? "ERROR" : "ok");
2958 static void TestInteractive()
2960 puts("\n*** interactive wxDateTime tests ***");
2966 printf("Enter a date: ");
2967 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2970 // kill the last '\n'
2971 buf
[strlen(buf
) - 1] = 0;
2974 const char *p
= dt
.ParseDate(buf
);
2977 printf("ERROR: failed to parse the date '%s'.\n", buf
);
2983 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
2986 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2987 dt
.Format("%b %d, %Y").c_str(),
2989 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2990 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2991 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
2994 puts("\n*** done ***");
2997 static void TestTimeMS()
2999 puts("*** testing millisecond-resolution support in wxDateTime ***");
3001 wxDateTime dt1
= wxDateTime::Now(),
3002 dt2
= wxDateTime::UNow();
3004 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3005 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3006 printf("Dummy loop: ");
3007 for ( int i
= 0; i
< 6000; i
++ )
3009 //for ( int j = 0; j < 10; j++ )
3012 s
.Printf("%g", sqrt(i
));
3021 dt2
= wxDateTime::UNow();
3022 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3024 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3026 puts("\n*** done ***");
3029 static void TestTimeArithmetics()
3031 puts("\n*** testing arithmetic operations on wxDateTime ***");
3033 static const struct ArithmData
3035 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3036 : span(sp
), name(nam
) { }
3040 } testArithmData
[] =
3042 ArithmData(wxDateSpan::Day(), "day"),
3043 ArithmData(wxDateSpan::Week(), "week"),
3044 ArithmData(wxDateSpan::Month(), "month"),
3045 ArithmData(wxDateSpan::Year(), "year"),
3046 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3049 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3051 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3053 wxDateSpan span
= testArithmData
[n
].span
;
3057 const char *name
= testArithmData
[n
].name
;
3058 printf("%s + %s = %s, %s - %s = %s\n",
3059 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3060 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3062 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3063 if ( dt1
- span
== dt
)
3069 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3072 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3073 if ( dt2
+ span
== dt
)
3079 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3082 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3083 if ( dt2
+ 2*span
== dt1
)
3089 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3096 static void TestTimeHolidays()
3098 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3100 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3101 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3102 dtEnd
= dtStart
.GetLastMonthDay();
3104 wxDateTimeArray hol
;
3105 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3107 const wxChar
*format
= "%d-%b-%Y (%a)";
3109 printf("All holidays between %s and %s:\n",
3110 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3112 size_t count
= hol
.GetCount();
3113 for ( size_t n
= 0; n
< count
; n
++ )
3115 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3121 static void TestTimeZoneBug()
3123 puts("\n*** testing for DST/timezone bug ***\n");
3125 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3126 for ( int i
= 0; i
< 31; i
++ )
3128 printf("Date %s: week day %s.\n",
3129 date
.Format(_T("%d-%m-%Y")).c_str(),
3130 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3132 date
+= wxDateSpan::Day();
3140 // test compatibility with the old wxDate/wxTime classes
3141 static void TestTimeCompatibility()
3143 puts("\n*** wxDateTime compatibility test ***");
3145 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3146 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3148 double jdnNow
= wxDateTime::Now().GetJDN();
3149 long jdnMidnight
= (long)(jdnNow
- 0.5);
3150 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3152 jdnMidnight
= wxDate().Set().GetJulianDate();
3153 printf("wxDateTime for today: %s\n",
3154 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3156 int flags
= wxEUROPEAN
;//wxFULL;
3159 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3160 for ( int n
= 0; n
< 7; n
++ )
3162 printf("Previous %s is %s\n",
3163 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3164 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3170 #endif // TEST_DATETIME
3172 // ----------------------------------------------------------------------------
3174 // ----------------------------------------------------------------------------
3178 #include <wx/thread.h>
3180 static size_t gs_counter
= (size_t)-1;
3181 static wxCriticalSection gs_critsect
;
3182 static wxCondition gs_cond
;
3184 class MyJoinableThread
: public wxThread
3187 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3188 { m_n
= n
; Create(); }
3190 // thread execution starts here
3191 virtual ExitCode
Entry();
3197 wxThread::ExitCode
MyJoinableThread::Entry()
3199 unsigned long res
= 1;
3200 for ( size_t n
= 1; n
< m_n
; n
++ )
3204 // it's a loooong calculation :-)
3208 return (ExitCode
)res
;
3211 class MyDetachedThread
: public wxThread
3214 MyDetachedThread(size_t n
, char ch
)
3218 m_cancelled
= FALSE
;
3223 // thread execution starts here
3224 virtual ExitCode
Entry();
3227 virtual void OnExit();
3230 size_t m_n
; // number of characters to write
3231 char m_ch
; // character to write
3233 bool m_cancelled
; // FALSE if we exit normally
3236 wxThread::ExitCode
MyDetachedThread::Entry()
3239 wxCriticalSectionLocker
lock(gs_critsect
);
3240 if ( gs_counter
== (size_t)-1 )
3246 for ( size_t n
= 0; n
< m_n
; n
++ )
3248 if ( TestDestroy() )
3258 wxThread::Sleep(100);
3264 void MyDetachedThread::OnExit()
3266 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3268 wxCriticalSectionLocker
lock(gs_critsect
);
3269 if ( !--gs_counter
&& !m_cancelled
)
3273 void TestDetachedThreads()
3275 puts("\n*** Testing detached threads ***");
3277 static const size_t nThreads
= 3;
3278 MyDetachedThread
*threads
[nThreads
];
3280 for ( n
= 0; n
< nThreads
; n
++ )
3282 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3285 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3286 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3288 for ( n
= 0; n
< nThreads
; n
++ )
3293 // wait until all threads terminate
3299 void TestJoinableThreads()
3301 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3303 // calc 10! in the background
3304 MyJoinableThread
thread(10);
3307 printf("\nThread terminated with exit code %lu.\n",
3308 (unsigned long)thread
.Wait());
3311 void TestThreadSuspend()
3313 puts("\n*** Testing thread suspend/resume functions ***");
3315 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3319 // this is for this demo only, in a real life program we'd use another
3320 // condition variable which would be signaled from wxThread::Entry() to
3321 // tell us that the thread really started running - but here just wait a
3322 // bit and hope that it will be enough (the problem is, of course, that
3323 // the thread might still not run when we call Pause() which will result
3325 wxThread::Sleep(300);
3327 for ( size_t n
= 0; n
< 3; n
++ )
3331 puts("\nThread suspended");
3334 // don't sleep but resume immediately the first time
3335 wxThread::Sleep(300);
3337 puts("Going to resume the thread");
3342 puts("Waiting until it terminates now");
3344 // wait until the thread terminates
3350 void TestThreadDelete()
3352 // As above, using Sleep() is only for testing here - we must use some
3353 // synchronisation object instead to ensure that the thread is still
3354 // running when we delete it - deleting a detached thread which already
3355 // terminated will lead to a crash!
3357 puts("\n*** Testing thread delete function ***");
3359 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3363 puts("\nDeleted a thread which didn't start to run yet.");
3365 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3369 wxThread::Sleep(300);
3373 puts("\nDeleted a running thread.");
3375 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3379 wxThread::Sleep(300);
3385 puts("\nDeleted a sleeping thread.");
3387 MyJoinableThread
thread3(20);
3392 puts("\nDeleted a joinable thread.");
3394 MyJoinableThread
thread4(2);
3397 wxThread::Sleep(300);
3401 puts("\nDeleted a joinable thread which already terminated.");
3406 #endif // TEST_THREADS
3408 // ----------------------------------------------------------------------------
3410 // ----------------------------------------------------------------------------
3414 static void PrintArray(const char* name
, const wxArrayString
& array
)
3416 printf("Dump of the array '%s'\n", name
);
3418 size_t nCount
= array
.GetCount();
3419 for ( size_t n
= 0; n
< nCount
; n
++ )
3421 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3425 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3427 printf("Dump of the array '%s'\n", name
);
3429 size_t nCount
= array
.GetCount();
3430 for ( size_t n
= 0; n
< nCount
; n
++ )
3432 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3436 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3437 const wxString
& second
)
3439 return first
.length() - second
.length();
3442 int wxCMPFUNC_CONV
IntCompare(int *first
,
3445 return *first
- *second
;
3448 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3451 return *second
- *first
;
3454 static void TestArrayOfInts()
3456 puts("*** Testing wxArrayInt ***\n");
3467 puts("After sort:");
3471 puts("After reverse sort:");
3472 a
.Sort(IntRevCompare
);
3476 #include "wx/dynarray.h"
3478 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3479 #include "wx/arrimpl.cpp"
3480 WX_DEFINE_OBJARRAY(ArrayBars
);
3482 static void TestArrayOfObjects()
3484 puts("*** Testing wxObjArray ***\n");
3488 Bar
bar("second bar");
3490 printf("Initially: %u objects in the array, %u objects total.\n",
3491 bars
.GetCount(), Bar::GetNumber());
3493 bars
.Add(new Bar("first bar"));
3496 printf("Now: %u objects in the array, %u objects total.\n",
3497 bars
.GetCount(), Bar::GetNumber());
3501 printf("After Empty(): %u objects in the array, %u objects total.\n",
3502 bars
.GetCount(), Bar::GetNumber());
3505 printf("Finally: no more objects in the array, %u objects total.\n",
3509 #endif // TEST_ARRAYS
3511 // ----------------------------------------------------------------------------
3513 // ----------------------------------------------------------------------------
3517 #include "wx/timer.h"
3518 #include "wx/tokenzr.h"
3520 static void TestStringConstruction()
3522 puts("*** Testing wxString constructores ***");
3524 #define TEST_CTOR(args, res) \
3527 printf("wxString%s = %s ", #args, s.c_str()); \
3534 printf("(ERROR: should be %s)\n", res); \
3538 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3539 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3540 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3541 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3543 static const wxChar
*s
= _T("?really!");
3544 const wxChar
*start
= wxStrchr(s
, _T('r'));
3545 const wxChar
*end
= wxStrchr(s
, _T('!'));
3546 TEST_CTOR((start
, end
), _T("really"));
3551 static void TestString()
3561 for (int i
= 0; i
< 1000000; ++i
)
3565 c
= "! How'ya doin'?";
3568 c
= "Hello world! What's up?";
3573 printf ("TestString elapsed time: %ld\n", sw
.Time());
3576 static void TestPChar()
3584 for (int i
= 0; i
< 1000000; ++i
)
3586 strcpy (a
, "Hello");
3587 strcpy (b
, " world");
3588 strcpy (c
, "! How'ya doin'?");
3591 strcpy (c
, "Hello world! What's up?");
3592 if (strcmp (c
, a
) == 0)
3596 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3599 static void TestStringSub()
3601 wxString
s("Hello, world!");
3603 puts("*** Testing wxString substring extraction ***");
3605 printf("String = '%s'\n", s
.c_str());
3606 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3607 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3608 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3609 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3610 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3611 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3613 static const wxChar
*prefixes
[] =
3617 _T("Hello, world!"),
3618 _T("Hello, world!!!"),
3624 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3626 wxString prefix
= prefixes
[n
], rest
;
3627 bool rc
= s
.StartsWith(prefix
, &rest
);
3628 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3631 printf(" (the rest is '%s')\n", rest
.c_str());
3642 static void TestStringFormat()
3644 puts("*** Testing wxString formatting ***");
3647 s
.Printf("%03d", 18);
3649 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3650 printf("Number 18: %s\n", s
.c_str());
3655 // returns "not found" for npos, value for all others
3656 static wxString
PosToString(size_t res
)
3658 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3659 : wxString::Format(_T("%u"), res
);
3663 static void TestStringFind()
3665 puts("*** Testing wxString find() functions ***");
3667 static const wxChar
*strToFind
= _T("ell");
3668 static const struct StringFindTest
3672 result
; // of searching "ell" in str
3675 { _T("Well, hello world"), 0, 1 },
3676 { _T("Well, hello world"), 6, 7 },
3677 { _T("Well, hello world"), 9, wxString::npos
},
3680 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3682 const StringFindTest
& ft
= findTestData
[n
];
3683 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3685 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3686 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3688 size_t resTrue
= ft
.result
;
3689 if ( res
== resTrue
)
3695 printf(_T("(ERROR: should be %s)\n"),
3696 PosToString(resTrue
).c_str());
3703 static void TestStringTokenizer()
3705 puts("*** Testing wxStringTokenizer ***");
3707 static const wxChar
*modeNames
[] =
3711 _T("return all empty"),
3716 static const struct StringTokenizerTest
3718 const wxChar
*str
; // string to tokenize
3719 const wxChar
*delims
; // delimiters to use
3720 size_t count
; // count of token
3721 wxStringTokenizerMode mode
; // how should we tokenize it
3722 } tokenizerTestData
[] =
3724 { _T(""), _T(" "), 0 },
3725 { _T("Hello, world"), _T(" "), 2 },
3726 { _T("Hello, world "), _T(" "), 2 },
3727 { _T("Hello, world"), _T(","), 2 },
3728 { _T("Hello, world!"), _T(",!"), 2 },
3729 { _T("Hello,, world!"), _T(",!"), 3 },
3730 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3731 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3732 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3733 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3734 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3735 { _T("01/02/99"), _T("/-"), 3 },
3736 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3739 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3741 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3742 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3744 size_t count
= tkz
.CountTokens();
3745 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3746 MakePrintable(tt
.str
).c_str(),
3748 MakePrintable(tt
.delims
).c_str(),
3749 modeNames
[tkz
.GetMode()]);
3750 if ( count
== tt
.count
)
3756 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3761 // if we emulate strtok(), check that we do it correctly
3762 wxChar
*buf
, *s
= NULL
, *last
;
3764 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3766 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3767 wxStrcpy(buf
, tt
.str
);
3769 s
= wxStrtok(buf
, tt
.delims
, &last
);
3776 // now show the tokens themselves
3778 while ( tkz
.HasMoreTokens() )
3780 wxString token
= tkz
.GetNextToken();
3782 printf(_T("\ttoken %u: '%s'"),
3784 MakePrintable(token
).c_str());
3794 printf(" (ERROR: should be %s)\n", s
);
3797 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3801 // nothing to compare with
3806 if ( count2
!= count
)
3808 puts(_T("\tERROR: token count mismatch"));
3817 static void TestStringReplace()
3819 puts("*** Testing wxString::replace ***");
3821 static const struct StringReplaceTestData
3823 const wxChar
*original
; // original test string
3824 size_t start
, len
; // the part to replace
3825 const wxChar
*replacement
; // the replacement string
3826 const wxChar
*result
; // and the expected result
3827 } stringReplaceTestData
[] =
3829 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3830 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3831 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3832 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3833 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3836 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3838 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3840 wxString original
= data
.original
;
3841 original
.replace(data
.start
, data
.len
, data
.replacement
);
3843 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3844 data
.original
, data
.start
, data
.len
, data
.replacement
,
3847 if ( original
== data
.result
)
3853 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3860 #endif // TEST_STRINGS
3862 // ----------------------------------------------------------------------------
3864 // ----------------------------------------------------------------------------
3866 int main(int argc
, char **argv
)
3868 if ( !wxInitialize() )
3870 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3874 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3876 #endif // TEST_USLEEP
3879 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3881 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3882 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3884 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3885 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3886 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3887 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3889 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
3890 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
3895 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
3897 parser
.AddOption("project_name", "", "full path to project file",
3898 wxCMD_LINE_VAL_STRING
,
3899 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
3901 switch ( parser
.Parse() )
3904 wxLogMessage("Help was given, terminating.");
3908 ShowCmdLine(parser
);
3912 wxLogMessage("Syntax error detected, aborting.");
3915 #endif // TEST_CMDLINE
3926 TestStringConstruction();
3929 TestStringTokenizer();
3930 TestStringReplace();
3932 #endif // TEST_STRINGS
3945 puts("*** Initially:");
3947 PrintArray("a1", a1
);
3949 wxArrayString
a2(a1
);
3950 PrintArray("a2", a2
);
3952 wxSortedArrayString
a3(a1
);
3953 PrintArray("a3", a3
);
3955 puts("*** After deleting a string from a1");
3958 PrintArray("a1", a1
);
3959 PrintArray("a2", a2
);
3960 PrintArray("a3", a3
);
3962 puts("*** After reassigning a1 to a2 and a3");
3964 PrintArray("a2", a2
);
3965 PrintArray("a3", a3
);
3967 puts("*** After sorting a1");
3969 PrintArray("a1", a1
);
3971 puts("*** After sorting a1 in reverse order");
3973 PrintArray("a1", a1
);
3975 puts("*** After sorting a1 by the string length");
3976 a1
.Sort(StringLenCompare
);
3977 PrintArray("a1", a1
);
3979 TestArrayOfObjects();
3982 #endif // TEST_ARRAYS
3988 #ifdef TEST_DLLLOADER
3990 #endif // TEST_DLLLOADER
3994 #endif // TEST_ENVIRON
3998 #endif // TEST_EXECUTE
4000 #ifdef TEST_FILECONF
4002 #endif // TEST_FILECONF
4010 for ( size_t n
= 0; n
< 8000; n
++ )
4012 s
<< (char)('A' + (n
% 26));
4016 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4018 // this one shouldn't be truncated
4021 // but this one will because log functions use fixed size buffer
4022 // (note that it doesn't need '\n' at the end neither - will be added
4024 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4036 #ifdef TEST_FILENAME
4037 TestFileNameSplit();
4040 TestFileNameConstruction();
4042 TestFileNameComparison();
4043 TestFileNameOperations();
4045 #endif // TEST_FILENAME
4048 int nCPUs
= wxThread::GetCPUCount();
4049 printf("This system has %d CPUs\n", nCPUs
);
4051 wxThread::SetConcurrency(nCPUs
);
4053 if ( argc
> 1 && argv
[1][0] == 't' )
4054 wxLog::AddTraceMask("thread");
4057 TestDetachedThreads();
4059 TestJoinableThreads();
4061 TestThreadSuspend();
4065 #endif // TEST_THREADS
4067 #ifdef TEST_LONGLONG
4068 // seed pseudo random generator
4069 srand((unsigned)time(NULL
));
4077 TestMultiplication();
4080 TestLongLongConversion();
4081 TestBitOperations();
4083 TestLongLongComparison();
4084 #endif // TEST_LONGLONG
4091 wxLog::AddTraceMask(_T("mime"));
4098 TestMimeAssociate();
4101 #ifdef TEST_INFO_FUNCTIONS
4104 #endif // TEST_INFO_FUNCTIONS
4106 #ifdef TEST_REGISTRY
4109 TestRegistryAssociation();
4110 #endif // TEST_REGISTRY
4118 #endif // TEST_SOCKETS
4121 wxLog::AddTraceMask(_T("ftp"));
4124 TestProtocolFtpUpload();
4129 #endif // TEST_STREAMS
4133 #endif // TEST_TIMER
4135 #ifdef TEST_DATETIME
4148 TestTimeArithmetics();
4157 #endif // TEST_DATETIME
4163 #endif // TEST_VCARD
4167 #endif // TEST_WCHAR
4170 TestZipStreamRead();
4175 TestZlibStreamWrite();
4176 TestZlibStreamRead();