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
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 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
], wxPATH_UNIX
);
615 printf("Filename: '%s'\t", fn
.GetFullPath().c_str());
616 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), wxPATH_UNIX
) )
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 #ifdef TEST_WUFTPD // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
1486 static const char *hostname
= "ftp.eudora.com";
1487 if ( !ftp
.Connect(hostname
) )
1489 printf("ERROR: failed to connect to %s\n", hostname
);
1493 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
1494 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1497 printf("ERROR: couldn't get input stream for %s\n", filename
);
1501 size_t size
= in
->StreamSize();
1502 printf("Reading file %s (%u bytes)...", filename
, size
);
1504 char *data
= new char[size
];
1505 if ( !in
->Read(data
, size
) )
1507 puts("ERROR: read error");
1511 printf("Successfully retrieved the file.\n");
1518 #else // !TEST_WUFTPD
1521 static const char *hostname
= "ftp.wxwindows.org";
1522 static const char *directory
= "pub";
1523 static const char *filename
= "welcome.msg";
1525 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
1527 static const char *hostname
= "localhost";
1528 static const char *user
= "zeitlin";
1529 static const char *directory
= "/tmp";
1532 ftp
.SetPassword("password");
1534 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
1537 if ( !ftp
.Connect(hostname
) )
1539 printf("ERROR: failed to connect to %s\n", hostname
);
1543 printf("--- Connected to %s, current directory is '%s'\n",
1544 hostname
, ftp
.Pwd().c_str());
1547 if ( !ftp
.ChDir(directory
) )
1549 printf("ERROR: failed to cd to %s\n", directory
);
1552 // test NLIST and LIST
1553 wxArrayString files
;
1554 if ( !ftp
.GetFilesList(files
) )
1556 puts("ERROR: failed to get NLIST of files");
1560 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
1561 size_t count
= files
.GetCount();
1562 for ( size_t n
= 0; n
< count
; n
++ )
1564 printf("\t%s\n", files
[n
].c_str());
1566 puts("End of the file list");
1569 if ( !ftp
.GetDirList(files
) )
1571 puts("ERROR: failed to get LIST of files");
1575 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
1576 size_t count
= files
.GetCount();
1577 for ( size_t n
= 0; n
< count
; n
++ )
1579 printf("\t%s\n", files
[n
].c_str());
1581 puts("End of the file list");
1584 if ( !ftp
.ChDir(_T("..")) )
1586 puts("ERROR: failed to cd to ..");
1590 wxInputStream
*in
= ftp
.GetInputStream(filename
);
1593 printf("ERROR: couldn't get input stream for %s\n", filename
);
1597 size_t size
= in
->StreamSize();
1598 printf("Reading file %s (%u bytes)...", filename
, size
);
1600 char *data
= new char[size
];
1601 if ( !in
->Read(data
, size
) )
1603 puts("ERROR: read error");
1607 printf("\nContents of %s:\n%s\n", filename
, data
);
1614 // test some other FTP commands
1615 if ( ftp
.SendCommand("STAT") != '2' )
1617 puts("ERROR: STAT failed");
1621 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
1624 if ( ftp
.SendCommand("HELP SITE") != '2' )
1626 puts("ERROR: HELP SITE failed");
1630 printf("The list of site-specific commands:\n\n%s\n",
1631 ftp
.GetLastResult().c_str());
1634 #endif // TEST_WUFTPD/!TEST_WUFTPD
1637 static void TestProtocolFtpUpload()
1639 puts("*** Testing wxFTP uploading ***\n");
1641 static const char *hostname
= "localhost";
1643 printf("--- Attempting to connect to %s:21...\n", hostname
);
1646 ftp
.SetUser("zeitlin");
1647 ftp
.SetPassword("password");
1648 if ( !ftp
.Connect(hostname
) )
1650 printf("ERROR: failed to connect to %s\n", hostname
);
1654 printf("--- Connected to %s, current directory is '%s'\n",
1655 hostname
, ftp
.Pwd().c_str());
1658 static const char *file1
= "test1";
1659 static const char *file2
= "test2";
1660 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
1663 printf("--- Uploading to %s ---\n", file1
);
1664 out
->Write("First hello", 11);
1668 // send a command to check the remote file
1669 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
1671 printf("ERROR: STAT %s failed\n", file1
);
1675 printf("STAT %s returned:\n\n%s\n",
1676 file1
, ftp
.GetLastResult().c_str());
1679 out
= ftp
.GetOutputStream(file2
);
1682 printf("--- Uploading to %s ---\n", file1
);
1683 out
->Write("Second hello", 12);
1691 // ----------------------------------------------------------------------------
1693 // ----------------------------------------------------------------------------
1697 #include <wx/mstream.h>
1699 static void TestMemoryStream()
1701 puts("*** Testing wxMemoryInputStream ***");
1704 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
1706 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
1707 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
1708 while ( !memInpStream
.Eof() )
1710 putchar(memInpStream
.GetC());
1713 puts("\n*** wxMemoryInputStream test done ***");
1716 #endif // TEST_STREAMS
1718 // ----------------------------------------------------------------------------
1720 // ----------------------------------------------------------------------------
1724 #include <wx/timer.h>
1725 #include <wx/utils.h>
1727 static void TestStopWatch()
1729 puts("*** Testing wxStopWatch ***\n");
1732 printf("Sleeping 3 seconds...");
1734 printf("\telapsed time: %ldms\n", sw
.Time());
1737 printf("Sleeping 2 more seconds...");
1739 printf("\telapsed time: %ldms\n", sw
.Time());
1742 printf("And 3 more seconds...");
1744 printf("\telapsed time: %ldms\n", sw
.Time());
1747 puts("\nChecking for 'backwards clock' bug...");
1748 for ( size_t n
= 0; n
< 70; n
++ )
1752 for ( size_t m
= 0; m
< 100000; m
++ )
1754 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
1756 puts("\ntime is negative - ERROR!");
1766 #endif // TEST_TIMER
1768 // ----------------------------------------------------------------------------
1770 // ----------------------------------------------------------------------------
1774 #include <wx/vcard.h>
1776 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
1779 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
1783 wxString(_T('\t'), level
).c_str(),
1784 vcObj
->GetName().c_str());
1787 switch ( vcObj
->GetType() )
1789 case wxVCardObject::String
:
1790 case wxVCardObject::UString
:
1793 vcObj
->GetValue(&val
);
1794 value
<< _T('"') << val
<< _T('"');
1798 case wxVCardObject::Int
:
1801 vcObj
->GetValue(&i
);
1802 value
.Printf(_T("%u"), i
);
1806 case wxVCardObject::Long
:
1809 vcObj
->GetValue(&l
);
1810 value
.Printf(_T("%lu"), l
);
1814 case wxVCardObject::None
:
1817 case wxVCardObject::Object
:
1818 value
= _T("<node>");
1822 value
= _T("<unknown value type>");
1826 printf(" = %s", value
.c_str());
1829 DumpVObject(level
+ 1, *vcObj
);
1832 vcObj
= vcard
.GetNextProp(&cookie
);
1836 static void DumpVCardAddresses(const wxVCard
& vcard
)
1838 puts("\nShowing all addresses from vCard:\n");
1842 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
1846 int flags
= addr
->GetFlags();
1847 if ( flags
& wxVCardAddress::Domestic
)
1849 flagsStr
<< _T("domestic ");
1851 if ( flags
& wxVCardAddress::Intl
)
1853 flagsStr
<< _T("international ");
1855 if ( flags
& wxVCardAddress::Postal
)
1857 flagsStr
<< _T("postal ");
1859 if ( flags
& wxVCardAddress::Parcel
)
1861 flagsStr
<< _T("parcel ");
1863 if ( flags
& wxVCardAddress::Home
)
1865 flagsStr
<< _T("home ");
1867 if ( flags
& wxVCardAddress::Work
)
1869 flagsStr
<< _T("work ");
1872 printf("Address %u:\n"
1874 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
1877 addr
->GetPostOffice().c_str(),
1878 addr
->GetExtAddress().c_str(),
1879 addr
->GetStreet().c_str(),
1880 addr
->GetLocality().c_str(),
1881 addr
->GetRegion().c_str(),
1882 addr
->GetPostalCode().c_str(),
1883 addr
->GetCountry().c_str()
1887 addr
= vcard
.GetNextAddress(&cookie
);
1891 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
1893 puts("\nShowing all phone numbers from vCard:\n");
1897 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
1901 int flags
= phone
->GetFlags();
1902 if ( flags
& wxVCardPhoneNumber::Voice
)
1904 flagsStr
<< _T("voice ");
1906 if ( flags
& wxVCardPhoneNumber::Fax
)
1908 flagsStr
<< _T("fax ");
1910 if ( flags
& wxVCardPhoneNumber::Cellular
)
1912 flagsStr
<< _T("cellular ");
1914 if ( flags
& wxVCardPhoneNumber::Modem
)
1916 flagsStr
<< _T("modem ");
1918 if ( flags
& wxVCardPhoneNumber::Home
)
1920 flagsStr
<< _T("home ");
1922 if ( flags
& wxVCardPhoneNumber::Work
)
1924 flagsStr
<< _T("work ");
1927 printf("Phone number %u:\n"
1932 phone
->GetNumber().c_str()
1936 phone
= vcard
.GetNextPhoneNumber(&cookie
);
1940 static void TestVCardRead()
1942 puts("*** Testing wxVCard reading ***\n");
1944 wxVCard
vcard(_T("vcard.vcf"));
1945 if ( !vcard
.IsOk() )
1947 puts("ERROR: couldn't load vCard.");
1951 // read individual vCard properties
1952 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
1956 vcObj
->GetValue(&value
);
1961 value
= _T("<none>");
1964 printf("Full name retrieved directly: %s\n", value
.c_str());
1967 if ( !vcard
.GetFullName(&value
) )
1969 value
= _T("<none>");
1972 printf("Full name from wxVCard API: %s\n", value
.c_str());
1974 // now show how to deal with multiply occuring properties
1975 DumpVCardAddresses(vcard
);
1976 DumpVCardPhoneNumbers(vcard
);
1978 // and finally show all
1979 puts("\nNow dumping the entire vCard:\n"
1980 "-----------------------------\n");
1982 DumpVObject(0, vcard
);
1986 static void TestVCardWrite()
1988 puts("*** Testing wxVCard writing ***\n");
1991 if ( !vcard
.IsOk() )
1993 puts("ERROR: couldn't create vCard.");
1998 vcard
.SetName("Zeitlin", "Vadim");
1999 vcard
.SetFullName("Vadim Zeitlin");
2000 vcard
.SetOrganization("wxWindows", "R&D");
2002 // just dump the vCard back
2003 puts("Entire vCard follows:\n");
2004 puts(vcard
.Write());
2008 #endif // TEST_VCARD
2010 // ----------------------------------------------------------------------------
2011 // wide char (Unicode) support
2012 // ----------------------------------------------------------------------------
2016 #include <wx/strconv.h>
2017 #include <wx/buffer.h>
2019 static void TestUtf8()
2021 puts("*** Testing UTF8 support ***\n");
2023 wxString testString
= "français";
2025 "************ French - Français ****************"
2026 "Juste un petit exemple pour dire que les français aussi"
2027 "ont à cœur de pouvoir utiliser tous leurs caractères ! :)";
2030 wxWCharBuffer wchBuf
= testString
.wc_str(wxConvUTF8
);
2031 const wchar_t *pwz
= (const wchar_t *)wchBuf
;
2032 wxString
testString2(pwz
, wxConvLocal
);
2034 printf("Decoding '%s' => '%s'\n", testString
.c_str(), testString2
.c_str());
2036 char *psz
= "fran" "\xe7" "ais";
2037 size_t len
= strlen(psz
);
2038 wchar_t *pwz2
= new wchar_t[len
+ 1];
2039 for ( size_t n
= 0; n
<= len
; n
++ )
2041 pwz2
[n
] = (wchar_t)(unsigned char)psz
[n
];
2044 wxString
testString3(pwz2
, wxConvUTF8
);
2047 printf("Encoding '%s' -> '%s'\n", psz
, testString3
.c_str());
2050 #endif // TEST_WCHAR
2052 // ----------------------------------------------------------------------------
2054 // ----------------------------------------------------------------------------
2058 #include "wx/zipstrm.h"
2060 static void TestZipStreamRead()
2062 puts("*** Testing ZIP reading ***\n");
2064 wxZipInputStream
istr(_T("idx.zip"), _T("IDX.txt"));
2065 printf("Archive size: %u\n", istr
.GetSize());
2067 puts("Dumping the file:");
2068 while ( !istr
.Eof() )
2070 putchar(istr
.GetC());
2074 puts("\n----- done ------");
2079 // ----------------------------------------------------------------------------
2081 // ----------------------------------------------------------------------------
2085 #include <wx/zstream.h>
2086 #include <wx/wfstream.h>
2088 static const wxChar
*FILENAME_GZ
= _T("test.gz");
2089 static const char *TEST_DATA
= "hello and hello again";
2091 static void TestZlibStreamWrite()
2093 puts("*** Testing Zlib stream reading ***\n");
2095 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
2096 wxZlibOutputStream
ostr(fileOutStream
, 0);
2097 printf("Compressing the test string... ");
2098 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
2101 puts("(ERROR: failed)");
2108 puts("\n----- done ------");
2111 static void TestZlibStreamRead()
2113 puts("*** Testing Zlib stream reading ***\n");
2115 wxFileInputStream
fileInStream(FILENAME_GZ
);
2116 wxZlibInputStream
istr(fileInStream
);
2117 printf("Archive size: %u\n", istr
.GetSize());
2119 puts("Dumping the file:");
2120 while ( !istr
.Eof() )
2122 putchar(istr
.GetC());
2126 puts("\n----- done ------");
2131 // ----------------------------------------------------------------------------
2133 // ----------------------------------------------------------------------------
2135 #ifdef TEST_DATETIME
2137 #include <wx/date.h>
2139 #include <wx/datetime.h>
2144 wxDateTime::wxDateTime_t day
;
2145 wxDateTime::Month month
;
2147 wxDateTime::wxDateTime_t hour
, min
, sec
;
2149 wxDateTime::WeekDay wday
;
2150 time_t gmticks
, ticks
;
2152 void Init(const wxDateTime::Tm
& tm
)
2161 gmticks
= ticks
= -1;
2164 wxDateTime
DT() const
2165 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
2167 bool SameDay(const wxDateTime::Tm
& tm
) const
2169 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
2172 wxString
Format() const
2175 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
2177 wxDateTime::GetMonthName(month
).c_str(),
2179 abs(wxDateTime::ConvertYearToBC(year
)),
2180 year
> 0 ? "AD" : "BC");
2184 wxString
FormatDate() const
2187 s
.Printf("%02d-%s-%4d%s",
2189 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2190 abs(wxDateTime::ConvertYearToBC(year
)),
2191 year
> 0 ? "AD" : "BC");
2196 static const Date testDates
[] =
2198 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
2199 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
2200 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
2201 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
2202 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
2203 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
2204 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
2205 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
2206 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
2207 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
2208 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
2209 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
2210 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
2211 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
2212 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
2215 // this test miscellaneous static wxDateTime functions
2216 static void TestTimeStatic()
2218 puts("\n*** wxDateTime static methods test ***");
2220 // some info about the current date
2221 int year
= wxDateTime::GetCurrentYear();
2222 printf("Current year %d is %sa leap one and has %d days.\n",
2224 wxDateTime::IsLeapYear(year
) ? "" : "not ",
2225 wxDateTime::GetNumberOfDays(year
));
2227 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
2228 printf("Current month is '%s' ('%s') and it has %d days\n",
2229 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
2230 wxDateTime::GetMonthName(month
).c_str(),
2231 wxDateTime::GetNumberOfDays(month
));
2234 static const size_t nYears
= 5;
2235 static const size_t years
[2][nYears
] =
2237 // first line: the years to test
2238 { 1990, 1976, 2000, 2030, 1984, },
2240 // second line: TRUE if leap, FALSE otherwise
2241 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
2244 for ( size_t n
= 0; n
< nYears
; n
++ )
2246 int year
= years
[0][n
];
2247 bool should
= years
[1][n
] != 0,
2248 is
= wxDateTime::IsLeapYear(year
);
2250 printf("Year %d is %sa leap year (%s)\n",
2253 should
== is
? "ok" : "ERROR");
2255 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
2259 // test constructing wxDateTime objects
2260 static void TestTimeSet()
2262 puts("\n*** wxDateTime construction test ***");
2264 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2266 const Date
& d1
= testDates
[n
];
2267 wxDateTime dt
= d1
.DT();
2270 d2
.Init(dt
.GetTm());
2272 wxString s1
= d1
.Format(),
2275 printf("Date: %s == %s (%s)\n",
2276 s1
.c_str(), s2
.c_str(),
2277 s1
== s2
? "ok" : "ERROR");
2281 // test time zones stuff
2282 static void TestTimeZones()
2284 puts("\n*** wxDateTime timezone test ***");
2286 wxDateTime now
= wxDateTime::Now();
2288 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
2289 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
2290 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
2291 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
2292 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
2293 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
2295 wxDateTime::Tm tm
= now
.GetTm();
2296 if ( wxDateTime(tm
) != now
)
2298 printf("ERROR: got %s instead of %s\n",
2299 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
2303 // test some minimal support for the dates outside the standard range
2304 static void TestTimeRange()
2306 puts("\n*** wxDateTime out-of-standard-range dates test ***");
2308 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
2310 printf("Unix epoch:\t%s\n",
2311 wxDateTime(2440587.5).Format(fmt
).c_str());
2312 printf("Feb 29, 0: \t%s\n",
2313 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
2314 printf("JDN 0: \t%s\n",
2315 wxDateTime(0.0).Format(fmt
).c_str());
2316 printf("Jan 1, 1AD:\t%s\n",
2317 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
2318 printf("May 29, 2099:\t%s\n",
2319 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
2322 static void TestTimeTicks()
2324 puts("\n*** wxDateTime ticks test ***");
2326 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2328 const Date
& d
= testDates
[n
];
2329 if ( d
.ticks
== -1 )
2332 wxDateTime dt
= d
.DT();
2333 long ticks
= (dt
.GetValue() / 1000).ToLong();
2334 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2335 if ( ticks
== d
.ticks
)
2341 printf(" (ERROR: should be %ld, delta = %ld)\n",
2342 d
.ticks
, ticks
- d
.ticks
);
2345 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
2346 ticks
= (dt
.GetValue() / 1000).ToLong();
2347 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
2348 if ( ticks
== d
.gmticks
)
2354 printf(" (ERROR: should be %ld, delta = %ld)\n",
2355 d
.gmticks
, ticks
- d
.gmticks
);
2362 // test conversions to JDN &c
2363 static void TestTimeJDN()
2365 puts("\n*** wxDateTime to JDN test ***");
2367 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2369 const Date
& d
= testDates
[n
];
2370 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2371 double jdn
= dt
.GetJulianDayNumber();
2373 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
2380 printf(" (ERROR: should be %f, delta = %f)\n",
2381 d
.jdn
, jdn
- d
.jdn
);
2386 // test week days computation
2387 static void TestTimeWDays()
2389 puts("\n*** wxDateTime weekday test ***");
2391 // test GetWeekDay()
2393 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
2395 const Date
& d
= testDates
[n
];
2396 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
2398 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
2401 wxDateTime::GetWeekDayName(wday
).c_str());
2402 if ( wday
== d
.wday
)
2408 printf(" (ERROR: should be %s)\n",
2409 wxDateTime::GetWeekDayName(d
.wday
).c_str());
2415 // test SetToWeekDay()
2416 struct WeekDateTestData
2418 Date date
; // the real date (precomputed)
2419 int nWeek
; // its week index in the month
2420 wxDateTime::WeekDay wday
; // the weekday
2421 wxDateTime::Month month
; // the month
2422 int year
; // and the year
2424 wxString
Format() const
2427 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
2429 case 1: which
= "first"; break;
2430 case 2: which
= "second"; break;
2431 case 3: which
= "third"; break;
2432 case 4: which
= "fourth"; break;
2433 case 5: which
= "fifth"; break;
2435 case -1: which
= "last"; break;
2440 which
+= " from end";
2443 s
.Printf("The %s %s of %s in %d",
2445 wxDateTime::GetWeekDayName(wday
).c_str(),
2446 wxDateTime::GetMonthName(month
).c_str(),
2453 // the array data was generated by the following python program
2455 from DateTime import *
2456 from whrandom import *
2457 from string import *
2459 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2460 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2462 week = DateTimeDelta(7)
2465 year = randint(1900, 2100)
2466 month = randint(1, 12)
2467 day = randint(1, 28)
2468 dt = DateTime(year, month, day)
2469 wday = dt.day_of_week
2471 countFromEnd = choice([-1, 1])
2474 while dt.month is month:
2475 dt = dt - countFromEnd * week
2476 weekNum = weekNum + countFromEnd
2478 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
2480 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
2481 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
2484 static const WeekDateTestData weekDatesTestData
[] =
2486 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
2487 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
2488 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
2489 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
2490 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
2491 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
2492 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
2493 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
2494 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
2495 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
2496 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
2497 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
2498 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
2499 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
2500 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
2501 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
2502 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
2503 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
2504 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
2505 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
2508 static const char *fmt
= "%d-%b-%Y";
2511 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
2513 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
2515 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
2517 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
2519 const Date
& d
= wd
.date
;
2520 if ( d
.SameDay(dt
.GetTm()) )
2526 dt
.Set(d
.day
, d
.month
, d
.year
);
2528 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
2533 // test the computation of (ISO) week numbers
2534 static void TestTimeWNumber()
2536 puts("\n*** wxDateTime week number test ***");
2538 struct WeekNumberTestData
2540 Date date
; // the date
2541 wxDateTime::wxDateTime_t week
; // the week number in the year
2542 wxDateTime::wxDateTime_t wmon
; // the week number in the month
2543 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
2544 wxDateTime::wxDateTime_t dnum
; // day number in the year
2547 // data generated with the following python script:
2549 from DateTime import *
2550 from whrandom import *
2551 from string import *
2553 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
2554 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
2556 def GetMonthWeek(dt):
2557 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
2558 if weekNumMonth < 0:
2559 weekNumMonth = weekNumMonth + 53
2562 def GetLastSundayBefore(dt):
2563 if dt.iso_week[2] == 7:
2566 return dt - DateTimeDelta(dt.iso_week[2])
2569 year = randint(1900, 2100)
2570 month = randint(1, 12)
2571 day = randint(1, 28)
2572 dt = DateTime(year, month, day)
2573 dayNum = dt.day_of_year
2574 weekNum = dt.iso_week[1]
2575 weekNumMonth = GetMonthWeek(dt)
2578 dtSunday = GetLastSundayBefore(dt)
2580 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
2581 weekNumMonth2 = weekNumMonth2 + 1
2582 dtSunday = dtSunday - DateTimeDelta(7)
2584 data = { 'day': rjust(`day`, 2), \
2585 'month': monthNames[month - 1], \
2587 'weekNum': rjust(`weekNum`, 2), \
2588 'weekNumMonth': weekNumMonth, \
2589 'weekNumMonth2': weekNumMonth2, \
2590 'dayNum': rjust(`dayNum`, 3) }
2592 print " { { %(day)s, "\
2593 "wxDateTime::%(month)s, "\
2596 "%(weekNumMonth)s, "\
2597 "%(weekNumMonth2)s, "\
2598 "%(dayNum)s }," % data
2601 static const WeekNumberTestData weekNumberTestDates
[] =
2603 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
2604 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
2605 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
2606 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
2607 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
2608 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
2609 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
2610 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
2611 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
2612 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
2613 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
2614 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
2615 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
2616 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
2617 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
2618 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
2619 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
2620 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
2621 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
2622 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
2625 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
2627 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
2628 const Date
& d
= wn
.date
;
2630 wxDateTime dt
= d
.DT();
2632 wxDateTime::wxDateTime_t
2633 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
2634 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2635 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2636 dnum
= dt
.GetDayOfYear();
2638 printf("%s: the day number is %d",
2639 d
.FormatDate().c_str(), dnum
);
2640 if ( dnum
== wn
.dnum
)
2646 printf(" (ERROR: should be %d)", wn
.dnum
);
2649 printf(", week in month is %d", wmon
);
2650 if ( wmon
== wn
.wmon
)
2656 printf(" (ERROR: should be %d)", wn
.wmon
);
2659 printf(" or %d", wmon2
);
2660 if ( wmon2
== wn
.wmon2
)
2666 printf(" (ERROR: should be %d)", wn
.wmon2
);
2669 printf(", week in year is %d", week
);
2670 if ( week
== wn
.week
)
2676 printf(" (ERROR: should be %d)\n", wn
.week
);
2681 // test DST calculations
2682 static void TestTimeDST()
2684 puts("\n*** wxDateTime DST test ***");
2686 printf("DST is%s in effect now.\n\n",
2687 wxDateTime::Now().IsDST() ? "" : " not");
2689 // taken from http://www.energy.ca.gov/daylightsaving.html
2690 static const Date datesDST
[2][2004 - 1900 + 1] =
2693 { 1, wxDateTime::Apr
, 1990 },
2694 { 7, wxDateTime::Apr
, 1991 },
2695 { 5, wxDateTime::Apr
, 1992 },
2696 { 4, wxDateTime::Apr
, 1993 },
2697 { 3, wxDateTime::Apr
, 1994 },
2698 { 2, wxDateTime::Apr
, 1995 },
2699 { 7, wxDateTime::Apr
, 1996 },
2700 { 6, wxDateTime::Apr
, 1997 },
2701 { 5, wxDateTime::Apr
, 1998 },
2702 { 4, wxDateTime::Apr
, 1999 },
2703 { 2, wxDateTime::Apr
, 2000 },
2704 { 1, wxDateTime::Apr
, 2001 },
2705 { 7, wxDateTime::Apr
, 2002 },
2706 { 6, wxDateTime::Apr
, 2003 },
2707 { 4, wxDateTime::Apr
, 2004 },
2710 { 28, wxDateTime::Oct
, 1990 },
2711 { 27, wxDateTime::Oct
, 1991 },
2712 { 25, wxDateTime::Oct
, 1992 },
2713 { 31, wxDateTime::Oct
, 1993 },
2714 { 30, wxDateTime::Oct
, 1994 },
2715 { 29, wxDateTime::Oct
, 1995 },
2716 { 27, wxDateTime::Oct
, 1996 },
2717 { 26, wxDateTime::Oct
, 1997 },
2718 { 25, wxDateTime::Oct
, 1998 },
2719 { 31, wxDateTime::Oct
, 1999 },
2720 { 29, wxDateTime::Oct
, 2000 },
2721 { 28, wxDateTime::Oct
, 2001 },
2722 { 27, wxDateTime::Oct
, 2002 },
2723 { 26, wxDateTime::Oct
, 2003 },
2724 { 31, wxDateTime::Oct
, 2004 },
2729 for ( year
= 1990; year
< 2005; year
++ )
2731 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
2732 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
2734 printf("DST period in the US for year %d: from %s to %s",
2735 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
2737 size_t n
= year
- 1990;
2738 const Date
& dBegin
= datesDST
[0][n
];
2739 const Date
& dEnd
= datesDST
[1][n
];
2741 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
2747 printf(" (ERROR: should be %s %d to %s %d)\n",
2748 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
2749 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
2755 for ( year
= 1990; year
< 2005; year
++ )
2757 printf("DST period in Europe for year %d: from %s to %s\n",
2759 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
2760 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
2764 // test wxDateTime -> text conversion
2765 static void TestTimeFormat()
2767 puts("\n*** wxDateTime formatting test ***");
2769 // some information may be lost during conversion, so store what kind
2770 // of info should we recover after a round trip
2773 CompareNone
, // don't try comparing
2774 CompareBoth
, // dates and times should be identical
2775 CompareDate
, // dates only
2776 CompareTime
// time only
2781 CompareKind compareKind
;
2783 } formatTestFormats
[] =
2785 { CompareBoth
, "---> %c" },
2786 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
2787 { CompareBoth
, "Date is %x, time is %X" },
2788 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
2789 { CompareNone
, "The day of year: %j, the week of year: %W" },
2790 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
2793 static const Date formatTestDates
[] =
2795 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
2796 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
2798 // this test can't work for other centuries because it uses two digit
2799 // years in formats, so don't even try it
2800 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
2801 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
2802 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
2806 // an extra test (as it doesn't depend on date, don't do it in the loop)
2807 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
2809 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
2813 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
2814 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
2816 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
2817 printf("%s", s
.c_str());
2819 // what can we recover?
2820 int kind
= formatTestFormats
[n
].compareKind
;
2824 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
2827 // converion failed - should it have?
2828 if ( kind
== CompareNone
)
2831 puts(" (ERROR: conversion back failed)");
2835 // should have parsed the entire string
2836 puts(" (ERROR: conversion back stopped too soon)");
2840 bool equal
= FALSE
; // suppress compilaer warning
2848 equal
= dt
.IsSameDate(dt2
);
2852 equal
= dt
.IsSameTime(dt2
);
2858 printf(" (ERROR: got back '%s' instead of '%s')\n",
2859 dt2
.Format().c_str(), dt
.Format().c_str());
2870 // test text -> wxDateTime conversion
2871 static void TestTimeParse()
2873 puts("\n*** wxDateTime parse test ***");
2875 struct ParseTestData
2882 static const ParseTestData parseTestDates
[] =
2884 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
2885 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
2888 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
2890 const char *format
= parseTestDates
[n
].format
;
2892 printf("%s => ", format
);
2895 if ( dt
.ParseRfc822Date(format
) )
2897 printf("%s ", dt
.Format().c_str());
2899 if ( parseTestDates
[n
].good
)
2901 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
2908 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
2913 puts("(ERROR: bad format)");
2918 printf("bad format (%s)\n",
2919 parseTestDates
[n
].good
? "ERROR" : "ok");
2924 static void TestInteractive()
2926 puts("\n*** interactive wxDateTime tests ***");
2932 printf("Enter a date: ");
2933 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2936 // kill the last '\n'
2937 buf
[strlen(buf
) - 1] = 0;
2940 const char *p
= dt
.ParseDate(buf
);
2943 printf("ERROR: failed to parse the date '%s'.\n", buf
);
2949 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
2952 printf("%s: day %u, week of month %u/%u, week of year %u\n",
2953 dt
.Format("%b %d, %Y").c_str(),
2955 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
2956 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
2957 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
2960 puts("\n*** done ***");
2963 static void TestTimeMS()
2965 puts("*** testing millisecond-resolution support in wxDateTime ***");
2967 wxDateTime dt1
= wxDateTime::Now(),
2968 dt2
= wxDateTime::UNow();
2970 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
2971 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2972 printf("Dummy loop: ");
2973 for ( int i
= 0; i
< 6000; i
++ )
2975 //for ( int j = 0; j < 10; j++ )
2978 s
.Printf("%g", sqrt(i
));
2987 dt2
= wxDateTime::UNow();
2988 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
2990 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
2992 puts("\n*** done ***");
2995 static void TestTimeArithmetics()
2997 puts("\n*** testing arithmetic operations on wxDateTime ***");
2999 static const struct ArithmData
3001 ArithmData(const wxDateSpan
& sp
, const char *nam
)
3002 : span(sp
), name(nam
) { }
3006 } testArithmData
[] =
3008 ArithmData(wxDateSpan::Day(), "day"),
3009 ArithmData(wxDateSpan::Week(), "week"),
3010 ArithmData(wxDateSpan::Month(), "month"),
3011 ArithmData(wxDateSpan::Year(), "year"),
3012 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
3015 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
3017 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
3019 wxDateSpan span
= testArithmData
[n
].span
;
3023 const char *name
= testArithmData
[n
].name
;
3024 printf("%s + %s = %s, %s - %s = %s\n",
3025 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
3026 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
3028 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
3029 if ( dt1
- span
== dt
)
3035 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3038 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
3039 if ( dt2
+ span
== dt
)
3045 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
3048 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
3049 if ( dt2
+ 2*span
== dt1
)
3055 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
3062 static void TestTimeHolidays()
3064 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
3066 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3067 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3068 dtEnd
= dtStart
.GetLastMonthDay();
3070 wxDateTimeArray hol
;
3071 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3073 const wxChar
*format
= "%d-%b-%Y (%a)";
3075 printf("All holidays between %s and %s:\n",
3076 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3078 size_t count
= hol
.GetCount();
3079 for ( size_t n
= 0; n
< count
; n
++ )
3081 printf("\t%s\n", hol
[n
].Format(format
).c_str());
3087 static void TestTimeZoneBug()
3089 puts("\n*** testing for DST/timezone bug ***\n");
3091 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3092 for ( int i
= 0; i
< 31; i
++ )
3094 printf("Date %s: week day %s.\n",
3095 date
.Format(_T("%d-%m-%Y")).c_str(),
3096 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3098 date
+= wxDateSpan::Day();
3106 // test compatibility with the old wxDate/wxTime classes
3107 static void TestTimeCompatibility()
3109 puts("\n*** wxDateTime compatibility test ***");
3111 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
3112 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
3114 double jdnNow
= wxDateTime::Now().GetJDN();
3115 long jdnMidnight
= (long)(jdnNow
- 0.5);
3116 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
3118 jdnMidnight
= wxDate().Set().GetJulianDate();
3119 printf("wxDateTime for today: %s\n",
3120 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
3122 int flags
= wxEUROPEAN
;//wxFULL;
3125 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
3126 for ( int n
= 0; n
< 7; n
++ )
3128 printf("Previous %s is %s\n",
3129 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
3130 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
3136 #endif // TEST_DATETIME
3138 // ----------------------------------------------------------------------------
3140 // ----------------------------------------------------------------------------
3144 #include <wx/thread.h>
3146 static size_t gs_counter
= (size_t)-1;
3147 static wxCriticalSection gs_critsect
;
3148 static wxCondition gs_cond
;
3150 class MyJoinableThread
: public wxThread
3153 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3154 { m_n
= n
; Create(); }
3156 // thread execution starts here
3157 virtual ExitCode
Entry();
3163 wxThread::ExitCode
MyJoinableThread::Entry()
3165 unsigned long res
= 1;
3166 for ( size_t n
= 1; n
< m_n
; n
++ )
3170 // it's a loooong calculation :-)
3174 return (ExitCode
)res
;
3177 class MyDetachedThread
: public wxThread
3180 MyDetachedThread(size_t n
, char ch
)
3184 m_cancelled
= FALSE
;
3189 // thread execution starts here
3190 virtual ExitCode
Entry();
3193 virtual void OnExit();
3196 size_t m_n
; // number of characters to write
3197 char m_ch
; // character to write
3199 bool m_cancelled
; // FALSE if we exit normally
3202 wxThread::ExitCode
MyDetachedThread::Entry()
3205 wxCriticalSectionLocker
lock(gs_critsect
);
3206 if ( gs_counter
== (size_t)-1 )
3212 for ( size_t n
= 0; n
< m_n
; n
++ )
3214 if ( TestDestroy() )
3224 wxThread::Sleep(100);
3230 void MyDetachedThread::OnExit()
3232 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
3234 wxCriticalSectionLocker
lock(gs_critsect
);
3235 if ( !--gs_counter
&& !m_cancelled
)
3239 void TestDetachedThreads()
3241 puts("\n*** Testing detached threads ***");
3243 static const size_t nThreads
= 3;
3244 MyDetachedThread
*threads
[nThreads
];
3246 for ( n
= 0; n
< nThreads
; n
++ )
3248 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3251 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3252 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3254 for ( n
= 0; n
< nThreads
; n
++ )
3259 // wait until all threads terminate
3265 void TestJoinableThreads()
3267 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
3269 // calc 10! in the background
3270 MyJoinableThread
thread(10);
3273 printf("\nThread terminated with exit code %lu.\n",
3274 (unsigned long)thread
.Wait());
3277 void TestThreadSuspend()
3279 puts("\n*** Testing thread suspend/resume functions ***");
3281 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3285 // this is for this demo only, in a real life program we'd use another
3286 // condition variable which would be signaled from wxThread::Entry() to
3287 // tell us that the thread really started running - but here just wait a
3288 // bit and hope that it will be enough (the problem is, of course, that
3289 // the thread might still not run when we call Pause() which will result
3291 wxThread::Sleep(300);
3293 for ( size_t n
= 0; n
< 3; n
++ )
3297 puts("\nThread suspended");
3300 // don't sleep but resume immediately the first time
3301 wxThread::Sleep(300);
3303 puts("Going to resume the thread");
3308 puts("Waiting until it terminates now");
3310 // wait until the thread terminates
3316 void TestThreadDelete()
3318 // As above, using Sleep() is only for testing here - we must use some
3319 // synchronisation object instead to ensure that the thread is still
3320 // running when we delete it - deleting a detached thread which already
3321 // terminated will lead to a crash!
3323 puts("\n*** Testing thread delete function ***");
3325 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3329 puts("\nDeleted a thread which didn't start to run yet.");
3331 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3335 wxThread::Sleep(300);
3339 puts("\nDeleted a running thread.");
3341 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3345 wxThread::Sleep(300);
3351 puts("\nDeleted a sleeping thread.");
3353 MyJoinableThread
thread3(20);
3358 puts("\nDeleted a joinable thread.");
3360 MyJoinableThread
thread4(2);
3363 wxThread::Sleep(300);
3367 puts("\nDeleted a joinable thread which already terminated.");
3372 #endif // TEST_THREADS
3374 // ----------------------------------------------------------------------------
3376 // ----------------------------------------------------------------------------
3380 static void PrintArray(const char* name
, const wxArrayString
& array
)
3382 printf("Dump of the array '%s'\n", name
);
3384 size_t nCount
= array
.GetCount();
3385 for ( size_t n
= 0; n
< nCount
; n
++ )
3387 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
3391 static void PrintArray(const char* name
, const wxArrayInt
& array
)
3393 printf("Dump of the array '%s'\n", name
);
3395 size_t nCount
= array
.GetCount();
3396 for ( size_t n
= 0; n
< nCount
; n
++ )
3398 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
3402 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
3403 const wxString
& second
)
3405 return first
.length() - second
.length();
3408 int wxCMPFUNC_CONV
IntCompare(int *first
,
3411 return *first
- *second
;
3414 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
3417 return *second
- *first
;
3420 static void TestArrayOfInts()
3422 puts("*** Testing wxArrayInt ***\n");
3433 puts("After sort:");
3437 puts("After reverse sort:");
3438 a
.Sort(IntRevCompare
);
3442 #include "wx/dynarray.h"
3444 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
3445 #include "wx/arrimpl.cpp"
3446 WX_DEFINE_OBJARRAY(ArrayBars
);
3448 static void TestArrayOfObjects()
3450 puts("*** Testing wxObjArray ***\n");
3454 Bar
bar("second bar");
3456 printf("Initially: %u objects in the array, %u objects total.\n",
3457 bars
.GetCount(), Bar::GetNumber());
3459 bars
.Add(new Bar("first bar"));
3462 printf("Now: %u objects in the array, %u objects total.\n",
3463 bars
.GetCount(), Bar::GetNumber());
3467 printf("After Empty(): %u objects in the array, %u objects total.\n",
3468 bars
.GetCount(), Bar::GetNumber());
3471 printf("Finally: no more objects in the array, %u objects total.\n",
3475 #endif // TEST_ARRAYS
3477 // ----------------------------------------------------------------------------
3479 // ----------------------------------------------------------------------------
3483 #include "wx/timer.h"
3484 #include "wx/tokenzr.h"
3486 static void TestStringConstruction()
3488 puts("*** Testing wxString constructores ***");
3490 #define TEST_CTOR(args, res) \
3493 printf("wxString%s = %s ", #args, s.c_str()); \
3500 printf("(ERROR: should be %s)\n", res); \
3504 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
3505 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
3506 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
3507 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
3509 static const wxChar
*s
= _T("?really!");
3510 const wxChar
*start
= wxStrchr(s
, _T('r'));
3511 const wxChar
*end
= wxStrchr(s
, _T('!'));
3512 TEST_CTOR((start
, end
), _T("really"));
3517 static void TestString()
3527 for (int i
= 0; i
< 1000000; ++i
)
3531 c
= "! How'ya doin'?";
3534 c
= "Hello world! What's up?";
3539 printf ("TestString elapsed time: %ld\n", sw
.Time());
3542 static void TestPChar()
3550 for (int i
= 0; i
< 1000000; ++i
)
3552 strcpy (a
, "Hello");
3553 strcpy (b
, " world");
3554 strcpy (c
, "! How'ya doin'?");
3557 strcpy (c
, "Hello world! What's up?");
3558 if (strcmp (c
, a
) == 0)
3562 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
3565 static void TestStringSub()
3567 wxString
s("Hello, world!");
3569 puts("*** Testing wxString substring extraction ***");
3571 printf("String = '%s'\n", s
.c_str());
3572 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
3573 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
3574 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
3575 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
3576 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
3577 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
3579 static const wxChar
*prefixes
[] =
3583 _T("Hello, world!"),
3584 _T("Hello, world!!!"),
3590 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
3592 wxString prefix
= prefixes
[n
], rest
;
3593 bool rc
= s
.StartsWith(prefix
, &rest
);
3594 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
3597 printf(" (the rest is '%s')\n", rest
.c_str());
3608 static void TestStringFormat()
3610 puts("*** Testing wxString formatting ***");
3613 s
.Printf("%03d", 18);
3615 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
3616 printf("Number 18: %s\n", s
.c_str());
3621 // returns "not found" for npos, value for all others
3622 static wxString
PosToString(size_t res
)
3624 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
3625 : wxString::Format(_T("%u"), res
);
3629 static void TestStringFind()
3631 puts("*** Testing wxString find() functions ***");
3633 static const wxChar
*strToFind
= _T("ell");
3634 static const struct StringFindTest
3638 result
; // of searching "ell" in str
3641 { _T("Well, hello world"), 0, 1 },
3642 { _T("Well, hello world"), 6, 7 },
3643 { _T("Well, hello world"), 9, wxString::npos
},
3646 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
3648 const StringFindTest
& ft
= findTestData
[n
];
3649 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
3651 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
3652 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
3654 size_t resTrue
= ft
.result
;
3655 if ( res
== resTrue
)
3661 printf(_T("(ERROR: should be %s)\n"),
3662 PosToString(resTrue
).c_str());
3669 static void TestStringTokenizer()
3671 puts("*** Testing wxStringTokenizer ***");
3673 static const wxChar
*modeNames
[] =
3677 _T("return all empty"),
3682 static const struct StringTokenizerTest
3684 const wxChar
*str
; // string to tokenize
3685 const wxChar
*delims
; // delimiters to use
3686 size_t count
; // count of token
3687 wxStringTokenizerMode mode
; // how should we tokenize it
3688 } tokenizerTestData
[] =
3690 { _T(""), _T(" "), 0 },
3691 { _T("Hello, world"), _T(" "), 2 },
3692 { _T("Hello, world "), _T(" "), 2 },
3693 { _T("Hello, world"), _T(","), 2 },
3694 { _T("Hello, world!"), _T(",!"), 2 },
3695 { _T("Hello,, world!"), _T(",!"), 3 },
3696 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
3697 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
3698 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
3699 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
3700 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
3701 { _T("01/02/99"), _T("/-"), 3 },
3702 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
3705 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
3707 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
3708 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
3710 size_t count
= tkz
.CountTokens();
3711 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
3712 MakePrintable(tt
.str
).c_str(),
3714 MakePrintable(tt
.delims
).c_str(),
3715 modeNames
[tkz
.GetMode()]);
3716 if ( count
== tt
.count
)
3722 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
3727 // if we emulate strtok(), check that we do it correctly
3728 wxChar
*buf
, *s
= NULL
, *last
;
3730 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
3732 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
3733 wxStrcpy(buf
, tt
.str
);
3735 s
= wxStrtok(buf
, tt
.delims
, &last
);
3742 // now show the tokens themselves
3744 while ( tkz
.HasMoreTokens() )
3746 wxString token
= tkz
.GetNextToken();
3748 printf(_T("\ttoken %u: '%s'"),
3750 MakePrintable(token
).c_str());
3760 printf(" (ERROR: should be %s)\n", s
);
3763 s
= wxStrtok(NULL
, tt
.delims
, &last
);
3767 // nothing to compare with
3772 if ( count2
!= count
)
3774 puts(_T("\tERROR: token count mismatch"));
3783 static void TestStringReplace()
3785 puts("*** Testing wxString::replace ***");
3787 static const struct StringReplaceTestData
3789 const wxChar
*original
; // original test string
3790 size_t start
, len
; // the part to replace
3791 const wxChar
*replacement
; // the replacement string
3792 const wxChar
*result
; // and the expected result
3793 } stringReplaceTestData
[] =
3795 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
3796 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
3797 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
3798 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
3799 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
3802 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
3804 const StringReplaceTestData data
= stringReplaceTestData
[n
];
3806 wxString original
= data
.original
;
3807 original
.replace(data
.start
, data
.len
, data
.replacement
);
3809 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
3810 data
.original
, data
.start
, data
.len
, data
.replacement
,
3813 if ( original
== data
.result
)
3819 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
3826 #endif // TEST_STRINGS
3828 // ----------------------------------------------------------------------------
3830 // ----------------------------------------------------------------------------
3832 int main(int argc
, char **argv
)
3834 if ( !wxInitialize() )
3836 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
3840 puts("Sleeping for 3 seconds... z-z-z-z-z...");
3842 #endif // TEST_USLEEP
3845 static const wxCmdLineEntryDesc cmdLineDesc
[] =
3847 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
3848 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
3850 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
3851 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
3852 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
3853 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
3855 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
3856 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
3861 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
3863 parser
.AddOption("project_name", "", "full path to project file",
3864 wxCMD_LINE_VAL_STRING
,
3865 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
3867 switch ( parser
.Parse() )
3870 wxLogMessage("Help was given, terminating.");
3874 ShowCmdLine(parser
);
3878 wxLogMessage("Syntax error detected, aborting.");
3881 #endif // TEST_CMDLINE
3892 TestStringConstruction();
3895 TestStringTokenizer();
3896 TestStringReplace();
3898 #endif // TEST_STRINGS
3911 puts("*** Initially:");
3913 PrintArray("a1", a1
);
3915 wxArrayString
a2(a1
);
3916 PrintArray("a2", a2
);
3918 wxSortedArrayString
a3(a1
);
3919 PrintArray("a3", a3
);
3921 puts("*** After deleting a string from a1");
3924 PrintArray("a1", a1
);
3925 PrintArray("a2", a2
);
3926 PrintArray("a3", a3
);
3928 puts("*** After reassigning a1 to a2 and a3");
3930 PrintArray("a2", a2
);
3931 PrintArray("a3", a3
);
3933 puts("*** After sorting a1");
3935 PrintArray("a1", a1
);
3937 puts("*** After sorting a1 in reverse order");
3939 PrintArray("a1", a1
);
3941 puts("*** After sorting a1 by the string length");
3942 a1
.Sort(StringLenCompare
);
3943 PrintArray("a1", a1
);
3945 TestArrayOfObjects();
3948 #endif // TEST_ARRAYS
3954 #ifdef TEST_DLLLOADER
3956 #endif // TEST_DLLLOADER
3960 #endif // TEST_ENVIRON
3964 #endif // TEST_EXECUTE
3966 #ifdef TEST_FILECONF
3968 #endif // TEST_FILECONF
3976 for ( size_t n
= 0; n
< 8000; n
++ )
3978 s
<< (char)('A' + (n
% 26));
3982 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
3984 // this one shouldn't be truncated
3987 // but this one will because log functions use fixed size buffer
3988 // (note that it doesn't need '\n' at the end neither - will be added
3990 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
4002 #ifdef TEST_FILENAME
4003 TestFileNameConstruction();
4007 TestFileNameComparison();
4008 TestFileNameOperations();
4010 #endif // TEST_FILENAME
4013 int nCPUs
= wxThread::GetCPUCount();
4014 printf("This system has %d CPUs\n", nCPUs
);
4016 wxThread::SetConcurrency(nCPUs
);
4018 if ( argc
> 1 && argv
[1][0] == 't' )
4019 wxLog::AddTraceMask("thread");
4022 TestDetachedThreads();
4024 TestJoinableThreads();
4026 TestThreadSuspend();
4030 #endif // TEST_THREADS
4032 #ifdef TEST_LONGLONG
4033 // seed pseudo random generator
4034 srand((unsigned)time(NULL
));
4042 TestMultiplication();
4045 TestLongLongConversion();
4046 TestBitOperations();
4048 TestLongLongComparison();
4049 #endif // TEST_LONGLONG
4056 wxLog::AddTraceMask(_T("mime"));
4063 TestMimeAssociate();
4066 #ifdef TEST_INFO_FUNCTIONS
4069 #endif // TEST_INFO_FUNCTIONS
4071 #ifdef TEST_REGISTRY
4074 TestRegistryAssociation();
4075 #endif // TEST_REGISTRY
4083 #endif // TEST_SOCKETS
4086 wxLog::AddTraceMask(_T("ftp"));
4089 TestProtocolFtpUpload();
4094 #endif // TEST_STREAMS
4098 #endif // TEST_TIMER
4100 #ifdef TEST_DATETIME
4113 TestTimeArithmetics();
4122 #endif // TEST_DATETIME
4128 #endif // TEST_VCARD
4132 #endif // TEST_WCHAR
4135 TestZipStreamRead();
4140 TestZlibStreamWrite();
4141 TestZlibStreamRead();