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
47 //#define TEST_FILENAME
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 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
818 wxArrayString mimetypes
;
820 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
822 printf("*** All %u known filetypes: ***\n", count
);
827 for ( size_t n
= 0; n
< count
; n
++ )
829 wxFileType
*filetype
= g_mimeManager
.GetFileTypeFromMimeType(mimetypes
[n
]);
832 printf("nothing known about the filetype '%s'!\n",
833 mimetypes
[n
].c_str());
837 filetype
->GetDescription(&desc
);
838 filetype
->GetExtensions(exts
);
840 filetype
->GetIcon(NULL
);
843 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
850 printf("\t%s: %s (%s)\n",
851 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
855 static void TestMimeOverride()
857 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
859 wxString mailcap
= _T("/tmp/mailcap"),
860 mimetypes
= _T("/tmp/mime.types");
862 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
864 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
865 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
867 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
870 static void TestMimeFilename()
872 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
874 static const wxChar
*filenames
[] =
881 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
883 const wxString fname
= filenames
[n
];
884 wxString ext
= fname
.AfterLast(_T('.'));
885 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
888 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
893 if ( !ft
->GetDescription(&desc
) )
894 desc
= _T("<no description>");
897 if ( !ft
->GetOpenCommand(&cmd
,
898 wxFileType::MessageParameters(fname
, _T(""))) )
899 cmd
= _T("<no command available>");
901 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
902 fname
.c_str(), desc
.c_str(), cmd
.c_str());
909 static void TestMimeAssociate()
911 wxPuts(_T("*** Testing creation of filetype association ***\n"));
913 wxFileTypeInfo
ftInfo(
914 _T("application/x-xyz"),
915 _T("xyzview '%s'"), // open cmd
917 _T("XYZ File") // description
918 _T(".xyz"), // extensions
919 NULL
// end of extensions
921 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
923 wxFileType
*ft
= g_mimeManager
.Associate(ftInfo
);
926 wxPuts(_T("ERROR: failed to create association!"));
930 // TODO: read it back
937 // ----------------------------------------------------------------------------
938 // misc information functions
939 // ----------------------------------------------------------------------------
941 #ifdef TEST_INFO_FUNCTIONS
943 #include <wx/utils.h>
945 static void TestOsInfo()
947 puts("*** Testing OS info functions ***\n");
950 wxGetOsVersion(&major
, &minor
);
951 printf("Running under: %s, version %d.%d\n",
952 wxGetOsDescription().c_str(), major
, minor
);
954 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
956 printf("Host name is %s (%s).\n",
957 wxGetHostName().c_str(), wxGetFullHostName().c_str());
962 static void TestUserInfo()
964 puts("*** Testing user info functions ***\n");
966 printf("User id is:\t%s\n", wxGetUserId().c_str());
967 printf("User name is:\t%s\n", wxGetUserName().c_str());
968 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
969 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
974 #endif // TEST_INFO_FUNCTIONS
976 // ----------------------------------------------------------------------------
978 // ----------------------------------------------------------------------------
982 #include <wx/longlong.h>
983 #include <wx/timer.h>
985 // make a 64 bit number from 4 16 bit ones
986 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
988 // get a random 64 bit number
989 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
991 #if wxUSE_LONGLONG_WX
992 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
993 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
994 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
995 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
996 #endif // wxUSE_LONGLONG_WX
998 static void TestSpeed()
1000 static const long max
= 100000000;
1007 for ( n
= 0; n
< max
; n
++ )
1012 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1015 #if wxUSE_LONGLONG_NATIVE
1020 for ( n
= 0; n
< max
; n
++ )
1025 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1027 #endif // wxUSE_LONGLONG_NATIVE
1033 for ( n
= 0; n
< max
; n
++ )
1038 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1042 static void TestLongLongConversion()
1044 puts("*** Testing wxLongLong conversions ***\n");
1048 for ( size_t n
= 0; n
< 100000; n
++ )
1052 #if wxUSE_LONGLONG_NATIVE
1053 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1055 wxASSERT_MSG( a
== b
, "conversions failure" );
1057 puts("Can't do it without native long long type, test skipped.");
1060 #endif // wxUSE_LONGLONG_NATIVE
1062 if ( !(nTested
% 1000) )
1074 static void TestMultiplication()
1076 puts("*** Testing wxLongLong multiplication ***\n");
1080 for ( size_t n
= 0; n
< 100000; n
++ )
1085 #if wxUSE_LONGLONG_NATIVE
1086 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1087 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1089 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1090 #else // !wxUSE_LONGLONG_NATIVE
1091 puts("Can't do it without native long long type, test skipped.");
1094 #endif // wxUSE_LONGLONG_NATIVE
1096 if ( !(nTested
% 1000) )
1108 static void TestDivision()
1110 puts("*** Testing wxLongLong division ***\n");
1114 for ( size_t n
= 0; n
< 100000; n
++ )
1116 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1117 // multiplication will not overflow)
1118 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1120 // get a random long (not wxLongLong for now) to divide it with
1125 #if wxUSE_LONGLONG_NATIVE
1126 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1128 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1129 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1130 #else // !wxUSE_LONGLONG_NATIVE
1131 // verify the result
1132 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1133 #endif // wxUSE_LONGLONG_NATIVE
1135 if ( !(nTested
% 1000) )
1147 static void TestAddition()
1149 puts("*** Testing wxLongLong addition ***\n");
1153 for ( size_t n
= 0; n
< 100000; n
++ )
1159 #if wxUSE_LONGLONG_NATIVE
1160 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1161 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1162 "addition failure" );
1163 #else // !wxUSE_LONGLONG_NATIVE
1164 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1165 #endif // wxUSE_LONGLONG_NATIVE
1167 if ( !(nTested
% 1000) )
1179 static void TestBitOperations()
1181 puts("*** Testing wxLongLong bit operation ***\n");
1185 for ( size_t n
= 0; n
< 100000; n
++ )
1189 #if wxUSE_LONGLONG_NATIVE
1190 for ( size_t n
= 0; n
< 33; n
++ )
1193 #else // !wxUSE_LONGLONG_NATIVE
1194 puts("Can't do it without native long long type, test skipped.");
1197 #endif // wxUSE_LONGLONG_NATIVE
1199 if ( !(nTested
% 1000) )
1211 static void TestLongLongComparison()
1213 puts("*** Testing wxLongLong comparison ***\n");
1215 static const long testLongs
[] =
1226 static const long ls
[2] =
1232 wxLongLongWx lls
[2];
1236 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1240 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1242 res
= lls
[m
] > testLongs
[n
];
1243 printf("0x%lx > 0x%lx is %s (%s)\n",
1244 ls
[m
], testLongs
[n
], res
? "true" : "false",
1245 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1247 res
= lls
[m
] < testLongs
[n
];
1248 printf("0x%lx < 0x%lx is %s (%s)\n",
1249 ls
[m
], testLongs
[n
], res
? "true" : "false",
1250 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1252 res
= lls
[m
] == testLongs
[n
];
1253 printf("0x%lx == 0x%lx is %s (%s)\n",
1254 ls
[m
], testLongs
[n
], res
? "true" : "false",
1255 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1263 #endif // TEST_LONGLONG
1265 // ----------------------------------------------------------------------------
1267 // ----------------------------------------------------------------------------
1269 // this is for MSW only
1271 #undef TEST_REGISTRY
1274 #ifdef TEST_REGISTRY
1276 #include <wx/msw/registry.h>
1278 // I chose this one because I liked its name, but it probably only exists under
1280 static const wxChar
*TESTKEY
=
1281 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1283 static void TestRegistryRead()
1285 puts("*** testing registry reading ***");
1287 wxRegKey
key(TESTKEY
);
1288 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1291 puts("ERROR: test key can't be opened, aborting test.");
1296 size_t nSubKeys
, nValues
;
1297 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1299 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1302 printf("Enumerating values:\n");
1306 bool cont
= key
.GetFirstValue(value
, dummy
);
1309 printf("Value '%s': type ", value
.c_str());
1310 switch ( key
.GetValueType(value
) )
1312 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1313 case wxRegKey::Type_String
: printf("SZ"); break;
1314 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1315 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1316 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1317 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1318 default: printf("other (unknown)"); break;
1321 printf(", value = ");
1322 if ( key
.IsNumericValue(value
) )
1325 key
.QueryValue(value
, &val
);
1331 key
.QueryValue(value
, val
);
1332 printf("'%s'", val
.c_str());
1334 key
.QueryRawValue(value
, val
);
1335 printf(" (raw value '%s')", val
.c_str());
1340 cont
= key
.GetNextValue(value
, dummy
);
1344 static void TestRegistryAssociation()
1347 The second call to deleteself genertaes an error message, with a
1348 messagebox saying .flo is crucial to system operation, while the .ddf
1349 call also fails, but with no error message
1354 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1356 key
= "ddxf_auto_file" ;
1357 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1359 key
= "ddxf_auto_file" ;
1360 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1363 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1365 key
= "program \"%1\"" ;
1367 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1369 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1371 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1373 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1377 #endif // TEST_REGISTRY
1379 // ----------------------------------------------------------------------------
1381 // ----------------------------------------------------------------------------
1385 #include <wx/socket.h>
1386 #include <wx/protocol/protocol.h>
1387 #include <wx/protocol/http.h>
1389 static void TestSocketServer()
1391 puts("*** Testing wxSocketServer ***\n");
1393 static const int PORT
= 3000;
1398 wxSocketServer
*server
= new wxSocketServer(addr
);
1399 if ( !server
->Ok() )
1401 puts("ERROR: failed to bind");
1408 printf("Server: waiting for connection on port %d...\n", PORT
);
1410 wxSocketBase
*socket
= server
->Accept();
1413 puts("ERROR: wxSocketServer::Accept() failed.");
1417 puts("Server: got a client.");
1419 server
->SetTimeout(60); // 1 min
1421 while ( socket
->IsConnected() )
1427 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1429 // don't log error if the client just close the connection
1430 if ( socket
->IsConnected() )
1432 puts("ERROR: in wxSocket::Read.");
1452 printf("Server: got '%s'.\n", s
.c_str());
1453 if ( s
== _T("bye") )
1460 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1461 socket
->Write("\r\n", 2);
1462 printf("Server: wrote '%s'.\n", s
.c_str());
1465 puts("Server: lost a client.");
1470 // same as "delete server" but is consistent with GUI programs
1474 static void TestSocketClient()
1476 puts("*** Testing wxSocketClient ***\n");
1478 static const char *hostname
= "www.wxwindows.org";
1481 addr
.Hostname(hostname
);
1484 printf("--- Attempting to connect to %s:80...\n", hostname
);
1486 wxSocketClient client
;
1487 if ( !client
.Connect(addr
) )
1489 printf("ERROR: failed to connect to %s\n", hostname
);
1493 printf("--- Connected to %s:%u...\n",
1494 addr
.Hostname().c_str(), addr
.Service());
1498 // could use simply "GET" here I suppose
1500 wxString::Format("GET http://%s/\r\n", hostname
);
1501 client
.Write(cmdGet
, cmdGet
.length());
1502 printf("--- Sent command '%s' to the server\n",
1503 MakePrintable(cmdGet
).c_str());
1504 client
.Read(buf
, WXSIZEOF(buf
));
1505 printf("--- Server replied:\n%s", buf
);
1509 #endif // TEST_SOCKETS
1511 // ----------------------------------------------------------------------------
1513 // ----------------------------------------------------------------------------
1517 #include <wx/protocol/ftp.h>
1521 #define FTP_ANONYMOUS
1523 #ifdef FTP_ANONYMOUS
1524 static const char *directory
= "/pub";
1525 static const char *filename
= "welcome.msg";
1527 static const char *directory
= "/etc";
1528 static const char *filename
= "issue";
1531 static bool TestFtpConnect()
1533 puts("*** Testing FTP connect ***");
1535 #ifdef FTP_ANONYMOUS
1536 static const char *hostname
= "ftp.wxwindows.org";
1538 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1539 #else // !FTP_ANONYMOUS
1540 static const char *hostname
= "localhost";
1543 fgets(user
, WXSIZEOF(user
), stdin
);
1544 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
1548 printf("Password for %s: ", password
);
1549 fgets(password
, WXSIZEOF(password
), stdin
);
1550 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
1551 ftp
.SetPassword(password
);
1553 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1554 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
1556 if ( !ftp
.Connect(hostname
) )
1558 printf("ERROR: failed to connect to %s\n", hostname
);
1564 printf("--- Connected to %s, current directory is '%s'\n",
1565 hostname
, ftp
.Pwd().c_str());
1571 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1572 static void TestFtpWuFtpd()
1575 static const char *hostname
= "ftp.eudora.com";
1576 if ( !ftp
.Connect(hostname
) )
1578 printf("ERROR: failed to connect to %s\n", hostname
);
1582 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1583 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1586 printf("ERROR: couldn't get input stream for %s\n", filename
);
1590 size_t size
= in
->StreamSize();
1591 printf("Reading file %s (%u bytes)...", filename
, size
);
1593 char *data
= new char[size
];
1594 if ( !in
->Read(data
, size
) )
1596 puts("ERROR: read error");
1600 printf("Successfully retrieved the file.\n");
1609 static void TestFtpList()
1611 puts("*** Testing wxFTP file listing ***\n");
1614 if ( !ftp
.ChDir(directory
) )
1616 printf("ERROR: failed to cd to %s\n", directory
);
1619 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1621 // test NLIST and LIST
1622 wxArrayString files
;
1623 if ( !ftp
.GetFilesList(files
) )
1625 puts("ERROR: failed to get NLIST of files");
1629 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1630 size_t count
= files
.GetCount();
1631 for ( size_t n
= 0; n
< count
; n
++ )
1633 printf("\t%s\n", files
[n
].c_str());
1635 puts("End of the file list");
1638 if ( !ftp
.GetDirList(files
) )
1640 puts("ERROR: failed to get LIST of files");
1644 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1645 size_t count
= files
.GetCount();
1646 for ( size_t n
= 0; n
< count
; n
++ )
1648 printf("\t%s\n", files
[n
].c_str());
1650 puts("End of the file list");
1653 if ( !ftp
.ChDir(_T("..")) )
1655 puts("ERROR: failed to cd to ..");
1658 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1661 static void TestFtpDownload()
1663 puts("*** Testing wxFTP download ***\n");
1666 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1669 printf("ERROR: couldn't get input stream for %s\n", filename
);
1673 size_t size
= in
->StreamSize();
1674 printf("Reading file %s (%u bytes)...", filename
, size
);
1677 char *data
= new char[size
];
1678 if ( !in
->Read(data
, size
) )
1680 puts("ERROR: read error");
1684 printf("\nContents of %s:\n%s\n", filename
, data
);
1692 static void TestFtpFileSize()
1694 puts("*** Testing FTP SIZE command ***");
1696 if ( !ftp
.ChDir(directory
) )
1698 printf("ERROR: failed to cd to %s\n", directory
);
1701 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
1703 if ( ftp
.FileExists(filename
) )
1705 int size
= ftp
.GetFileSize(filename
);
1707 printf("ERROR: couldn't get size of '%s'\n", filename
);
1709 printf("Size of '%s' is %d bytes.\n", filename
, size
);
1713 printf("ERROR: '%s' doesn't exist\n", filename
);
1717 static void TestFtpMisc()
1719 puts("*** Testing miscellaneous wxFTP functions ***");
1721 if ( ftp
.SendCommand("STAT") != '2' )
1723 puts("ERROR: STAT failed");
1727 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1730 if ( ftp
.SendCommand("HELP SITE") != '2' )
1732 puts("ERROR: HELP SITE failed");
1736 printf("The list of site-specific commands:\n\n%s\n",
1737 ftp
.GetLastResult().c_str());
1741 static void TestFtpInteractive()
1743 puts("\n*** Interactive wxFTP test ***");
1749 printf("Enter FTP command: ");
1750 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1753 // kill the last '\n'
1754 buf
[strlen(buf
) - 1] = 0;
1756 // special handling of LIST and NLST as they require data connection
1757 wxString
start(buf
, 4);
1759 if ( start
== "LIST" || start
== "NLST" )
1762 if ( strlen(buf
) > 4 )
1765 wxArrayString files
;
1766 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
1768 printf("ERROR: failed to get %s of files\n", start
.c_str());
1772 printf("--- %s of '%s' under '%s':\n",
1773 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
1774 size_t count
= files
.GetCount();
1775 for ( size_t n
= 0; n
< count
; n
++ )
1777 printf("\t%s\n", files
[n
].c_str());
1779 puts("--- End of the file list");
1784 char ch
= ftp
.SendCommand(buf
);
1785 printf("Command %s", ch
? "succeeded" : "failed");
1788 printf(" (return code %c)", ch
);
1791 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
1795 puts("\n*** done ***");
1798 static void TestFtpUpload()
1800 puts("*** Testing wxFTP uploading ***\n");
1803 static const char *file1
= "test1";
1804 static const char *file2
= "test2";
1805 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1808 printf("--- Uploading to %s ---\n", file1
);
1809 out
->Write("First hello", 11);
1813 // send a command to check the remote file
1814 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1816 printf("ERROR: STAT %s failed\n", file1
);
1820 printf("STAT %s returned:\n\n%s\n",
1821 file1
, ftp
.GetLastResult().c_str());
1824 out
= ftp
.GetOutputStream(file2
);
1827 printf("--- Uploading to %s ---\n", file1
);
1828 out
->Write("Second hello", 12);
1835 // ----------------------------------------------------------------------------
1837 // ----------------------------------------------------------------------------
1841 #include <wx/mstream.h>
1843 static void TestMemoryStream()
1845 puts("*** Testing wxMemoryInputStream ***");
1848 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1850 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1851 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1852 while ( !memInpStream
.Eof() )
1854 putchar(memInpStream
.GetC());
1857 puts("\n*** wxMemoryInputStream test done ***");
1860 #endif // TEST_STREAMS
1862 // ----------------------------------------------------------------------------
1864 // ----------------------------------------------------------------------------
1868 #include <wx/timer.h>
1869 #include <wx/utils.h>
1871 static void TestStopWatch()
1873 puts("*** Testing wxStopWatch ***\n");
1876 printf("Sleeping 3 seconds...");
1878 printf("\telapsed time: %ldms\n", sw
.Time());
1881 printf("Sleeping 2 more seconds...");
1883 printf("\telapsed time: %ldms\n", sw
.Time());
1886 printf("And 3 more seconds...");
1888 printf("\telapsed time: %ldms\n", sw
.Time());
1891 puts("\nChecking for 'backwards clock' bug...");
1892 for ( size_t n
= 0; n
< 70; n
++ )
1896 for ( size_t m
= 0; m
< 100000; m
++ )
1898 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1900 puts("\ntime is negative - ERROR!");
1910 #endif // TEST_TIMER
1912 // ----------------------------------------------------------------------------
1914 // ----------------------------------------------------------------------------
1918 #include <wx/vcard.h>
1920 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1923 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1927 wxString(_T('\t'), level
).c_str(),
1928 vcObj
->GetName().c_str());
1931 switch ( vcObj
->GetType() )
1933 case wxVCardObject::String
:
1934 case wxVCardObject::UString
:
1937 vcObj
->GetValue(&val
);
1938 value
<< _T('"') << val
<< _T('"');
1942 case wxVCardObject::Int
:
1945 vcObj
->GetValue(&i
);
1946 value
.Printf(_T("%u"), i
);
1950 case wxVCardObject::Long
:
1953 vcObj
->GetValue(&l
);
1954 value
.Printf(_T("%lu"), l
);
1958 case wxVCardObject::None
:
1961 case wxVCardObject::Object
:
1962 value
= _T("<node>");
1966 value
= _T("<unknown value type>");
1970 printf(" = %s", value
.c_str());
1973 DumpVObject(level
+ 1, *vcObj
);
1976 vcObj
= vcard
.GetNextProp(&cookie
);
1980 static void DumpVCardAddresses(const wxVCard
& vcard
)
1982 puts("\nShowing all addresses from vCard:\n");
1986 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1990 int flags
= addr
->GetFlags();
1991 if ( flags
& wxVCardAddress::Domestic
)
1993 flagsStr
<< _T("domestic ");
1995 if ( flags
& wxVCardAddress::Intl
)
1997 flagsStr
<< _T("international ");
1999 if ( flags
& wxVCardAddress::Postal
)
2001 flagsStr
<< _T("postal ");
2003 if ( flags
& wxVCardAddress::Parcel
)
2005 flagsStr
<< _T("parcel ");
2007 if ( flags
& wxVCardAddress::Home
)
2009 flagsStr
<< _T("home ");
2011 if ( flags
& wxVCardAddress::Work
)
2013 flagsStr
<< _T("work ");
2016 printf("Address %u:\n"
2018 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2021 addr
->GetPostOffice().c_str(),
2022 addr
->GetExtAddress().c_str(),
2023 addr
->GetStreet().c_str(),
2024 addr
->GetLocality().c_str(),
2025 addr
->GetRegion().c_str(),
2026 addr
->GetPostalCode().c_str(),
2027 addr
->GetCountry().c_str()
2031 addr
= vcard
.GetNextAddress(&cookie
);
2035 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2037 puts("\nShowing all phone numbers from vCard:\n");
2041 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2045 int flags
= phone
->GetFlags();
2046 if ( flags
& wxVCardPhoneNumber::Voice
)
2048 flagsStr
<< _T("voice ");
2050 if ( flags
& wxVCardPhoneNumber::Fax
)
2052 flagsStr
<< _T("fax ");
2054 if ( flags
& wxVCardPhoneNumber::Cellular
)
2056 flagsStr
<< _T("cellular ");
2058 if ( flags
& wxVCardPhoneNumber::Modem
)
2060 flagsStr
<< _T("modem ");
2062 if ( flags
& wxVCardPhoneNumber::Home
)
2064 flagsStr
<< _T("home ");
2066 if ( flags
& wxVCardPhoneNumber::Work
)
2068 flagsStr
<< _T("work ");
2071 printf("Phone number %u:\n"
2076 phone
->GetNumber().c_str()
2080 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2084 static void TestVCardRead()
2086 puts("*** Testing wxVCard reading ***\n");
2088 wxVCard
vcard(_T("vcard.vcf"));
2089 if ( !vcard
.IsOk() )
2091 puts("ERROR: couldn't load vCard.");
2095 // read individual vCard properties
2096 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2100 vcObj
->GetValue(&value
);
2105 value
= _T("<none>");
2108 printf("Full name retrieved directly: %s\n", value
.c_str());
2111 if ( !vcard
.GetFullName(&value
) )
2113 value
= _T("<none>");
2116 printf("Full name from wxVCard API: %s\n", value
.c_str());
2118 // now show how to deal with multiply occuring properties
2119 DumpVCardAddresses(vcard
);
2120 DumpVCardPhoneNumbers(vcard
);
2122 // and finally show all
2123 puts("\nNow dumping the entire vCard:\n"
2124 "-----------------------------\n");
2126 DumpVObject(0, vcard
);
2130 static void TestVCardWrite()
2132 puts("*** Testing wxVCard writing ***\n");
2135 if ( !vcard
.IsOk() )
2137 puts("ERROR: couldn't create vCard.");
2142 vcard
.SetName("Zeitlin", "Vadim");
2143 vcard
.SetFullName("Vadim Zeitlin");
2144 vcard
.SetOrganization("wxWindows", "R&D");
2146 // just dump the vCard back
2147 puts("Entire vCard follows:\n");
2148 puts(vcard
.Write());
2152 #endif // TEST_VCARD
2154 // ----------------------------------------------------------------------------
2155 // wide char (Unicode) support
2156 // ----------------------------------------------------------------------------
2160 #include <wx/strconv.h>
2161 #include <wx/buffer.h>
2163 static void TestUtf8()
2165 puts("*** Testing UTF8 support ***\n");
2167 wxString testString
= "français";
2169 "************ French - Français ****************"
2170 "Juste un petit exemple pour dire que les français aussi"
2171 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
2174 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
2175 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
2176 wxString
testString2(pwz
, wxConvLocal
);
2178 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
2180 char *psz
= "fran" "\xe7" "ais";
2181 size_t len
= strlen(psz
);
2182 wchar_t *pwz2
= new wchar_t[len
+ 1];
2183 for ( size_t n
= 0; n
<= len
; n
++ )
2185 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
2188 wxString
testString3(pwz2
, wxConvUTF8
);
2191 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
2194 #endif // TEST_WCHAR
2196 // ----------------------------------------------------------------------------
2198 // ----------------------------------------------------------------------------
2202 #include "wx/zipstrm.h"
2204 static void TestZipStreamRead()
2206 puts("*** Testing ZIP reading ***\n");
2208 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
2209 printf("Archive size: %u\n", istr
.GetSize());
2211 puts("Dumping the file:");
2212 while ( !istr
.Eof() )
2214 putchar(istr
.GetC());
2218 puts("\n----- done ------");
2223 // ----------------------------------------------------------------------------
2225 // ----------------------------------------------------------------------------
2229 #include <wx/zstream.h>
2230 #include <wx/wfstream.h>
2232 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2233 static const char *TEST_DATA
= "hello and hello again";
2235 static void TestZlibStreamWrite()
2237 puts("*** Testing Zlib stream reading ***\n");
2239 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2240 wxZlibOutputStream
ostr(fileOutStream
, 0);
2241 printf("Compressing the test string... ");
2242 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2245 puts("(ERROR: failed)");
2252 puts("\n----- done ------");
2255 static void TestZlibStreamRead()
2257 puts("*** Testing Zlib stream reading ***\n");
2259 wxFileInputStream
fileInStream(FILENAME_GZ
);
2260 wxZlibInputStream
istr(fileInStream
);
2261 printf("Archive size: %u\n", istr
.GetSize());
2263 puts("Dumping the file:");
2264 while ( !istr
.Eof() )
2266 putchar(istr
.GetC());
2270 puts("\n----- done ------");
2275 // ----------------------------------------------------------------------------
2277 // ----------------------------------------------------------------------------
2279 #ifdef TEST_DATETIME
2281 #include <wx/date.h>
2283 #include <wx/datetime.h>
2288 wxDateTime::wxDateTime_t day
;
2289 wxDateTime::Month month
;
2291 wxDateTime::wxDateTime_t hour
, min
, sec
;
2293 wxDateTime::WeekDay wday
;
2294 time_t gmticks
, ticks
;
2296 void Init(const wxDateTime::Tm
& tm
)
2305 gmticks
= ticks
= -1;
2308 wxDateTime
DT() const
2309 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2311 bool SameDay(const wxDateTime::Tm
& tm
) const
2313 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2316 wxString
Format() const
2319 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2321 wxDateTime::GetMonthName(month
).c_str(),
2323 abs(wxDateTime::ConvertYearToBC(year
)),
2324 year
> 0 ? "AD" : "BC");
2328 wxString
FormatDate() const
2331 s
.Printf("%02d-%s-%4d%s",
2333 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2334 abs(wxDateTime::ConvertYearToBC(year
)),
2335 year
> 0 ? "AD" : "BC");
2340 static const Date testDates
[] =
2342 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2343 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2344 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2345 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2346 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2347 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2348 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2349 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2350 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2351 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2352 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2353 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2354 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2355 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2356 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2359 // this test miscellaneous static wxDateTime functions
2360 static void TestTimeStatic()
2362 puts("\n*** wxDateTime static methods test ***");
2364 // some info about the current date
2365 int year
= wxDateTime::GetCurrentYear();
2366 printf("Current year %d is %sa leap one and has %d days.\n",
2368 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2369 wxDateTime::GetNumberOfDays(year
));
2371 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2372 printf("Current month is '%s' ('%s') and it has %d days\n",
2373 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2374 wxDateTime::GetMonthName(month
).c_str(),
2375 wxDateTime::GetNumberOfDays(month
));
2378 static const size_t nYears
= 5;
2379 static const size_t years
[2][nYears
] =
2381 // first line: the years to test
2382 { 1990, 1976, 2000, 2030, 1984, },
2384 // second line: TRUE if leap, FALSE otherwise
2385 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2388 for ( size_t n
= 0; n
< nYears
; n
++ )
2390 int year
= years
[0][n
];
2391 bool should
= years
[1][n
] != 0,
2392 is
= wxDateTime::IsLeapYear(year
);
2394 printf("Year %d is %sa leap year (%s)\n",
2397 should
== is
? "ok" : "ERROR");
2399 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2403 // test constructing wxDateTime objects
2404 static void TestTimeSet()
2406 puts("\n*** wxDateTime construction test ***");
2408 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2410 const Date
& d1
= testDates
[n
];
2411 wxDateTime dt
= d1
.DT();
2414 d2
.Init(dt
.GetTm());
2416 wxString s1
= d1
.Format(),
2419 printf("Date: %s == %s (%s)\n",
2420 s1
.c_str(), s2
.c_str(),
2421 s1
== s2
? "ok" : "ERROR");
2425 // test time zones stuff
2426 static void TestTimeZones()
2428 puts("\n*** wxDateTime timezone test ***");
2430 wxDateTime now
= wxDateTime::Now();
2432 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2433 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2434 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2435 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2436 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2437 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2439 wxDateTime::Tm tm
= now
.GetTm();
2440 if ( wxDateTime(tm
) != now
)
2442 printf("ERROR: got %s instead of %s\n",
2443 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2447 // test some minimal support for the dates outside the standard range
2448 static void TestTimeRange()
2450 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2452 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2454 printf("Unix epoch:\t%s\n",
2455 wxDateTime(2440587.5).Format(fmt
).c_str());
2456 printf("Feb 29, 0: \t%s\n",
2457 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2458 printf("JDN 0: \t%s\n",
2459 wxDateTime(0.0).Format(fmt
).c_str());
2460 printf("Jan 1, 1AD:\t%s\n",
2461 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2462 printf("May 29, 2099:\t%s\n",
2463 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2466 static void TestTimeTicks()
2468 puts("\n*** wxDateTime ticks test ***");
2470 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2472 const Date
& d
= testDates
[n
];
2473 if ( d
.ticks
== -1 )
2476 wxDateTime dt
= d
.DT();
2477 long ticks
= (dt
.GetValue() / 1000).ToLong();
2478 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2479 if ( ticks
== d
.ticks
)
2485 printf(" (ERROR: should be %ld, delta = %ld)\n",
2486 d
.ticks
, ticks
- d
.ticks
);
2489 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2490 ticks
= (dt
.GetValue() / 1000).ToLong();
2491 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2492 if ( ticks
== d
.gmticks
)
2498 printf(" (ERROR: should be %ld, delta = %ld)\n",
2499 d
.gmticks
, ticks
- d
.gmticks
);
2506 // test conversions to JDN &c
2507 static void TestTimeJDN()
2509 puts("\n*** wxDateTime to JDN test ***");
2511 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2513 const Date
& d
= testDates
[n
];
2514 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2515 double jdn
= dt
.GetJulianDayNumber();
2517 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2524 printf(" (ERROR: should be %f, delta = %f)\n",
2525 d
.jdn
, jdn
- d
.jdn
);
2530 // test week days computation
2531 static void TestTimeWDays()
2533 puts("\n*** wxDateTime weekday test ***");
2535 // test GetWeekDay()
2537 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2539 const Date
& d
= testDates
[n
];
2540 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2542 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2545 wxDateTime::GetWeekDayName(wday
).c_str());
2546 if ( wday
== d
.wday
)
2552 printf(" (ERROR: should be %s)\n",
2553 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2559 // test SetToWeekDay()
2560 struct WeekDateTestData
2562 Date date
; // the real date (precomputed)
2563 int nWeek
; // its week index in the month
2564 wxDateTime::WeekDay wday
; // the weekday
2565 wxDateTime::Month month
; // the month
2566 int year
; // and the year
2568 wxString
Format() const
2571 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2573 case 1: which
= "first"; break;
2574 case 2: which
= "second"; break;
2575 case 3: which
= "third"; break;
2576 case 4: which
= "fourth"; break;
2577 case 5: which
= "fifth"; break;
2579 case -1: which
= "last"; break;
2584 which
+= " from end";
2587 s
.Printf("The %s %s of %s in %d",
2589 wxDateTime::GetWeekDayName(wday
).c_str(),
2590 wxDateTime::GetMonthName(month
).c_str(),
2597 // the array data was generated by the following python program
2599 from DateTime import *
2600 from whrandom import *
2601 from string import *
2603 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2604 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2606 week = DateTimeDelta(7)
2609 year = randint(1900, 2100)
2610 month = randint(1, 12)
2611 day = randint(1, 28)
2612 dt = DateTime(year, month, day)
2613 wday = dt.day_of_week
2615 countFromEnd = choice([-1, 1])
2618 while dt.month is month:
2619 dt = dt - countFromEnd * week
2620 weekNum = weekNum + countFromEnd
2622 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2624 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2625 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2628 static const WeekDateTestData weekDatesTestData
[] =
2630 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2631 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2632 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2633 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2634 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2635 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2636 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2637 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2638 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2639 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2640 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2641 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2642 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2643 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2644 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2645 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2646 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2647 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2648 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2649 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2652 static const char *fmt
= "%d-%b-%Y";
2655 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2657 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2659 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2661 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2663 const Date
& d
= wd
.date
;
2664 if ( d
.SameDay(dt
.GetTm()) )
2670 dt
.Set(d
.day
, d
.month
, d
.year
);
2672 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2677 // test the computation of (ISO) week numbers
2678 static void TestTimeWNumber()
2680 puts("\n*** wxDateTime week number test ***");
2682 struct WeekNumberTestData
2684 Date date
; // the date
2685 wxDateTime::wxDateTime_t week
; // the week number in the year
2686 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2687 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2688 wxDateTime::wxDateTime_t dnum
; // day number in the year
2691 // data generated with the following python script:
2693 from DateTime import *
2694 from whrandom import *
2695 from string import *
2697 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2698 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2700 def GetMonthWeek(dt):
2701 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2702 if weekNumMonth < 0:
2703 weekNumMonth = weekNumMonth + 53
2706 def GetLastSundayBefore(dt):
2707 if dt.iso_week[2] == 7:
2710 return dt - DateTimeDelta(dt.iso_week[2])
2713 year = randint(1900, 2100)
2714 month = randint(1, 12)
2715 day = randint(1, 28)
2716 dt = DateTime(year, month, day)
2717 dayNum = dt.day_of_year
2718 weekNum = dt.iso_week[1]
2719 weekNumMonth = GetMonthWeek(dt)
2722 dtSunday = GetLastSundayBefore(dt)
2724 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2725 weekNumMonth2 = weekNumMonth2 + 1
2726 dtSunday = dtSunday - DateTimeDelta(7)
2728 data = { 'day': rjust(`day`, 2), \
2729 'month': monthNames[month - 1], \
2731 'weekNum': rjust(`weekNum`, 2), \
2732 'weekNumMonth': weekNumMonth, \
2733 'weekNumMonth2': weekNumMonth2, \
2734 'dayNum': rjust(`dayNum`, 3) }
2736 print " { { %(day)s, "\
2737 "wxDateTime::%(month)s, "\
2740 "%(weekNumMonth)s, "\
2741 "%(weekNumMonth2)s, "\
2742 "%(dayNum)s }," % data
2745 static const WeekNumberTestData weekNumberTestDates
[] =
2747 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2748 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2749 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2750 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2751 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2752 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2753 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2754 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2755 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2756 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2757 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2758 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2759 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2760 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2761 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2762 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2763 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2764 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2765 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2766 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2769 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2771 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2772 const Date
& d
= wn
.date
;
2774 wxDateTime dt
= d
.DT();
2776 wxDateTime::wxDateTime_t
2777 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2778 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2779 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2780 dnum
= dt
.GetDayOfYear();
2782 printf("%s: the day number is %d",
2783 d
.FormatDate().c_str(), dnum
);
2784 if ( dnum
== wn
.dnum
)
2790 printf(" (ERROR: should be %d)", wn
.dnum
);
2793 printf(", week in month is %d", wmon
);
2794 if ( wmon
== wn
.wmon
)
2800 printf(" (ERROR: should be %d)", wn
.wmon
);
2803 printf(" or %d", wmon2
);
2804 if ( wmon2
== wn
.wmon2
)
2810 printf(" (ERROR: should be %d)", wn
.wmon2
);
2813 printf(", week in year is %d", week
);
2814 if ( week
== wn
.week
)
2820 printf(" (ERROR: should be %d)\n", wn
.week
);
2825 // test DST calculations
2826 static void TestTimeDST()
2828 puts("\n*** wxDateTime DST test ***");
2830 printf("DST is%s in effect now.\n\n",
2831 wxDateTime::Now().IsDST() ? "" : " not");
2833 // taken from http://www.energy.ca.gov/daylightsaving.html
2834 static const Date datesDST
[2][2004 - 1900 + 1] =
2837 { 1, wxDateTime::Apr
, 1990 },
2838 { 7, wxDateTime::Apr
, 1991 },
2839 { 5, wxDateTime::Apr
, 1992 },
2840 { 4, wxDateTime::Apr
, 1993 },
2841 { 3, wxDateTime::Apr
, 1994 },
2842 { 2, wxDateTime::Apr
, 1995 },
2843 { 7, wxDateTime::Apr
, 1996 },
2844 { 6, wxDateTime::Apr
, 1997 },
2845 { 5, wxDateTime::Apr
, 1998 },
2846 { 4, wxDateTime::Apr
, 1999 },
2847 { 2, wxDateTime::Apr
, 2000 },
2848 { 1, wxDateTime::Apr
, 2001 },
2849 { 7, wxDateTime::Apr
, 2002 },
2850 { 6, wxDateTime::Apr
, 2003 },
2851 { 4, wxDateTime::Apr
, 2004 },
2854 { 28, wxDateTime::Oct
, 1990 },
2855 { 27, wxDateTime::Oct
, 1991 },
2856 { 25, wxDateTime::Oct
, 1992 },
2857 { 31, wxDateTime::Oct
, 1993 },
2858 { 30, wxDateTime::Oct
, 1994 },
2859 { 29, wxDateTime::Oct
, 1995 },
2860 { 27, wxDateTime::Oct
, 1996 },
2861 { 26, wxDateTime::Oct
, 1997 },
2862 { 25, wxDateTime::Oct
, 1998 },
2863 { 31, wxDateTime::Oct
, 1999 },
2864 { 29, wxDateTime::Oct
, 2000 },
2865 { 28, wxDateTime::Oct
, 2001 },
2866 { 27, wxDateTime::Oct
, 2002 },
2867 { 26, wxDateTime::Oct
, 2003 },
2868 { 31, wxDateTime::Oct
, 2004 },
2873 for ( year
= 1990; year
< 2005; year
++ )
2875 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2876 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2878 printf("DST period in the US for year %d: from %s to %s",
2879 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2881 size_t n
= year
- 1990;
2882 const Date
& dBegin
= datesDST
[0][n
];
2883 const Date
& dEnd
= datesDST
[1][n
];
2885 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2891 printf(" (ERROR: should be %s %d to %s %d)\n",
2892 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2893 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2899 for ( year
= 1990; year
< 2005; year
++ )
2901 printf("DST period in Europe for year %d: from %s to %s\n",
2903 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2904 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2908 // test wxDateTime -> text conversion
2909 static void TestTimeFormat()
2911 puts("\n*** wxDateTime formatting test ***");
2913 // some information may be lost during conversion, so store what kind
2914 // of info should we recover after a round trip
2917 CompareNone
, // don't try comparing
2918 CompareBoth
, // dates and times should be identical
2919 CompareDate
, // dates only
2920 CompareTime
// time only
2925 CompareKind compareKind
;
2927 } formatTestFormats
[] =
2929 { CompareBoth
, "---> %c" },
2930 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2931 { CompareBoth
, "Date is %x, time is %X" },
2932 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2933 { CompareNone
, "The day of year: %j, the week of year: %W" },
2934 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2937 static const Date formatTestDates
[] =
2939 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2940 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2942 // this test can't work for other centuries because it uses two digit
2943 // years in formats, so don't even try it
2944 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2945 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2946 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2950 // an extra test (as it doesn't depend on date, don't do it in the loop)
2951 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2953 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2957 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2958 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2960 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2961 printf("%s", s
.c_str());
2963 // what can we recover?
2964 int kind
= formatTestFormats
[n
].compareKind
;
2968 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2971 // converion failed - should it have?
2972 if ( kind
== CompareNone
)
2975 puts(" (ERROR: conversion back failed)");
2979 // should have parsed the entire string
2980 puts(" (ERROR: conversion back stopped too soon)");
2984 bool equal
= FALSE
; // suppress compilaer warning
2992 equal
= dt
.IsSameDate(dt2
);
2996 equal
= dt
.IsSameTime(dt2
);
3002 printf(" (ERROR: got back '%s' instead of '%s')\n",
3003 dt2
.Format().c_str(), dt
.Format().c_str());
3014 // test text -> wxDateTime conversion
3015 static void TestTimeParse()
3017 puts("\n*** wxDateTime parse test ***");
3019 struct ParseTestData
3026 static const ParseTestData parseTestDates
[] =
3028 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
3029 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
3032 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
3034 const char *format
= parseTestDates
[n
].format
;
3036 printf("%s => ", format
);
3039 if ( dt
.ParseRfc822Date(format
) )
3041 printf("%s ", dt
.Format().c_str());
3043 if ( parseTestDates
[n
].good
)
3045 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
3052 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
3057 puts("(ERROR: bad format)");
3062 printf("bad format (%s)\n",
3063 parseTestDates
[n
].good
? "ERROR" : "ok");
3068 static void TestDateTimeInteractive()
3070 puts("\n*** interactive wxDateTime tests ***");
3076 printf("Enter a date: ");
3077 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
3080 // kill the last '\n'
3081 buf
[strlen(buf
) - 1] = 0;
3084 const char *p
= dt
.ParseDate(buf
);
3087 printf("ERROR: failed to parse the date '%s'.\n", buf
);
3093 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
3096 printf("%s: day %u, week of month %u/%u, week of year %u\n",
3097 dt
.Format("%b %d, %Y").c_str(),
3099 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3100 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3101 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3104 puts("\n*** done ***");
3107 static void TestTimeMS()
3109 puts("*** testing millisecond-resolution support in wxDateTime ***");
3111 wxDateTime dt1
= wxDateTime::Now(),
3112 dt2
= wxDateTime::UNow();
3114 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
3115 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3116 printf("Dummy loop: ");
3117 for ( int i
= 0; i
< 6000; i
++ )
3119 //for ( int j = 0; j < 10; j++ )
3122 s
.Printf("%g", sqrt(i
));
3131 dt2
= wxDateTime::UNow();
3132 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
3134 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
3136 puts("\n*** done ***");
3139 static void TestTimeArithmetics()
3141 puts("\n*** testing arithmetic operations on wxDateTime ***");
3143 static const struct ArithmData
3145 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3146 : span(sp
), name(nam
) { }
3150 } testArithmData
[] =
3152 ArithmData(wxDateSpan::Day(), "day"),
3153 ArithmData(wxDateSpan::Week(), "week"),
3154 ArithmData(wxDateSpan::Month(), "month"),
3155 ArithmData(wxDateSpan::Year(), "year"),
3156 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3159 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3161 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3163 wxDateSpan span
= testArithmData
[n
].span
;
3167 const char *name
= testArithmData
[n
].name
;
3168 printf("%s + %s = %s, %s - %s = %s\n",
3169 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3170 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3172 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3173 if ( dt1
- span
== dt
)
3179 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3182 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3183 if ( dt2
+ span
== dt
)
3189 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3192 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3193 if ( dt2
+ 2*span
== dt1
)
3199 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3206 static void TestTimeHolidays()
3208 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3210 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3211 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3212 dtEnd
= dtStart
.GetLastMonthDay();
3214 wxDateTimeArray hol
;
3215 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3217 const wxChar
*format
= "%d-%b-%Y (%a)";
3219 printf("All holidays between %s and %s:\n",
3220 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3222 size_t count
= hol
.GetCount();
3223 for ( size_t n
= 0; n
< count
; n
++ )
3225 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3231 static void TestTimeZoneBug()
3233 puts("\n*** testing for DST/timezone bug ***\n");
3235 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3236 for ( int i
= 0; i
< 31; i
++ )
3238 printf("Date %s: week day %s.\n",
3239 date
.Format(_T("%d-%m-%Y")).c_str(),
3240 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3242 date
+= wxDateSpan::Day();
3250 // test compatibility with the old wxDate/wxTime classes
3251 static void TestTimeCompatibility()
3253 puts("\n*** wxDateTime compatibility test ***");
3255 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3256 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3258 double jdnNow
= wxDateTime::Now().GetJDN();
3259 long jdnMidnight
= (long)(jdnNow
- 0.5);
3260 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3262 jdnMidnight
= wxDate().Set().GetJulianDate();
3263 printf("wxDateTime for today: %s\n",
3264 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3266 int flags
= wxEUROPEAN
;//wxFULL;
3269 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3270 for ( int n
= 0; n
< 7; n
++ )
3272 printf("Previous %s is %s\n",
3273 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3274 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3280 #endif // TEST_DATETIME
3282 // ----------------------------------------------------------------------------
3284 // ----------------------------------------------------------------------------
3288 #include <wx/thread.h>
3290 static size_t gs_counter
= (size_t)-1;
3291 static wxCriticalSection gs_critsect
;
3292 static wxCondition gs_cond
;
3294 class MyJoinableThread
: public wxThread
3297 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3298 { m_n
= n
; Create(); }
3300 // thread execution starts here
3301 virtual ExitCode
Entry();
3307 wxThread::ExitCode
MyJoinableThread::Entry()
3309 unsigned long res
= 1;
3310 for ( size_t n
= 1; n
< m_n
; n
++ )
3314 // it's a loooong calculation :-)
3318 return (ExitCode
)res
;
3321 class MyDetachedThread
: public wxThread
3324 MyDetachedThread(size_t n
, char ch
)
3328 m_cancelled
= FALSE
;
3333 // thread execution starts here
3334 virtual ExitCode
Entry();
3337 virtual void OnExit();
3340 size_t m_n
; // number of characters to write
3341 char m_ch
; // character to write
3343 bool m_cancelled
; // FALSE if we exit normally
3346 wxThread::ExitCode
MyDetachedThread::Entry()
3349 wxCriticalSectionLocker
lock(gs_critsect
);
3350 if ( gs_counter
== (size_t)-1 )
3356 for ( size_t n
= 0; n
< m_n
; n
++ )
3358 if ( TestDestroy() )
3368 wxThread::Sleep(100);
3374 void MyDetachedThread::OnExit()
3376 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3378 wxCriticalSectionLocker
lock(gs_critsect
);
3379 if ( !--gs_counter
&& !m_cancelled
)
3383 void TestDetachedThreads()
3385 puts("\n*** Testing detached threads ***");
3387 static const size_t nThreads
= 3;
3388 MyDetachedThread
*threads
[nThreads
];
3390 for ( n
= 0; n
< nThreads
; n
++ )
3392 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3395 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3396 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3398 for ( n
= 0; n
< nThreads
; n
++ )
3403 // wait until all threads terminate
3409 void TestJoinableThreads()
3411 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3413 // calc 10! in the background
3414 MyJoinableThread
thread(10);
3417 printf("\nThread terminated with exit code %lu.\n",
3418 (unsigned long)thread
.Wait());
3421 void TestThreadSuspend()
3423 puts("\n*** Testing thread suspend/resume functions ***");
3425 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3429 // this is for this demo only, in a real life program we'd use another
3430 // condition variable which would be signaled from wxThread::Entry() to
3431 // tell us that the thread really started running - but here just wait a
3432 // bit and hope that it will be enough (the problem is, of course, that
3433 // the thread might still not run when we call Pause() which will result
3435 wxThread::Sleep(300);
3437 for ( size_t n
= 0; n
< 3; n
++ )
3441 puts("\nThread suspended");
3444 // don't sleep but resume immediately the first time
3445 wxThread::Sleep(300);
3447 puts("Going to resume the thread");
3452 puts("Waiting until it terminates now");
3454 // wait until the thread terminates
3460 void TestThreadDelete()
3462 // As above, using Sleep() is only for testing here - we must use some
3463 // synchronisation object instead to ensure that the thread is still
3464 // running when we delete it - deleting a detached thread which already
3465 // terminated will lead to a crash!
3467 puts("\n*** Testing thread delete function ***");
3469 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3473 puts("\nDeleted a thread which didn't start to run yet.");
3475 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3479 wxThread::Sleep(300);
3483 puts("\nDeleted a running thread.");
3485 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3489 wxThread::Sleep(300);
3495 puts("\nDeleted a sleeping thread.");
3497 MyJoinableThread
thread3(20);
3502 puts("\nDeleted a joinable thread.");
3504 MyJoinableThread
thread4(2);
3507 wxThread::Sleep(300);
3511 puts("\nDeleted a joinable thread which already terminated.");
3516 #endif // TEST_THREADS
3518 // ----------------------------------------------------------------------------
3520 // ----------------------------------------------------------------------------
3524 static void PrintArray(const char* name
, const wxArrayString
& array
)
3526 printf("Dump of the array '%s'\n", name
);
3528 size_t nCount
= array
.GetCount();
3529 for ( size_t n
= 0; n
< nCount
; n
++ )
3531 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3535 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3537 printf("Dump of the array '%s'\n", name
);
3539 size_t nCount
= array
.GetCount();
3540 for ( size_t n
= 0; n
< nCount
; n
++ )
3542 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3546 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3547 const wxString
& second
)
3549 return first
.length() - second
.length();
3552 int wxCMPFUNC_CONV
IntCompare(int *first
,
3555 return *first
- *second
;
3558 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3561 return *second
- *first
;
3564 static void TestArrayOfInts()
3566 puts("*** Testing wxArrayInt ***\n");
3577 puts("After sort:");
3581 puts("After reverse sort:");
3582 a
.Sort(IntRevCompare
);
3586 #include "wx/dynarray.h"
3588 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3589 #include "wx/arrimpl.cpp"
3590 WX_DEFINE_OBJARRAY(ArrayBars
);
3592 static void TestArrayOfObjects()
3594 puts("*** Testing wxObjArray ***\n");
3598 Bar
bar("second bar");
3600 printf("Initially: %u objects in the array, %u objects total.\n",
3601 bars
.GetCount(), Bar::GetNumber());
3603 bars
.Add(new Bar("first bar"));
3606 printf("Now: %u objects in the array, %u objects total.\n",
3607 bars
.GetCount(), Bar::GetNumber());
3611 printf("After Empty(): %u objects in the array, %u objects total.\n",
3612 bars
.GetCount(), Bar::GetNumber());
3615 printf("Finally: no more objects in the array, %u objects total.\n",
3619 #endif // TEST_ARRAYS
3621 // ----------------------------------------------------------------------------
3623 // ----------------------------------------------------------------------------
3627 #include "wx/timer.h"
3628 #include "wx/tokenzr.h"
3630 static void TestStringConstruction()
3632 puts("*** Testing wxString constructores ***");
3634 #define TEST_CTOR(args, res) \
3637 printf("wxString%s = %s ", #args, s.c_str()); \
3644 printf("(ERROR: should be %s)\n", res); \
3648 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3649 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3650 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3651 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3653 static const wxChar
*s
= _T("?really!");
3654 const wxChar
*start
= wxStrchr(s
, _T('r'));
3655 const wxChar
*end
= wxStrchr(s
, _T('!'));
3656 TEST_CTOR((start
, end
), _T("really"));
3661 static void TestString()
3671 for (int i
= 0; i
< 1000000; ++i
)
3675 c
= "! How'ya doin'?";
3678 c
= "Hello world! What's up?";
3683 printf ("TestString elapsed time: %ld\n", sw
.Time());
3686 static void TestPChar()
3694 for (int i
= 0; i
< 1000000; ++i
)
3696 strcpy (a
, "Hello");
3697 strcpy (b
, " world");
3698 strcpy (c
, "! How'ya doin'?");
3701 strcpy (c
, "Hello world! What's up?");
3702 if (strcmp (c
, a
) == 0)
3706 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3709 static void TestStringSub()
3711 wxString
s("Hello, world!");
3713 puts("*** Testing wxString substring extraction ***");
3715 printf("String = '%s'\n", s
.c_str());
3716 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3717 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3718 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3719 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3720 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3721 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3723 static const wxChar
*prefixes
[] =
3727 _T("Hello, world!"),
3728 _T("Hello, world!!!"),
3734 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3736 wxString prefix
= prefixes
[n
], rest
;
3737 bool rc
= s
.StartsWith(prefix
, &rest
);
3738 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3741 printf(" (the rest is '%s')\n", rest
.c_str());
3752 static void TestStringFormat()
3754 puts("*** Testing wxString formatting ***");
3757 s
.Printf("%03d", 18);
3759 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3760 printf("Number 18: %s\n", s
.c_str());
3765 // returns "not found" for npos, value for all others
3766 static wxString
PosToString(size_t res
)
3768 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3769 : wxString::Format(_T("%u"), res
);
3773 static void TestStringFind()
3775 puts("*** Testing wxString find() functions ***");
3777 static const wxChar
*strToFind
= _T("ell");
3778 static const struct StringFindTest
3782 result
; // of searching "ell" in str
3785 { _T("Well, hello world"), 0, 1 },
3786 { _T("Well, hello world"), 6, 7 },
3787 { _T("Well, hello world"), 9, wxString::npos
},
3790 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3792 const StringFindTest
& ft
= findTestData
[n
];
3793 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3795 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3796 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3798 size_t resTrue
= ft
.result
;
3799 if ( res
== resTrue
)
3805 printf(_T("(ERROR: should be %s)\n"),
3806 PosToString(resTrue
).c_str());
3813 static void TestStringTokenizer()
3815 puts("*** Testing wxStringTokenizer ***");
3817 static const wxChar
*modeNames
[] =
3821 _T("return all empty"),
3826 static const struct StringTokenizerTest
3828 const wxChar
*str
; // string to tokenize
3829 const wxChar
*delims
; // delimiters to use
3830 size_t count
; // count of token
3831 wxStringTokenizerMode mode
; // how should we tokenize it
3832 } tokenizerTestData
[] =
3834 { _T(""), _T(" "), 0 },
3835 { _T("Hello, world"), _T(" "), 2 },
3836 { _T("Hello, world "), _T(" "), 2 },
3837 { _T("Hello, world"), _T(","), 2 },
3838 { _T("Hello, world!"), _T(",!"), 2 },
3839 { _T("Hello,, world!"), _T(",!"), 3 },
3840 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3841 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3842 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3843 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3844 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3845 { _T("01/02/99"), _T("/-"), 3 },
3846 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3849 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3851 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3852 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3854 size_t count
= tkz
.CountTokens();
3855 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3856 MakePrintable(tt
.str
).c_str(),
3858 MakePrintable(tt
.delims
).c_str(),
3859 modeNames
[tkz
.GetMode()]);
3860 if ( count
== tt
.count
)
3866 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3871 // if we emulate strtok(), check that we do it correctly
3872 wxChar
*buf
, *s
= NULL
, *last
;
3874 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3876 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3877 wxStrcpy(buf
, tt
.str
);
3879 s
= wxStrtok(buf
, tt
.delims
, &last
);
3886 // now show the tokens themselves
3888 while ( tkz
.HasMoreTokens() )
3890 wxString token
= tkz
.GetNextToken();
3892 printf(_T("\ttoken %u: '%s'"),
3894 MakePrintable(token
).c_str());
3904 printf(" (ERROR: should be %s)\n", s
);
3907 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3911 // nothing to compare with
3916 if ( count2
!= count
)
3918 puts(_T("\tERROR: token count mismatch"));
3927 static void TestStringReplace()
3929 puts("*** Testing wxString::replace ***");
3931 static const struct StringReplaceTestData
3933 const wxChar
*original
; // original test string
3934 size_t start
, len
; // the part to replace
3935 const wxChar
*replacement
; // the replacement string
3936 const wxChar
*result
; // and the expected result
3937 } stringReplaceTestData
[] =
3939 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3940 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3941 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3942 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3943 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3946 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3948 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3950 wxString original
= data
.original
;
3951 original
.replace(data
.start
, data
.len
, data
.replacement
);
3953 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3954 data
.original
, data
.start
, data
.len
, data
.replacement
,
3957 if ( original
== data
.result
)
3963 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3970 #endif // TEST_STRINGS
3972 // ----------------------------------------------------------------------------
3974 // ----------------------------------------------------------------------------
3976 int main(int argc
, char **argv
)
3978 if ( !wxInitialize() )
3980 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3984 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3986 #endif // TEST_USLEEP
3989 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3991 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3992 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3994 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3995 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3996 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3997 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3999 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
4000 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4005 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4007 parser
.AddOption("project_name", "", "full path to project file",
4008 wxCMD_LINE_VAL_STRING
,
4009 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4011 switch ( parser
.Parse() )
4014 wxLogMessage("Help was given, terminating.");
4018 ShowCmdLine(parser
);
4022 wxLogMessage("Syntax error detected, aborting.");
4025 #endif // TEST_CMDLINE
4036 TestStringConstruction();
4039 TestStringTokenizer();
4040 TestStringReplace();
4042 #endif // TEST_STRINGS
4055 puts("*** Initially:");
4057 PrintArray("a1", a1
);
4059 wxArrayString
a2(a1
);
4060 PrintArray("a2", a2
);
4062 wxSortedArrayString
a3(a1
);
4063 PrintArray("a3", a3
);
4065 puts("*** After deleting a string from a1");
4068 PrintArray("a1", a1
);
4069 PrintArray("a2", a2
);
4070 PrintArray("a3", a3
);
4072 puts("*** After reassigning a1 to a2 and a3");
4074 PrintArray("a2", a2
);
4075 PrintArray("a3", a3
);
4077 puts("*** After sorting a1");
4079 PrintArray("a1", a1
);
4081 puts("*** After sorting a1 in reverse order");
4083 PrintArray("a1", a1
);
4085 puts("*** After sorting a1 by the string length");
4086 a1
.Sort(StringLenCompare
);
4087 PrintArray("a1", a1
);
4089 TestArrayOfObjects();
4092 #endif // TEST_ARRAYS
4098 #ifdef TEST_DLLLOADER
4100 #endif // TEST_DLLLOADER
4104 #endif // TEST_ENVIRON
4108 #endif // TEST_EXECUTE
4110 #ifdef TEST_FILECONF
4112 #endif // TEST_FILECONF
4120 for ( size_t n
= 0; n
< 8000; n
++ )
4122 s
<< (char)('A' + (n
% 26));
4126 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
4128 // this one shouldn't be truncated
4131 // but this one will because log functions use fixed size buffer
4132 // (note that it doesn't need '\n' at the end neither - will be added
4134 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4146 #ifdef TEST_FILENAME
4147 TestFileNameSplit();
4150 TestFileNameConstruction();
4152 TestFileNameComparison();
4153 TestFileNameOperations();
4155 #endif // TEST_FILENAME
4158 int nCPUs
= wxThread::GetCPUCount();
4159 printf("This system has %d CPUs\n", nCPUs
);
4161 wxThread::SetConcurrency(nCPUs
);
4163 if ( argc
> 1 && argv
[1][0] == 't' )
4164 wxLog::AddTraceMask("thread");
4167 TestDetachedThreads();
4169 TestJoinableThreads();
4171 TestThreadSuspend();
4175 #endif // TEST_THREADS
4177 #ifdef TEST_LONGLONG
4178 // seed pseudo random generator
4179 srand((unsigned)time(NULL
));
4187 TestMultiplication();
4190 TestLongLongConversion();
4191 TestBitOperations();
4193 TestLongLongComparison();
4194 #endif // TEST_LONGLONG
4201 wxLog::AddTraceMask(_T("mime"));
4209 TestMimeAssociate();
4212 #ifdef TEST_INFO_FUNCTIONS
4215 #endif // TEST_INFO_FUNCTIONS
4217 #ifdef TEST_REGISTRY
4220 TestRegistryAssociation();
4221 #endif // TEST_REGISTRY
4229 #endif // TEST_SOCKETS
4232 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4233 if ( TestFtpConnect() )
4244 TestFtpInteractive();
4246 //else: connecting to the FTP server failed
4254 #endif // TEST_STREAMS
4258 #endif // TEST_TIMER
4260 #ifdef TEST_DATETIME
4273 TestTimeArithmetics();
4281 TestDateTimeInteractive();
4282 #endif // TEST_DATETIME
4288 #endif // TEST_VCARD
4292 #endif // TEST_WCHAR
4295 TestZipStreamRead();
4300 TestZlibStreamWrite();
4301 TestZlibStreamRead();