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 void TestFileNameConstruction()
601 puts("*** testing wxFileName construction ***");
603 static const wxChar
*filenames
[] =
611 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
613 wxFileName
fn(filenames
[n
]);
615 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
616 if ( !fn
.Normalize() )
618 puts("ERROR (couldn't be normalized)");
622 printf("normalized: '%s'\n", fn
.GetFullPath().c_str());
629 static void TestFileNameComparison()
634 static void TestFileNameOperations()
639 static void TestFileNameCwd()
644 #endif // TEST_FILENAME
646 // ----------------------------------------------------------------------------
648 // ----------------------------------------------------------------------------
656 Foo(int n_
) { n
= n_
; count
++; }
664 size_t Foo::count
= 0;
666 WX_DECLARE_LIST(Foo
, wxListFoos
);
667 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
669 #include <wx/listimpl.cpp>
671 WX_DEFINE_LIST(wxListFoos
);
673 static void TestHash()
675 puts("*** Testing wxHashTable ***\n");
679 hash
.DeleteContents(TRUE
);
681 printf("Hash created: %u foos in hash, %u foos totally\n",
682 hash
.GetCount(), Foo::count
);
684 static const int hashTestData
[] =
686 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
690 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
692 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
695 printf("Hash filled: %u foos in hash, %u foos totally\n",
696 hash
.GetCount(), Foo::count
);
698 puts("Hash access test:");
699 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
701 printf("\tGetting element with key %d, value %d: ",
703 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
706 printf("ERROR, not found.\n");
710 printf("%d (%s)\n", foo
->n
,
711 (size_t)foo
->n
== n
? "ok" : "ERROR");
715 printf("\nTrying to get an element not in hash: ");
717 if ( hash
.Get(1234) || hash
.Get(1, 0) )
719 puts("ERROR: found!");
723 puts("ok (not found)");
727 printf("Hash destroyed: %u foos left\n", Foo::count
);
732 // ----------------------------------------------------------------------------
734 // ----------------------------------------------------------------------------
740 WX_DECLARE_LIST(Bar
, wxListBars
);
741 #include <wx/listimpl.cpp>
742 WX_DEFINE_LIST(wxListBars
);
744 static void TestListCtor()
746 puts("*** Testing wxList construction ***\n");
750 list1
.Append(new Bar(_T("first")));
751 list1
.Append(new Bar(_T("second")));
753 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
754 list1
.GetCount(), Bar::GetNumber());
759 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
760 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
762 list1
.DeleteContents(TRUE
);
765 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
770 // ----------------------------------------------------------------------------
772 // ----------------------------------------------------------------------------
776 #include <wx/mimetype.h>
778 static wxMimeTypesManager g_mimeManager
;
780 static void TestMimeEnum()
782 wxArrayString mimetypes
;
784 size_t count
= g_mimeManager
.EnumAllFileTypes(mimetypes
);
786 printf("*** All %u known filetypes: ***\n", count
);
791 for ( size_t n
= 0; n
< count
; n
++ )
793 wxFileType
*filetype
= g_mimeManager
.GetFileTypeFromMimeType(mimetypes
[n
]);
796 printf("nothing known about the filetype '%s'!\n",
797 mimetypes
[n
].c_str());
801 filetype
->GetDescription(&desc
);
802 filetype
->GetExtensions(exts
);
804 filetype
->GetIcon(NULL
);
807 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
814 printf("\t%s: %s (%s)\n",
815 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
819 static void TestMimeOverride()
821 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
823 wxString mailcap
= _T("/tmp/mailcap"),
824 mimetypes
= _T("/tmp/mime.types");
826 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
828 g_mimeManager
.ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
829 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
831 g_mimeManager
.ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
834 static void TestMimeFilename()
836 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
838 static const wxChar
*filenames
[] =
845 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
847 const wxString fname
= filenames
[n
];
848 wxString ext
= fname
.AfterLast(_T('.'));
849 wxFileType
*ft
= g_mimeManager
.GetFileTypeFromExtension(ext
);
852 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
857 if ( !ft
->GetDescription(&desc
) )
858 desc
= _T("<no description>");
861 if ( !ft
->GetOpenCommand(&cmd
,
862 wxFileType::MessageParameters(fname
, _T(""))) )
863 cmd
= _T("<no command available>");
865 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
866 fname
.c_str(), desc
.c_str(), cmd
.c_str());
873 static void TestMimeAssociate()
875 wxPuts(_T("*** Testing creation of filetype association ***\n"));
877 wxFileType
*ft
= g_mimeManager
.Associate
880 _T("application/x-xyz"),
881 _T("XYZFile"), // filetype (MSW only)
882 _T("XYZ File") // description (Unix only)
886 wxPuts(_T("ERROR: failed to create association!"));
890 if ( !ft
->SetOpenCommand(_T("myprogram")) )
892 wxPuts(_T("ERROR: failed to set open command!"));
901 // ----------------------------------------------------------------------------
902 // misc information functions
903 // ----------------------------------------------------------------------------
905 #ifdef TEST_INFO_FUNCTIONS
907 #include <wx/utils.h>
909 static void TestOsInfo()
911 puts("*** Testing OS info functions ***\n");
914 wxGetOsVersion(&major
, &minor
);
915 printf("Running under: %s, version %d.%d\n",
916 wxGetOsDescription().c_str(), major
, minor
);
918 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
920 printf("Host name is %s (%s).\n",
921 wxGetHostName().c_str(), wxGetFullHostName().c_str());
926 static void TestUserInfo()
928 puts("*** Testing user info functions ***\n");
930 printf("User id is:\t%s\n", wxGetUserId().c_str());
931 printf("User name is:\t%s\n", wxGetUserName().c_str());
932 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
933 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
938 #endif // TEST_INFO_FUNCTIONS
940 // ----------------------------------------------------------------------------
942 // ----------------------------------------------------------------------------
946 #include <wx/longlong.h>
947 #include <wx/timer.h>
949 // make a 64 bit number from 4 16 bit ones
950 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
952 // get a random 64 bit number
953 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
955 #if wxUSE_LONGLONG_WX
956 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
957 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
958 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
959 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
960 #endif // wxUSE_LONGLONG_WX
962 static void TestSpeed()
964 static const long max
= 100000000;
971 for ( n
= 0; n
< max
; n
++ )
976 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
979 #if wxUSE_LONGLONG_NATIVE
984 for ( n
= 0; n
< max
; n
++ )
989 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
991 #endif // wxUSE_LONGLONG_NATIVE
997 for ( n
= 0; n
< max
; n
++ )
1002 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1006 static void TestLongLongConversion()
1008 puts("*** Testing wxLongLong conversions ***\n");
1012 for ( size_t n
= 0; n
< 100000; n
++ )
1016 #if wxUSE_LONGLONG_NATIVE
1017 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1019 wxASSERT_MSG( a
== b
, "conversions failure" );
1021 puts("Can't do it without native long long type, test skipped.");
1024 #endif // wxUSE_LONGLONG_NATIVE
1026 if ( !(nTested
% 1000) )
1038 static void TestMultiplication()
1040 puts("*** Testing wxLongLong multiplication ***\n");
1044 for ( size_t n
= 0; n
< 100000; n
++ )
1049 #if wxUSE_LONGLONG_NATIVE
1050 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1051 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1053 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1054 #else // !wxUSE_LONGLONG_NATIVE
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 TestDivision()
1074 puts("*** Testing wxLongLong division ***\n");
1078 for ( size_t n
= 0; n
< 100000; n
++ )
1080 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1081 // multiplication will not overflow)
1082 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1084 // get a random long (not wxLongLong for now) to divide it with
1089 #if wxUSE_LONGLONG_NATIVE
1090 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1092 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1093 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1094 #else // !wxUSE_LONGLONG_NATIVE
1095 // verify the result
1096 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1097 #endif // wxUSE_LONGLONG_NATIVE
1099 if ( !(nTested
% 1000) )
1111 static void TestAddition()
1113 puts("*** Testing wxLongLong addition ***\n");
1117 for ( size_t n
= 0; n
< 100000; n
++ )
1123 #if wxUSE_LONGLONG_NATIVE
1124 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1125 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1126 "addition failure" );
1127 #else // !wxUSE_LONGLONG_NATIVE
1128 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1129 #endif // wxUSE_LONGLONG_NATIVE
1131 if ( !(nTested
% 1000) )
1143 static void TestBitOperations()
1145 puts("*** Testing wxLongLong bit operation ***\n");
1149 for ( size_t n
= 0; n
< 100000; n
++ )
1153 #if wxUSE_LONGLONG_NATIVE
1154 for ( size_t n
= 0; n
< 33; n
++ )
1157 #else // !wxUSE_LONGLONG_NATIVE
1158 puts("Can't do it without native long long type, test skipped.");
1161 #endif // wxUSE_LONGLONG_NATIVE
1163 if ( !(nTested
% 1000) )
1175 static void TestLongLongComparison()
1177 puts("*** Testing wxLongLong comparison ***\n");
1179 static const long testLongs
[] =
1190 static const long ls
[2] =
1196 wxLongLongWx lls
[2];
1200 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1204 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1206 res
= lls
[m
] > testLongs
[n
];
1207 printf("0x%lx > 0x%lx is %s (%s)\n",
1208 ls
[m
], testLongs
[n
], res
? "true" : "false",
1209 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1211 res
= lls
[m
] < testLongs
[n
];
1212 printf("0x%lx < 0x%lx is %s (%s)\n",
1213 ls
[m
], testLongs
[n
], res
? "true" : "false",
1214 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1216 res
= lls
[m
] == testLongs
[n
];
1217 printf("0x%lx == 0x%lx is %s (%s)\n",
1218 ls
[m
], testLongs
[n
], res
? "true" : "false",
1219 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1227 #endif // TEST_LONGLONG
1229 // ----------------------------------------------------------------------------
1231 // ----------------------------------------------------------------------------
1233 // this is for MSW only
1235 #undef TEST_REGISTRY
1238 #ifdef TEST_REGISTRY
1240 #include <wx/msw/registry.h>
1242 // I chose this one because I liked its name, but it probably only exists under
1244 static const wxChar
*TESTKEY
=
1245 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
1247 static void TestRegistryRead()
1249 puts("*** testing registry reading ***");
1251 wxRegKey
key(TESTKEY
);
1252 printf("The test key name is '%s'.\n", key
.GetName().c_str());
1255 puts("ERROR: test key can't be opened, aborting test.");
1260 size_t nSubKeys
, nValues
;
1261 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
1263 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
1266 printf("Enumerating values:\n");
1270 bool cont
= key
.GetFirstValue(value
, dummy
);
1273 printf("Value '%s': type ", value
.c_str());
1274 switch ( key
.GetValueType(value
) )
1276 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
1277 case wxRegKey::Type_String
: printf("SZ"); break;
1278 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
1279 case wxRegKey::Type_Binary
: printf("BINARY"); break;
1280 case wxRegKey::Type_Dword
: printf("DWORD"); break;
1281 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
1282 default: printf("other (unknown)"); break;
1285 printf(", value = ");
1286 if ( key
.IsNumericValue(value
) )
1289 key
.QueryValue(value
, &val
);
1295 key
.QueryValue(value
, val
);
1296 printf("'%s'", val
.c_str());
1298 key
.QueryRawValue(value
, val
);
1299 printf(" (raw value '%s')", val
.c_str());
1304 cont
= key
.GetNextValue(value
, dummy
);
1308 static void TestRegistryAssociation()
1311 The second call to deleteself genertaes an error message, with a
1312 messagebox saying .flo is crucial to system operation, while the .ddf
1313 call also fails, but with no error message
1318 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1320 key
= "ddxf_auto_file" ;
1321 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1323 key
= "ddxf_auto_file" ;
1324 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1327 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1329 key
= "program \"%1\"" ;
1331 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
1333 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
1335 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
1337 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
1341 #endif // TEST_REGISTRY
1343 // ----------------------------------------------------------------------------
1345 // ----------------------------------------------------------------------------
1349 #include <wx/socket.h>
1350 #include <wx/protocol/protocol.h>
1351 #include <wx/protocol/http.h>
1353 static void TestSocketServer()
1355 puts("*** Testing wxSocketServer ***\n");
1357 static const int PORT
= 3000;
1362 wxSocketServer
*server
= new wxSocketServer(addr
);
1363 if ( !server
->Ok() )
1365 puts("ERROR: failed to bind");
1372 printf("Server: waiting for connection on port %d...\n", PORT
);
1374 wxSocketBase
*socket
= server
->Accept();
1377 puts("ERROR: wxSocketServer::Accept() failed.");
1381 puts("Server: got a client.");
1383 server
->SetTimeout(60); // 1 min
1385 while ( socket
->IsConnected() )
1391 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
1393 // don't log error if the client just close the connection
1394 if ( socket
->IsConnected() )
1396 puts("ERROR: in wxSocket::Read.");
1416 printf("Server: got '%s'.\n", s
.c_str());
1417 if ( s
== _T("bye") )
1424 socket
->Write(s
.MakeUpper().c_str(), s
.length());
1425 socket
->Write("\r\n", 2);
1426 printf("Server: wrote '%s'.\n", s
.c_str());
1429 puts("Server: lost a client.");
1434 // same as "delete server" but is consistent with GUI programs
1438 static void TestSocketClient()
1440 puts("*** Testing wxSocketClient ***\n");
1442 static const char *hostname
= "www.wxwindows.org";
1445 addr
.Hostname(hostname
);
1448 printf("--- Attempting to connect to %s:80...\n", hostname
);
1450 wxSocketClient client
;
1451 if ( !client
.Connect(addr
) )
1453 printf("ERROR: failed to connect to %s\n", hostname
);
1457 printf("--- Connected to %s:%u...\n",
1458 addr
.Hostname().c_str(), addr
.Service());
1462 // could use simply "GET" here I suppose
1464 wxString::Format("GET http://%s/\r\n", hostname
);
1465 client
.Write(cmdGet
, cmdGet
.length());
1466 printf("--- Sent command '%s' to the server\n",
1467 MakePrintable(cmdGet
).c_str());
1468 client
.Read(buf
, WXSIZEOF(buf
));
1469 printf("--- Server replied:\n%s", buf
);
1473 #endif // TEST_SOCKETS
1477 #include <wx/protocol/ftp.h>
1479 static void TestProtocolFtp()
1481 puts("*** Testing wxFTP download ***\n");
1485 static const char *hostname
= "ftp.wxwindows.org";
1486 static const char *directory
= "pub";
1488 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1490 static const char *hostname
= "localhost";
1491 static const char *user
= "zeitlin";
1492 static const char *directory
= "/tmp";
1495 ftp
.SetPassword("password");
1497 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1500 if ( !ftp
.Connect(hostname
) )
1502 printf("ERROR: failed to connect to %s\n", hostname
);
1506 printf("--- Connected to %s, current directory is '%s'\n",
1507 hostname
, ftp
.Pwd().c_str());
1510 if ( !ftp
.ChDir(directory
) )
1512 printf("ERROR: failed to cd to %s\n", directory
);
1515 // test NLIST and LIST
1516 wxArrayString files
;
1517 if ( !ftp
.GetFilesList(files
) )
1519 puts("ERROR: failed to get NLIST of files");
1523 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1524 size_t count
= files
.GetCount();
1525 for ( size_t n
= 0; n
< count
; n
++ )
1527 printf("\t%s\n", files
[n
].c_str());
1529 puts("End of the file list");
1532 if ( !ftp
.GetDirList(files
) )
1534 puts("ERROR: failed to get LIST of files");
1538 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1539 size_t count
= files
.GetCount();
1540 for ( size_t n
= 0; n
< count
; n
++ )
1542 printf("\t%s\n", files
[n
].c_str());
1544 puts("End of the file list");
1547 if ( !ftp
.ChDir(_T("..")) )
1549 puts("ERROR: failed to cd to ..");
1553 static const char *filename
= "welcome.msg";
1554 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1557 printf("ERROR: couldn't get input stream for %s\n", filename
);
1561 size_t size
= in
->StreamSize();
1562 printf("Reading file %s (%u bytes)...", filename
, size
);
1564 char *data
= new char[size
];
1565 if ( !in
->Read(data
, size
) )
1567 puts("ERROR: read error");
1571 printf("\nContents of %s:\n%s\n", filename
, data
);
1578 // test some other FTP commands
1579 if ( ftp
.SendCommand("STAT") != '2' )
1581 puts("ERROR: STAT failed");
1585 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1588 if ( ftp
.SendCommand("HELP SITE") != '2' )
1590 puts("ERROR: HELP SITE failed");
1594 printf("The list of site-specific commands:\n\n%s\n",
1595 ftp
.GetLastResult().c_str());
1600 static void TestProtocolFtpUpload()
1602 puts("*** Testing wxFTP uploading ***\n");
1604 static const char *hostname
= "localhost";
1606 printf("--- Attempting to connect to %s:21...\n", hostname
);
1609 ftp
.SetUser("zeitlin");
1610 ftp
.SetPassword("password");
1611 if ( !ftp
.Connect(hostname
) )
1613 printf("ERROR: failed to connect to %s\n", hostname
);
1617 printf("--- Connected to %s, current directory is '%s'\n",
1618 hostname
, ftp
.Pwd().c_str());
1621 static const char *file1
= "test1";
1622 static const char *file2
= "test2";
1623 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1626 printf("--- Uploading to %s ---\n", file1
);
1627 out
->Write("First hello", 11);
1631 // send a command to check the remote file
1632 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1634 printf("ERROR: STAT %s failed\n", file1
);
1638 printf("STAT %s returned:\n\n%s\n",
1639 file1
, ftp
.GetLastResult().c_str());
1642 out
= ftp
.GetOutputStream(file2
);
1645 printf("--- Uploading to %s ---\n", file1
);
1646 out
->Write("Second hello", 12);
1654 // ----------------------------------------------------------------------------
1656 // ----------------------------------------------------------------------------
1660 #include <wx/mstream.h>
1662 static void TestMemoryStream()
1664 puts("*** Testing wxMemoryInputStream ***");
1667 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1669 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1670 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1671 while ( !memInpStream
.Eof() )
1673 putchar(memInpStream
.GetC());
1676 puts("\n*** wxMemoryInputStream test done ***");
1679 #endif // TEST_STREAMS
1681 // ----------------------------------------------------------------------------
1683 // ----------------------------------------------------------------------------
1687 #include <wx/timer.h>
1688 #include <wx/utils.h>
1690 static void TestStopWatch()
1692 puts("*** Testing wxStopWatch ***\n");
1695 printf("Sleeping 3 seconds...");
1697 printf("\telapsed time: %ldms\n", sw
.Time());
1700 printf("Sleeping 2 more seconds...");
1702 printf("\telapsed time: %ldms\n", sw
.Time());
1705 printf("And 3 more seconds...");
1707 printf("\telapsed time: %ldms\n", sw
.Time());
1710 puts("\nChecking for 'backwards clock' bug...");
1711 for ( size_t n
= 0; n
< 70; n
++ )
1715 for ( size_t m
= 0; m
< 100000; m
++ )
1717 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1719 puts("\ntime is negative - ERROR!");
1729 #endif // TEST_TIMER
1731 // ----------------------------------------------------------------------------
1733 // ----------------------------------------------------------------------------
1737 #include <wx/vcard.h>
1739 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1742 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1746 wxString(_T('\t'), level
).c_str(),
1747 vcObj
->GetName().c_str());
1750 switch ( vcObj
->GetType() )
1752 case wxVCardObject::String
:
1753 case wxVCardObject::UString
:
1756 vcObj
->GetValue(&val
);
1757 value
<< _T('"') << val
<< _T('"');
1761 case wxVCardObject::Int
:
1764 vcObj
->GetValue(&i
);
1765 value
.Printf(_T("%u"), i
);
1769 case wxVCardObject::Long
:
1772 vcObj
->GetValue(&l
);
1773 value
.Printf(_T("%lu"), l
);
1777 case wxVCardObject::None
:
1780 case wxVCardObject::Object
:
1781 value
= _T("<node>");
1785 value
= _T("<unknown value type>");
1789 printf(" = %s", value
.c_str());
1792 DumpVObject(level
+ 1, *vcObj
);
1795 vcObj
= vcard
.GetNextProp(&cookie
);
1799 static void DumpVCardAddresses(const wxVCard
& vcard
)
1801 puts("\nShowing all addresses from vCard:\n");
1805 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1809 int flags
= addr
->GetFlags();
1810 if ( flags
& wxVCardAddress::Domestic
)
1812 flagsStr
<< _T("domestic ");
1814 if ( flags
& wxVCardAddress::Intl
)
1816 flagsStr
<< _T("international ");
1818 if ( flags
& wxVCardAddress::Postal
)
1820 flagsStr
<< _T("postal ");
1822 if ( flags
& wxVCardAddress::Parcel
)
1824 flagsStr
<< _T("parcel ");
1826 if ( flags
& wxVCardAddress::Home
)
1828 flagsStr
<< _T("home ");
1830 if ( flags
& wxVCardAddress::Work
)
1832 flagsStr
<< _T("work ");
1835 printf("Address %u:\n"
1837 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1840 addr
->GetPostOffice().c_str(),
1841 addr
->GetExtAddress().c_str(),
1842 addr
->GetStreet().c_str(),
1843 addr
->GetLocality().c_str(),
1844 addr
->GetRegion().c_str(),
1845 addr
->GetPostalCode().c_str(),
1846 addr
->GetCountry().c_str()
1850 addr
= vcard
.GetNextAddress(&cookie
);
1854 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
1856 puts("\nShowing all phone numbers from vCard:\n");
1860 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
1864 int flags
= phone
->GetFlags();
1865 if ( flags
& wxVCardPhoneNumber::Voice
)
1867 flagsStr
<< _T("voice ");
1869 if ( flags
& wxVCardPhoneNumber::Fax
)
1871 flagsStr
<< _T("fax ");
1873 if ( flags
& wxVCardPhoneNumber::Cellular
)
1875 flagsStr
<< _T("cellular ");
1877 if ( flags
& wxVCardPhoneNumber::Modem
)
1879 flagsStr
<< _T("modem ");
1881 if ( flags
& wxVCardPhoneNumber::Home
)
1883 flagsStr
<< _T("home ");
1885 if ( flags
& wxVCardPhoneNumber::Work
)
1887 flagsStr
<< _T("work ");
1890 printf("Phone number %u:\n"
1895 phone
->GetNumber().c_str()
1899 phone
= vcard
.GetNextPhoneNumber(&cookie
);
1903 static void TestVCardRead()
1905 puts("*** Testing wxVCard reading ***\n");
1907 wxVCard
vcard(_T("vcard.vcf"));
1908 if ( !vcard
.IsOk() )
1910 puts("ERROR: couldn't load vCard.");
1914 // read individual vCard properties
1915 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
1919 vcObj
->GetValue(&value
);
1924 value
= _T("<none>");
1927 printf("Full name retrieved directly: %s\n", value
.c_str());
1930 if ( !vcard
.GetFullName(&value
) )
1932 value
= _T("<none>");
1935 printf("Full name from wxVCard API: %s\n", value
.c_str());
1937 // now show how to deal with multiply occuring properties
1938 DumpVCardAddresses(vcard
);
1939 DumpVCardPhoneNumbers(vcard
);
1941 // and finally show all
1942 puts("\nNow dumping the entire vCard:\n"
1943 "-----------------------------\n");
1945 DumpVObject(0, vcard
);
1949 static void TestVCardWrite()
1951 puts("*** Testing wxVCard writing ***\n");
1954 if ( !vcard
.IsOk() )
1956 puts("ERROR: couldn't create vCard.");
1961 vcard
.SetName("Zeitlin", "Vadim");
1962 vcard
.SetFullName("Vadim Zeitlin");
1963 vcard
.SetOrganization("wxWindows", "R&D");
1965 // just dump the vCard back
1966 puts("Entire vCard follows:\n");
1967 puts(vcard
.Write());
1971 #endif // TEST_VCARD
1973 // ----------------------------------------------------------------------------
1974 // wide char (Unicode) support
1975 // ----------------------------------------------------------------------------
1979 #include <wx/strconv.h>
1980 #include <wx/buffer.h>
1982 static void TestUtf8()
1984 puts("*** Testing UTF8 support ***\n");
1986 wxString testString
= "français";
1988 "************ French - Français ****************"
1989 "Juste un petit exemple pour dire que les français aussi"
1990 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
1993 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
1994 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
1995 wxString
testString2(pwz
, wxConvLocal
);
1997 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
1999 char *psz
= "fran" "\xe7" "ais";
2000 size_t len
= strlen(psz
);
2001 wchar_t *pwz2
= new wchar_t[len
+ 1];
2002 for ( size_t n
= 0; n
<= len
; n
++ )
2004 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
2007 wxString
testString3(pwz2
, wxConvUTF8
);
2010 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
2013 #endif // TEST_WCHAR
2015 // ----------------------------------------------------------------------------
2017 // ----------------------------------------------------------------------------
2021 #include "wx/zipstrm.h"
2023 static void TestZipStreamRead()
2025 puts("*** Testing ZIP reading ***\n");
2027 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
2028 printf("Archive size: %u\n", istr
.GetSize());
2030 puts("Dumping the file:");
2031 while ( !istr
.Eof() )
2033 putchar(istr
.GetC());
2037 puts("\n----- done ------");
2042 // ----------------------------------------------------------------------------
2044 // ----------------------------------------------------------------------------
2048 #include <wx/zstream.h>
2049 #include <wx/wfstream.h>
2051 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2052 static const char *TEST_DATA
= "hello and hello again";
2054 static void TestZlibStreamWrite()
2056 puts("*** Testing Zlib stream reading ***\n");
2058 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2059 wxZlibOutputStream
ostr(fileOutStream
, 0);
2060 printf("Compressing the test string... ");
2061 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2064 puts("(ERROR: failed)");
2071 puts("\n----- done ------");
2074 static void TestZlibStreamRead()
2076 puts("*** Testing Zlib stream reading ***\n");
2078 wxFileInputStream
fileInStream(FILENAME_GZ
);
2079 wxZlibInputStream
istr(fileInStream
);
2080 printf("Archive size: %u\n", istr
.GetSize());
2082 puts("Dumping the file:");
2083 while ( !istr
.Eof() )
2085 putchar(istr
.GetC());
2089 puts("\n----- done ------");
2094 // ----------------------------------------------------------------------------
2096 // ----------------------------------------------------------------------------
2098 #ifdef TEST_DATETIME
2100 #include <wx/date.h>
2102 #include <wx/datetime.h>
2107 wxDateTime::wxDateTime_t day
;
2108 wxDateTime::Month month
;
2110 wxDateTime::wxDateTime_t hour
, min
, sec
;
2112 wxDateTime::WeekDay wday
;
2113 time_t gmticks
, ticks
;
2115 void Init(const wxDateTime::Tm
& tm
)
2124 gmticks
= ticks
= -1;
2127 wxDateTime
DT() const
2128 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2130 bool SameDay(const wxDateTime::Tm
& tm
) const
2132 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2135 wxString
Format() const
2138 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2140 wxDateTime::GetMonthName(month
).c_str(),
2142 abs(wxDateTime::ConvertYearToBC(year
)),
2143 year
> 0 ? "AD" : "BC");
2147 wxString
FormatDate() const
2150 s
.Printf("%02d-%s-%4d%s",
2152 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2153 abs(wxDateTime::ConvertYearToBC(year
)),
2154 year
> 0 ? "AD" : "BC");
2159 static const Date testDates
[] =
2161 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2162 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2163 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2164 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2165 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2166 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2167 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2168 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2169 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2170 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2171 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2172 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2173 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2174 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2175 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2178 // this test miscellaneous static wxDateTime functions
2179 static void TestTimeStatic()
2181 puts("\n*** wxDateTime static methods test ***");
2183 // some info about the current date
2184 int year
= wxDateTime::GetCurrentYear();
2185 printf("Current year %d is %sa leap one and has %d days.\n",
2187 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2188 wxDateTime::GetNumberOfDays(year
));
2190 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2191 printf("Current month is '%s' ('%s') and it has %d days\n",
2192 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2193 wxDateTime::GetMonthName(month
).c_str(),
2194 wxDateTime::GetNumberOfDays(month
));
2197 static const size_t nYears
= 5;
2198 static const size_t years
[2][nYears
] =
2200 // first line: the years to test
2201 { 1990, 1976, 2000, 2030, 1984, },
2203 // second line: TRUE if leap, FALSE otherwise
2204 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2207 for ( size_t n
= 0; n
< nYears
; n
++ )
2209 int year
= years
[0][n
];
2210 bool should
= years
[1][n
] != 0,
2211 is
= wxDateTime::IsLeapYear(year
);
2213 printf("Year %d is %sa leap year (%s)\n",
2216 should
== is
? "ok" : "ERROR");
2218 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2222 // test constructing wxDateTime objects
2223 static void TestTimeSet()
2225 puts("\n*** wxDateTime construction test ***");
2227 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2229 const Date
& d1
= testDates
[n
];
2230 wxDateTime dt
= d1
.DT();
2233 d2
.Init(dt
.GetTm());
2235 wxString s1
= d1
.Format(),
2238 printf("Date: %s == %s (%s)\n",
2239 s1
.c_str(), s2
.c_str(),
2240 s1
== s2
? "ok" : "ERROR");
2244 // test time zones stuff
2245 static void TestTimeZones()
2247 puts("\n*** wxDateTime timezone test ***");
2249 wxDateTime now
= wxDateTime::Now();
2251 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2252 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2253 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2254 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2255 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2256 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2258 wxDateTime::Tm tm
= now
.GetTm();
2259 if ( wxDateTime(tm
) != now
)
2261 printf("ERROR: got %s instead of %s\n",
2262 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2266 // test some minimal support for the dates outside the standard range
2267 static void TestTimeRange()
2269 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2271 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2273 printf("Unix epoch:\t%s\n",
2274 wxDateTime(2440587.5).Format(fmt
).c_str());
2275 printf("Feb 29, 0: \t%s\n",
2276 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2277 printf("JDN 0: \t%s\n",
2278 wxDateTime(0.0).Format(fmt
).c_str());
2279 printf("Jan 1, 1AD:\t%s\n",
2280 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2281 printf("May 29, 2099:\t%s\n",
2282 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2285 static void TestTimeTicks()
2287 puts("\n*** wxDateTime ticks test ***");
2289 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2291 const Date
& d
= testDates
[n
];
2292 if ( d
.ticks
== -1 )
2295 wxDateTime dt
= d
.DT();
2296 long ticks
= (dt
.GetValue() / 1000).ToLong();
2297 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2298 if ( ticks
== d
.ticks
)
2304 printf(" (ERROR: should be %ld, delta = %ld)\n",
2305 d
.ticks
, ticks
- d
.ticks
);
2308 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2309 ticks
= (dt
.GetValue() / 1000).ToLong();
2310 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2311 if ( ticks
== d
.gmticks
)
2317 printf(" (ERROR: should be %ld, delta = %ld)\n",
2318 d
.gmticks
, ticks
- d
.gmticks
);
2325 // test conversions to JDN &c
2326 static void TestTimeJDN()
2328 puts("\n*** wxDateTime to JDN test ***");
2330 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2332 const Date
& d
= testDates
[n
];
2333 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2334 double jdn
= dt
.GetJulianDayNumber();
2336 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2343 printf(" (ERROR: should be %f, delta = %f)\n",
2344 d
.jdn
, jdn
- d
.jdn
);
2349 // test week days computation
2350 static void TestTimeWDays()
2352 puts("\n*** wxDateTime weekday test ***");
2354 // test GetWeekDay()
2356 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2358 const Date
& d
= testDates
[n
];
2359 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2361 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2364 wxDateTime::GetWeekDayName(wday
).c_str());
2365 if ( wday
== d
.wday
)
2371 printf(" (ERROR: should be %s)\n",
2372 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2378 // test SetToWeekDay()
2379 struct WeekDateTestData
2381 Date date
; // the real date (precomputed)
2382 int nWeek
; // its week index in the month
2383 wxDateTime::WeekDay wday
; // the weekday
2384 wxDateTime::Month month
; // the month
2385 int year
; // and the year
2387 wxString
Format() const
2390 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2392 case 1: which
= "first"; break;
2393 case 2: which
= "second"; break;
2394 case 3: which
= "third"; break;
2395 case 4: which
= "fourth"; break;
2396 case 5: which
= "fifth"; break;
2398 case -1: which
= "last"; break;
2403 which
+= " from end";
2406 s
.Printf("The %s %s of %s in %d",
2408 wxDateTime::GetWeekDayName(wday
).c_str(),
2409 wxDateTime::GetMonthName(month
).c_str(),
2416 // the array data was generated by the following python program
2418 from DateTime import *
2419 from whrandom import *
2420 from string import *
2422 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2423 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2425 week = DateTimeDelta(7)
2428 year = randint(1900, 2100)
2429 month = randint(1, 12)
2430 day = randint(1, 28)
2431 dt = DateTime(year, month, day)
2432 wday = dt.day_of_week
2434 countFromEnd = choice([-1, 1])
2437 while dt.month is month:
2438 dt = dt - countFromEnd * week
2439 weekNum = weekNum + countFromEnd
2441 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2443 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2444 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2447 static const WeekDateTestData weekDatesTestData
[] =
2449 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2450 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2451 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2452 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2453 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2454 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2455 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2456 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2457 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2458 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2459 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2460 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2461 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2462 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2463 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2464 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2465 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2466 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2467 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2468 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2471 static const char *fmt
= "%d-%b-%Y";
2474 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2476 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2478 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2480 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2482 const Date
& d
= wd
.date
;
2483 if ( d
.SameDay(dt
.GetTm()) )
2489 dt
.Set(d
.day
, d
.month
, d
.year
);
2491 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2496 // test the computation of (ISO) week numbers
2497 static void TestTimeWNumber()
2499 puts("\n*** wxDateTime week number test ***");
2501 struct WeekNumberTestData
2503 Date date
; // the date
2504 wxDateTime::wxDateTime_t week
; // the week number in the year
2505 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2506 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2507 wxDateTime::wxDateTime_t dnum
; // day number in the year
2510 // data generated with the following python script:
2512 from DateTime import *
2513 from whrandom import *
2514 from string import *
2516 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2517 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2519 def GetMonthWeek(dt):
2520 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2521 if weekNumMonth < 0:
2522 weekNumMonth = weekNumMonth + 53
2525 def GetLastSundayBefore(dt):
2526 if dt.iso_week[2] == 7:
2529 return dt - DateTimeDelta(dt.iso_week[2])
2532 year = randint(1900, 2100)
2533 month = randint(1, 12)
2534 day = randint(1, 28)
2535 dt = DateTime(year, month, day)
2536 dayNum = dt.day_of_year
2537 weekNum = dt.iso_week[1]
2538 weekNumMonth = GetMonthWeek(dt)
2541 dtSunday = GetLastSundayBefore(dt)
2543 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2544 weekNumMonth2 = weekNumMonth2 + 1
2545 dtSunday = dtSunday - DateTimeDelta(7)
2547 data = { 'day': rjust(`day`, 2), \
2548 'month': monthNames[month - 1], \
2550 'weekNum': rjust(`weekNum`, 2), \
2551 'weekNumMonth': weekNumMonth, \
2552 'weekNumMonth2': weekNumMonth2, \
2553 'dayNum': rjust(`dayNum`, 3) }
2555 print " { { %(day)s, "\
2556 "wxDateTime::%(month)s, "\
2559 "%(weekNumMonth)s, "\
2560 "%(weekNumMonth2)s, "\
2561 "%(dayNum)s }," % data
2564 static const WeekNumberTestData weekNumberTestDates
[] =
2566 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2567 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2568 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2569 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2570 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2571 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2572 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2573 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2574 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2575 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2576 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2577 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2578 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2579 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2580 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2581 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2582 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2583 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2584 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2585 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2588 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2590 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2591 const Date
& d
= wn
.date
;
2593 wxDateTime dt
= d
.DT();
2595 wxDateTime::wxDateTime_t
2596 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2597 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2598 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2599 dnum
= dt
.GetDayOfYear();
2601 printf("%s: the day number is %d",
2602 d
.FormatDate().c_str(), dnum
);
2603 if ( dnum
== wn
.dnum
)
2609 printf(" (ERROR: should be %d)", wn
.dnum
);
2612 printf(", week in month is %d", wmon
);
2613 if ( wmon
== wn
.wmon
)
2619 printf(" (ERROR: should be %d)", wn
.wmon
);
2622 printf(" or %d", wmon2
);
2623 if ( wmon2
== wn
.wmon2
)
2629 printf(" (ERROR: should be %d)", wn
.wmon2
);
2632 printf(", week in year is %d", week
);
2633 if ( week
== wn
.week
)
2639 printf(" (ERROR: should be %d)\n", wn
.week
);
2644 // test DST calculations
2645 static void TestTimeDST()
2647 puts("\n*** wxDateTime DST test ***");
2649 printf("DST is%s in effect now.\n\n",
2650 wxDateTime::Now().IsDST() ? "" : " not");
2652 // taken from http://www.energy.ca.gov/daylightsaving.html
2653 static const Date datesDST
[2][2004 - 1900 + 1] =
2656 { 1, wxDateTime::Apr
, 1990 },
2657 { 7, wxDateTime::Apr
, 1991 },
2658 { 5, wxDateTime::Apr
, 1992 },
2659 { 4, wxDateTime::Apr
, 1993 },
2660 { 3, wxDateTime::Apr
, 1994 },
2661 { 2, wxDateTime::Apr
, 1995 },
2662 { 7, wxDateTime::Apr
, 1996 },
2663 { 6, wxDateTime::Apr
, 1997 },
2664 { 5, wxDateTime::Apr
, 1998 },
2665 { 4, wxDateTime::Apr
, 1999 },
2666 { 2, wxDateTime::Apr
, 2000 },
2667 { 1, wxDateTime::Apr
, 2001 },
2668 { 7, wxDateTime::Apr
, 2002 },
2669 { 6, wxDateTime::Apr
, 2003 },
2670 { 4, wxDateTime::Apr
, 2004 },
2673 { 28, wxDateTime::Oct
, 1990 },
2674 { 27, wxDateTime::Oct
, 1991 },
2675 { 25, wxDateTime::Oct
, 1992 },
2676 { 31, wxDateTime::Oct
, 1993 },
2677 { 30, wxDateTime::Oct
, 1994 },
2678 { 29, wxDateTime::Oct
, 1995 },
2679 { 27, wxDateTime::Oct
, 1996 },
2680 { 26, wxDateTime::Oct
, 1997 },
2681 { 25, wxDateTime::Oct
, 1998 },
2682 { 31, wxDateTime::Oct
, 1999 },
2683 { 29, wxDateTime::Oct
, 2000 },
2684 { 28, wxDateTime::Oct
, 2001 },
2685 { 27, wxDateTime::Oct
, 2002 },
2686 { 26, wxDateTime::Oct
, 2003 },
2687 { 31, wxDateTime::Oct
, 2004 },
2692 for ( year
= 1990; year
< 2005; year
++ )
2694 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2695 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2697 printf("DST period in the US for year %d: from %s to %s",
2698 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2700 size_t n
= year
- 1990;
2701 const Date
& dBegin
= datesDST
[0][n
];
2702 const Date
& dEnd
= datesDST
[1][n
];
2704 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2710 printf(" (ERROR: should be %s %d to %s %d)\n",
2711 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2712 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2718 for ( year
= 1990; year
< 2005; year
++ )
2720 printf("DST period in Europe for year %d: from %s to %s\n",
2722 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2723 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2727 // test wxDateTime -> text conversion
2728 static void TestTimeFormat()
2730 puts("\n*** wxDateTime formatting test ***");
2732 // some information may be lost during conversion, so store what kind
2733 // of info should we recover after a round trip
2736 CompareNone
, // don't try comparing
2737 CompareBoth
, // dates and times should be identical
2738 CompareDate
, // dates only
2739 CompareTime
// time only
2744 CompareKind compareKind
;
2746 } formatTestFormats
[] =
2748 { CompareBoth
, "---> %c" },
2749 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2750 { CompareBoth
, "Date is %x, time is %X" },
2751 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2752 { CompareNone
, "The day of year: %j, the week of year: %W" },
2753 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2756 static const Date formatTestDates
[] =
2758 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2759 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2761 // this test can't work for other centuries because it uses two digit
2762 // years in formats, so don't even try it
2763 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2764 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2765 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2769 // an extra test (as it doesn't depend on date, don't do it in the loop)
2770 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2772 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2776 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2777 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2779 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2780 printf("%s", s
.c_str());
2782 // what can we recover?
2783 int kind
= formatTestFormats
[n
].compareKind
;
2787 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2790 // converion failed - should it have?
2791 if ( kind
== CompareNone
)
2794 puts(" (ERROR: conversion back failed)");
2798 // should have parsed the entire string
2799 puts(" (ERROR: conversion back stopped too soon)");
2803 bool equal
= FALSE
; // suppress compilaer warning
2811 equal
= dt
.IsSameDate(dt2
);
2815 equal
= dt
.IsSameTime(dt2
);
2821 printf(" (ERROR: got back '%s' instead of '%s')\n",
2822 dt2
.Format().c_str(), dt
.Format().c_str());
2833 // test text -> wxDateTime conversion
2834 static void TestTimeParse()
2836 puts("\n*** wxDateTime parse test ***");
2838 struct ParseTestData
2845 static const ParseTestData parseTestDates
[] =
2847 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
2848 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
2851 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
2853 const char *format
= parseTestDates
[n
].format
;
2855 printf("%s => ", format
);
2858 if ( dt
.ParseRfc822Date(format
) )
2860 printf("%s ", dt
.Format().c_str());
2862 if ( parseTestDates
[n
].good
)
2864 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
2871 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
2876 puts("(ERROR: bad format)");
2881 printf("bad format (%s)\n",
2882 parseTestDates
[n
].good
? "ERROR" : "ok");
2887 static void TestInteractive()
2889 puts("\n*** interactive wxDateTime tests ***");
2895 printf("Enter a date: ");
2896 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2899 // kill the last '\n'
2900 buf
[strlen(buf
) - 1] = 0;
2903 const char *p
= dt
.ParseDate(buf
);
2906 printf("ERROR: failed to parse the date '%s'.\n", buf
);
2912 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
2915 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2916 dt
.Format("%b %d, %Y").c_str(),
2918 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2919 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2920 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
2923 puts("\n*** done ***");
2926 static void TestTimeMS()
2928 puts("*** testing millisecond-resolution support in wxDateTime ***");
2930 wxDateTime dt1
= wxDateTime::Now(),
2931 dt2
= wxDateTime::UNow();
2933 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
2934 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2935 printf("Dummy loop: ");
2936 for ( int i
= 0; i
< 6000; i
++ )
2938 //for ( int j = 0; j < 10; j++ )
2941 s
.Printf("%g", sqrt(i
));
2950 dt2
= wxDateTime::UNow();
2951 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2953 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
2955 puts("\n*** done ***");
2958 static void TestTimeArithmetics()
2960 puts("\n*** testing arithmetic operations on wxDateTime ***");
2962 static const struct ArithmData
2964 ArithmData(const wxDateSpan
& sp
, const char *nam
)
2965 : span(sp
), name(nam
) { }
2969 } testArithmData
[] =
2971 ArithmData(wxDateSpan::Day(), "day"),
2972 ArithmData(wxDateSpan::Week(), "week"),
2973 ArithmData(wxDateSpan::Month(), "month"),
2974 ArithmData(wxDateSpan::Year(), "year"),
2975 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
2978 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
2980 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
2982 wxDateSpan span
= testArithmData
[n
].span
;
2986 const char *name
= testArithmData
[n
].name
;
2987 printf("%s + %s = %s, %s - %s = %s\n",
2988 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
2989 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
2991 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
2992 if ( dt1
- span
== dt
)
2998 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3001 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3002 if ( dt2
+ span
== dt
)
3008 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3011 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3012 if ( dt2
+ 2*span
== dt1
)
3018 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3025 static void TestTimeHolidays()
3027 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3029 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3030 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3031 dtEnd
= dtStart
.GetLastMonthDay();
3033 wxDateTimeArray hol
;
3034 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3036 const wxChar
*format
= "%d-%b-%Y (%a)";
3038 printf("All holidays between %s and %s:\n",
3039 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3041 size_t count
= hol
.GetCount();
3042 for ( size_t n
= 0; n
< count
; n
++ )
3044 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3050 static void TestTimeZoneBug()
3052 puts("\n*** testing for DST/timezone bug ***\n");
3054 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3055 for ( int i
= 0; i
< 31; i
++ )
3057 printf("Date %s: week day %s.\n",
3058 date
.Format(_T("%d-%m-%Y")).c_str(),
3059 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3061 date
+= wxDateSpan::Day();
3069 // test compatibility with the old wxDate/wxTime classes
3070 static void TestTimeCompatibility()
3072 puts("\n*** wxDateTime compatibility test ***");
3074 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3075 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3077 double jdnNow
= wxDateTime::Now().GetJDN();
3078 long jdnMidnight
= (long)(jdnNow
- 0.5);
3079 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3081 jdnMidnight
= wxDate().Set().GetJulianDate();
3082 printf("wxDateTime for today: %s\n",
3083 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3085 int flags
= wxEUROPEAN
;//wxFULL;
3088 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3089 for ( int n
= 0; n
< 7; n
++ )
3091 printf("Previous %s is %s\n",
3092 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3093 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3099 #endif // TEST_DATETIME
3101 // ----------------------------------------------------------------------------
3103 // ----------------------------------------------------------------------------
3107 #include <wx/thread.h>
3109 static size_t gs_counter
= (size_t)-1;
3110 static wxCriticalSection gs_critsect
;
3111 static wxCondition gs_cond
;
3113 class MyJoinableThread
: public wxThread
3116 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3117 { m_n
= n
; Create(); }
3119 // thread execution starts here
3120 virtual ExitCode
Entry();
3126 wxThread::ExitCode
MyJoinableThread::Entry()
3128 unsigned long res
= 1;
3129 for ( size_t n
= 1; n
< m_n
; n
++ )
3133 // it's a loooong calculation :-)
3137 return (ExitCode
)res
;
3140 class MyDetachedThread
: public wxThread
3143 MyDetachedThread(size_t n
, char ch
)
3147 m_cancelled
= FALSE
;
3152 // thread execution starts here
3153 virtual ExitCode
Entry();
3156 virtual void OnExit();
3159 size_t m_n
; // number of characters to write
3160 char m_ch
; // character to write
3162 bool m_cancelled
; // FALSE if we exit normally
3165 wxThread::ExitCode
MyDetachedThread::Entry()
3168 wxCriticalSectionLocker
lock(gs_critsect
);
3169 if ( gs_counter
== (size_t)-1 )
3175 for ( size_t n
= 0; n
< m_n
; n
++ )
3177 if ( TestDestroy() )
3187 wxThread::Sleep(100);
3193 void MyDetachedThread::OnExit()
3195 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3197 wxCriticalSectionLocker
lock(gs_critsect
);
3198 if ( !--gs_counter
&& !m_cancelled
)
3202 void TestDetachedThreads()
3204 puts("\n*** Testing detached threads ***");
3206 static const size_t nThreads
= 3;
3207 MyDetachedThread
*threads
[nThreads
];
3209 for ( n
= 0; n
< nThreads
; n
++ )
3211 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3214 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3215 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3217 for ( n
= 0; n
< nThreads
; n
++ )
3222 // wait until all threads terminate
3228 void TestJoinableThreads()
3230 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3232 // calc 10! in the background
3233 MyJoinableThread
thread(10);
3236 printf("\nThread terminated with exit code %lu.\n",
3237 (unsigned long)thread
.Wait());
3240 void TestThreadSuspend()
3242 puts("\n*** Testing thread suspend/resume functions ***");
3244 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3248 // this is for this demo only, in a real life program we'd use another
3249 // condition variable which would be signaled from wxThread::Entry() to
3250 // tell us that the thread really started running - but here just wait a
3251 // bit and hope that it will be enough (the problem is, of course, that
3252 // the thread might still not run when we call Pause() which will result
3254 wxThread::Sleep(300);
3256 for ( size_t n
= 0; n
< 3; n
++ )
3260 puts("\nThread suspended");
3263 // don't sleep but resume immediately the first time
3264 wxThread::Sleep(300);
3266 puts("Going to resume the thread");
3271 puts("Waiting until it terminates now");
3273 // wait until the thread terminates
3279 void TestThreadDelete()
3281 // As above, using Sleep() is only for testing here - we must use some
3282 // synchronisation object instead to ensure that the thread is still
3283 // running when we delete it - deleting a detached thread which already
3284 // terminated will lead to a crash!
3286 puts("\n*** Testing thread delete function ***");
3288 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3292 puts("\nDeleted a thread which didn't start to run yet.");
3294 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3298 wxThread::Sleep(300);
3302 puts("\nDeleted a running thread.");
3304 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3308 wxThread::Sleep(300);
3314 puts("\nDeleted a sleeping thread.");
3316 MyJoinableThread
thread3(20);
3321 puts("\nDeleted a joinable thread.");
3323 MyJoinableThread
thread4(2);
3326 wxThread::Sleep(300);
3330 puts("\nDeleted a joinable thread which already terminated.");
3335 #endif // TEST_THREADS
3337 // ----------------------------------------------------------------------------
3339 // ----------------------------------------------------------------------------
3343 static void PrintArray(const char* name
, const wxArrayString
& array
)
3345 printf("Dump of the array '%s'\n", name
);
3347 size_t nCount
= array
.GetCount();
3348 for ( size_t n
= 0; n
< nCount
; n
++ )
3350 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3354 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3356 printf("Dump of the array '%s'\n", name
);
3358 size_t nCount
= array
.GetCount();
3359 for ( size_t n
= 0; n
< nCount
; n
++ )
3361 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3365 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3366 const wxString
& second
)
3368 return first
.length() - second
.length();
3371 int wxCMPFUNC_CONV
IntCompare(int *first
,
3374 return *first
- *second
;
3377 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3380 return *second
- *first
;
3383 static void TestArrayOfInts()
3385 puts("*** Testing wxArrayInt ***\n");
3396 puts("After sort:");
3400 puts("After reverse sort:");
3401 a
.Sort(IntRevCompare
);
3405 #include "wx/dynarray.h"
3407 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3408 #include "wx/arrimpl.cpp"
3409 WX_DEFINE_OBJARRAY(ArrayBars
);
3411 static void TestArrayOfObjects()
3413 puts("*** Testing wxObjArray ***\n");
3417 Bar
bar("second bar");
3419 printf("Initially: %u objects in the array, %u objects total.\n",
3420 bars
.GetCount(), Bar::GetNumber());
3422 bars
.Add(new Bar("first bar"));
3425 printf("Now: %u objects in the array, %u objects total.\n",
3426 bars
.GetCount(), Bar::GetNumber());
3430 printf("After Empty(): %u objects in the array, %u objects total.\n",
3431 bars
.GetCount(), Bar::GetNumber());
3434 printf("Finally: no more objects in the array, %u objects total.\n",
3438 #endif // TEST_ARRAYS
3440 // ----------------------------------------------------------------------------
3442 // ----------------------------------------------------------------------------
3446 #include "wx/timer.h"
3447 #include "wx/tokenzr.h"
3449 static void TestStringConstruction()
3451 puts("*** Testing wxString constructores ***");
3453 #define TEST_CTOR(args, res) \
3456 printf("wxString%s = %s ", #args, s.c_str()); \
3463 printf("(ERROR: should be %s)\n", res); \
3467 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3468 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3469 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3470 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3472 static const wxChar
*s
= _T("?really!");
3473 const wxChar
*start
= wxStrchr(s
, _T('r'));
3474 const wxChar
*end
= wxStrchr(s
, _T('!'));
3475 TEST_CTOR((start
, end
), _T("really"));
3480 static void TestString()
3490 for (int i
= 0; i
< 1000000; ++i
)
3494 c
= "! How'ya doin'?";
3497 c
= "Hello world! What's up?";
3502 printf ("TestString elapsed time: %ld\n", sw
.Time());
3505 static void TestPChar()
3513 for (int i
= 0; i
< 1000000; ++i
)
3515 strcpy (a
, "Hello");
3516 strcpy (b
, " world");
3517 strcpy (c
, "! How'ya doin'?");
3520 strcpy (c
, "Hello world! What's up?");
3521 if (strcmp (c
, a
) == 0)
3525 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3528 static void TestStringSub()
3530 wxString
s("Hello, world!");
3532 puts("*** Testing wxString substring extraction ***");
3534 printf("String = '%s'\n", s
.c_str());
3535 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3536 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3537 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3538 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3539 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3540 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3542 static const wxChar
*prefixes
[] =
3546 _T("Hello, world!"),
3547 _T("Hello, world!!!"),
3553 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3555 wxString prefix
= prefixes
[n
], rest
;
3556 bool rc
= s
.StartsWith(prefix
, &rest
);
3557 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3560 printf(" (the rest is '%s')\n", rest
.c_str());
3571 static void TestStringFormat()
3573 puts("*** Testing wxString formatting ***");
3576 s
.Printf("%03d", 18);
3578 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3579 printf("Number 18: %s\n", s
.c_str());
3584 // returns "not found" for npos, value for all others
3585 static wxString
PosToString(size_t res
)
3587 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3588 : wxString::Format(_T("%u"), res
);
3592 static void TestStringFind()
3594 puts("*** Testing wxString find() functions ***");
3596 static const wxChar
*strToFind
= _T("ell");
3597 static const struct StringFindTest
3601 result
; // of searching "ell" in str
3604 { _T("Well, hello world"), 0, 1 },
3605 { _T("Well, hello world"), 6, 7 },
3606 { _T("Well, hello world"), 9, wxString::npos
},
3609 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3611 const StringFindTest
& ft
= findTestData
[n
];
3612 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3614 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3615 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3617 size_t resTrue
= ft
.result
;
3618 if ( res
== resTrue
)
3624 printf(_T("(ERROR: should be %s)\n"),
3625 PosToString(resTrue
).c_str());
3632 static void TestStringTokenizer()
3634 puts("*** Testing wxStringTokenizer ***");
3636 static const wxChar
*modeNames
[] =
3640 _T("return all empty"),
3645 static const struct StringTokenizerTest
3647 const wxChar
*str
; // string to tokenize
3648 const wxChar
*delims
; // delimiters to use
3649 size_t count
; // count of token
3650 wxStringTokenizerMode mode
; // how should we tokenize it
3651 } tokenizerTestData
[] =
3653 { _T(""), _T(" "), 0 },
3654 { _T("Hello, world"), _T(" "), 2 },
3655 { _T("Hello, world "), _T(" "), 2 },
3656 { _T("Hello, world"), _T(","), 2 },
3657 { _T("Hello, world!"), _T(",!"), 2 },
3658 { _T("Hello,, world!"), _T(",!"), 3 },
3659 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3660 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3661 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3662 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3663 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3664 { _T("01/02/99"), _T("/-"), 3 },
3665 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3668 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3670 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3671 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3673 size_t count
= tkz
.CountTokens();
3674 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3675 MakePrintable(tt
.str
).c_str(),
3677 MakePrintable(tt
.delims
).c_str(),
3678 modeNames
[tkz
.GetMode()]);
3679 if ( count
== tt
.count
)
3685 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3690 // if we emulate strtok(), check that we do it correctly
3691 wxChar
*buf
, *s
= NULL
, *last
;
3693 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3695 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3696 wxStrcpy(buf
, tt
.str
);
3698 s
= wxStrtok(buf
, tt
.delims
, &last
);
3705 // now show the tokens themselves
3707 while ( tkz
.HasMoreTokens() )
3709 wxString token
= tkz
.GetNextToken();
3711 printf(_T("\ttoken %u: '%s'"),
3713 MakePrintable(token
).c_str());
3723 printf(" (ERROR: should be %s)\n", s
);
3726 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3730 // nothing to compare with
3735 if ( count2
!= count
)
3737 puts(_T("\tERROR: token count mismatch"));
3746 static void TestStringReplace()
3748 puts("*** Testing wxString::replace ***");
3750 static const struct StringReplaceTestData
3752 const wxChar
*original
; // original test string
3753 size_t start
, len
; // the part to replace
3754 const wxChar
*replacement
; // the replacement string
3755 const wxChar
*result
; // and the expected result
3756 } stringReplaceTestData
[] =
3758 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3759 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3760 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3761 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3762 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3765 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3767 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3769 wxString original
= data
.original
;
3770 original
.replace(data
.start
, data
.len
, data
.replacement
);
3772 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3773 data
.original
, data
.start
, data
.len
, data
.replacement
,
3776 if ( original
== data
.result
)
3782 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3789 #endif // TEST_STRINGS
3791 // ----------------------------------------------------------------------------
3793 // ----------------------------------------------------------------------------
3795 int main(int argc
, char **argv
)
3797 if ( !wxInitialize() )
3799 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3803 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3805 #endif // TEST_USLEEP
3808 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3810 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3811 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3813 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3814 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3815 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3816 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3818 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
3819 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
3824 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
3826 parser
.AddOption("project_name", "", "full path to project file",
3827 wxCMD_LINE_VAL_STRING
,
3828 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
3830 switch ( parser
.Parse() )
3833 wxLogMessage("Help was given, terminating.");
3837 ShowCmdLine(parser
);
3841 wxLogMessage("Syntax error detected, aborting.");
3844 #endif // TEST_CMDLINE
3855 TestStringConstruction();
3858 TestStringTokenizer();
3859 TestStringReplace();
3861 #endif // TEST_STRINGS
3874 puts("*** Initially:");
3876 PrintArray("a1", a1
);
3878 wxArrayString
a2(a1
);
3879 PrintArray("a2", a2
);
3881 wxSortedArrayString
a3(a1
);
3882 PrintArray("a3", a3
);
3884 puts("*** After deleting a string from a1");
3887 PrintArray("a1", a1
);
3888 PrintArray("a2", a2
);
3889 PrintArray("a3", a3
);
3891 puts("*** After reassigning a1 to a2 and a3");
3893 PrintArray("a2", a2
);
3894 PrintArray("a3", a3
);
3896 puts("*** After sorting a1");
3898 PrintArray("a1", a1
);
3900 puts("*** After sorting a1 in reverse order");
3902 PrintArray("a1", a1
);
3904 puts("*** After sorting a1 by the string length");
3905 a1
.Sort(StringLenCompare
);
3906 PrintArray("a1", a1
);
3908 TestArrayOfObjects();
3911 #endif // TEST_ARRAYS
3917 #ifdef TEST_DLLLOADER
3919 #endif // TEST_DLLLOADER
3923 #endif // TEST_ENVIRON
3927 #endif // TEST_EXECUTE
3929 #ifdef TEST_FILECONF
3931 #endif // TEST_FILECONF
3939 for ( size_t n
= 0; n
< 8000; n
++ )
3941 s
<< (char)('A' + (n
% 26));
3945 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
3947 // this one shouldn't be truncated
3950 // but this one will because log functions use fixed size buffer
3951 // (note that it doesn't need '\n' at the end neither - will be added
3953 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
3965 #ifdef TEST_FILENAME
3966 TestFileNameConstruction();
3967 #endif // TEST_FILENAME
3970 int nCPUs
= wxThread::GetCPUCount();
3971 printf("This system has %d CPUs\n", nCPUs
);
3973 wxThread::SetConcurrency(nCPUs
);
3975 if ( argc
> 1 && argv
[1][0] == 't' )
3976 wxLog::AddTraceMask("thread");
3979 TestDetachedThreads();
3981 TestJoinableThreads();
3983 TestThreadSuspend();
3987 #endif // TEST_THREADS
3989 #ifdef TEST_LONGLONG
3990 // seed pseudo random generator
3991 srand((unsigned)time(NULL
));
3999 TestMultiplication();
4002 TestLongLongConversion();
4003 TestBitOperations();
4005 TestLongLongComparison();
4006 #endif // TEST_LONGLONG
4013 wxLog::AddTraceMask(_T("mime"));
4020 TestMimeAssociate();
4023 #ifdef TEST_INFO_FUNCTIONS
4026 #endif // TEST_INFO_FUNCTIONS
4028 #ifdef TEST_REGISTRY
4031 TestRegistryAssociation();
4032 #endif // TEST_REGISTRY
4040 #endif // TEST_SOCKETS
4043 wxLog::AddTraceMask(_T("ftp"));
4046 TestProtocolFtpUpload();
4051 #endif // TEST_STREAMS
4055 #endif // TEST_TIMER
4057 #ifdef TEST_DATETIME
4070 TestTimeArithmetics();
4079 #endif // TEST_DATETIME
4085 #endif // TEST_VCARD
4089 #endif // TEST_WCHAR
4092 TestZipStreamRead();
4097 TestZlibStreamWrite();
4098 TestZlibStreamRead();