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_EXECUTE
43 //#define TEST_FILECONF
46 //#define TEST_LONGLONG
48 #define TEST_INFO_FUNCTIONS
49 //#define TEST_SOCKETS
50 //#define TEST_STRINGS
51 //#define TEST_THREADS
54 // ============================================================================
56 // ============================================================================
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
64 // replace TABs with \t and CRs with \n
65 static wxString
MakePrintable(const wxChar
*s
)
68 (void)str
.Replace(_T("\t"), _T("\\t"));
69 (void)str
.Replace(_T("\n"), _T("\\n"));
70 (void)str
.Replace(_T("\r"), _T("\\r"));
75 #endif // MakePrintable() is used
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
83 #include <wx/cmdline.h>
84 #include <wx/datetime.h>
86 static void ShowCmdLine(const wxCmdLineParser
& parser
)
88 wxString s
= "Input files: ";
90 size_t count
= parser
.GetParamCount();
91 for ( size_t param
= 0; param
< count
; param
++ )
93 s
<< parser
.GetParam(param
) << ' ';
97 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
98 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
103 if ( parser
.Found("o", &strVal
) )
104 s
<< "Output file:\t" << strVal
<< '\n';
105 if ( parser
.Found("i", &strVal
) )
106 s
<< "Input dir:\t" << strVal
<< '\n';
107 if ( parser
.Found("s", &lVal
) )
108 s
<< "Size:\t" << lVal
<< '\n';
109 if ( parser
.Found("d", &dt
) )
110 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
115 #endif // TEST_CMDLINE
117 // ----------------------------------------------------------------------------
119 // ----------------------------------------------------------------------------
125 static void TestDirEnumHelper(wxDir
& dir
,
126 int flags
= wxDIR_DEFAULT
,
127 const wxString
& filespec
= wxEmptyString
)
131 if ( !dir
.IsOpened() )
134 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
137 printf("\t%s\n", filename
.c_str());
139 cont
= dir
.GetNext(&filename
);
145 static void TestDirEnum()
147 wxDir
dir(wxGetCwd());
149 puts("Enumerating everything in current directory:");
150 TestDirEnumHelper(dir
);
152 puts("Enumerating really everything in current directory:");
153 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
155 puts("Enumerating object files in current directory:");
156 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
158 puts("Enumerating directories in current directory:");
159 TestDirEnumHelper(dir
, wxDIR_DIRS
);
161 puts("Enumerating files in current directory:");
162 TestDirEnumHelper(dir
, wxDIR_FILES
);
164 puts("Enumerating files including hidden in current directory:");
165 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
169 #elif defined(__WXMSW__)
172 #error "don't know where the root directory is"
175 puts("Enumerating everything in root directory:");
176 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
178 puts("Enumerating directories in root directory:");
179 TestDirEnumHelper(dir
, wxDIR_DIRS
);
181 puts("Enumerating files in root directory:");
182 TestDirEnumHelper(dir
, wxDIR_FILES
);
184 puts("Enumerating files including hidden in root directory:");
185 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
187 puts("Enumerating files in non existing directory:");
188 wxDir
dirNo("nosuchdir");
189 TestDirEnumHelper(dirNo
);
194 // ----------------------------------------------------------------------------
196 // ----------------------------------------------------------------------------
200 #include <wx/utils.h>
202 static void TestExecute()
204 puts("*** testing wxExecute ***");
207 #define COMMAND "echo hi"
208 #define SHELL_COMMAND "echo hi from shell"
209 #define REDIRECT_COMMAND "date"
210 #elif defined(__WXMSW__)
211 #define COMMAND "command.com -c 'echo hi'"
212 #define SHELL_COMMAND "echo hi"
213 #define REDIRECT_COMMAND COMMAND
215 #error "no command to exec"
218 printf("Testing wxShell: ");
220 if ( wxShell(SHELL_COMMAND
) )
225 printf("Testing wxExecute: ");
227 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
232 #if 0 // no, it doesn't work (yet?)
233 printf("Testing async wxExecute: ");
235 if ( wxExecute(COMMAND
) != 0 )
236 puts("Ok (command launched).");
241 printf("Testing wxExecute with redirection:\n");
242 wxArrayString output
;
243 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
249 size_t count
= output
.GetCount();
250 for ( size_t n
= 0; n
< count
; n
++ )
252 printf("\t%s\n", output
[n
].c_str());
259 #endif // TEST_EXECUTE
261 // ----------------------------------------------------------------------------
263 // ----------------------------------------------------------------------------
267 #include <wx/confbase.h>
268 #include <wx/fileconf.h>
270 static const struct FileConfTestData
272 const wxChar
*name
; // value name
273 const wxChar
*value
; // the value from the file
276 { _T("value1"), _T("one") },
277 { _T("value2"), _T("two") },
278 { _T("novalue"), _T("default") },
281 static void TestFileConfRead()
283 puts("*** testing wxFileConfig loading/reading ***");
285 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
286 _T("testdata.fc"), wxEmptyString
,
287 wxCONFIG_USE_RELATIVE_PATH
);
289 // test simple reading
290 puts("\nReading config file:");
291 wxString
defValue(_T("default")), value
;
292 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
294 const FileConfTestData
& data
= fcTestData
[n
];
295 value
= fileconf
.Read(data
.name
, defValue
);
296 printf("\t%s = %s ", data
.name
, value
.c_str());
297 if ( value
== data
.value
)
303 printf("(ERROR: should be %s)\n", data
.value
);
307 // test enumerating the entries
308 puts("\nEnumerating all root entries:");
311 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
314 printf("\t%s = %s\n",
316 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
318 cont
= fileconf
.GetNextEntry(name
, dummy
);
322 #endif // TEST_FILECONF
324 // ----------------------------------------------------------------------------
326 // ----------------------------------------------------------------------------
334 Foo(int n_
) { n
= n_
; count
++; }
342 size_t Foo::count
= 0;
344 WX_DECLARE_LIST(Foo
, wxListFoos
);
345 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
347 #include <wx/listimpl.cpp>
349 WX_DEFINE_LIST(wxListFoos
);
351 static void TestHash()
353 puts("*** Testing wxHashTable ***\n");
357 hash
.DeleteContents(TRUE
);
359 printf("Hash created: %u foos in hash, %u foos totally\n",
360 hash
.GetCount(), Foo::count
);
362 static const int hashTestData
[] =
364 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
368 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
370 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
373 printf("Hash filled: %u foos in hash, %u foos totally\n",
374 hash
.GetCount(), Foo::count
);
376 puts("Hash access test:");
377 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
379 printf("\tGetting element with key %d, value %d: ",
381 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
384 printf("ERROR, not found.\n");
388 printf("%d (%s)\n", foo
->n
,
389 (size_t)foo
->n
== n
? "ok" : "ERROR");
393 printf("\nTrying to get an element not in hash: ");
395 if ( hash
.Get(1234) || hash
.Get(1, 0) )
397 puts("ERROR: found!");
401 puts("ok (not found)");
405 printf("Hash destroyed: %u foos left\n", Foo::count
);
410 // ----------------------------------------------------------------------------
412 // ----------------------------------------------------------------------------
416 #include <wx/mimetype.h>
418 static void TestMimeEnum()
420 wxMimeTypesManager mimeTM
;
421 wxArrayString mimetypes
;
423 size_t count
= mimeTM
.EnumAllFileTypes(mimetypes
);
425 printf("*** All %u known filetypes: ***\n", count
);
430 for ( size_t n
= 0; n
< count
; n
++ )
432 wxFileType
*filetype
= mimeTM
.GetFileTypeFromMimeType(mimetypes
[n
]);
435 printf("nothing known about the filetype '%s'!\n",
436 mimetypes
[n
].c_str());
440 filetype
->GetDescription(&desc
);
441 filetype
->GetExtensions(exts
);
443 filetype
->GetIcon(NULL
);
446 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
453 printf("\t%s: %s (%s)\n",
454 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
460 // ----------------------------------------------------------------------------
461 // misc information functions
462 // ----------------------------------------------------------------------------
464 #ifdef TEST_INFO_FUNCTIONS
466 #include <wx/utils.h>
468 static void TestOsInfo()
470 puts("*** Testing OS info functions ***\n");
473 wxGetOsVersion(&major
, &minor
);
474 printf("Running under: %s, version %d.%d\n",
475 wxGetOsDescription().c_str(), major
, minor
);
477 printf("%d free bytes of memory left.\n", wxGetFreeMemory());
479 printf("Host name is %s (%s).\n",
480 wxGetHostName().c_str(), wxGetFullHostName().c_str());
483 static void TestUserInfo()
485 puts("*** Testing user info functions ***\n");
487 printf("User id is:\t%s\n", wxGetUserId().c_str());
488 printf("User name is:\t%s\n", wxGetUserName().c_str());
489 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
490 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
493 #endif // TEST_INFO_FUNCTIONS
495 // ----------------------------------------------------------------------------
497 // ----------------------------------------------------------------------------
501 #include <wx/longlong.h>
502 #include <wx/timer.h>
504 // make a 64 bit number from 4 16 bit ones
505 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
507 // get a random 64 bit number
508 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
510 #if wxUSE_LONGLONG_WX
511 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
512 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
513 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
514 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
515 #endif // wxUSE_LONGLONG_WX
517 static void TestSpeed()
519 static const long max
= 100000000;
526 for ( n
= 0; n
< max
; n
++ )
531 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
534 #if wxUSE_LONGLONG_NATIVE
539 for ( n
= 0; n
< max
; n
++ )
544 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
546 #endif // wxUSE_LONGLONG_NATIVE
552 for ( n
= 0; n
< max
; n
++ )
557 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
561 static void TestLongLongConversion()
563 puts("*** Testing wxLongLong conversions ***\n");
567 for ( size_t n
= 0; n
< 100000; n
++ )
571 #if wxUSE_LONGLONG_NATIVE
572 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
574 wxASSERT_MSG( a
== b
, "conversions failure" );
576 puts("Can't do it without native long long type, test skipped.");
579 #endif // wxUSE_LONGLONG_NATIVE
581 if ( !(nTested
% 1000) )
593 static void TestMultiplication()
595 puts("*** Testing wxLongLong multiplication ***\n");
599 for ( size_t n
= 0; n
< 100000; n
++ )
604 #if wxUSE_LONGLONG_NATIVE
605 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
606 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
608 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
609 #else // !wxUSE_LONGLONG_NATIVE
610 puts("Can't do it without native long long type, test skipped.");
613 #endif // wxUSE_LONGLONG_NATIVE
615 if ( !(nTested
% 1000) )
627 static void TestDivision()
629 puts("*** Testing wxLongLong division ***\n");
633 for ( size_t n
= 0; n
< 100000; n
++ )
635 // get a random wxLongLong (shifting by 12 the MSB ensures that the
636 // multiplication will not overflow)
637 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
639 // get a random long (not wxLongLong for now) to divide it with
644 #if wxUSE_LONGLONG_NATIVE
645 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
647 wxLongLongNative p
= m
/ l
, s
= m
% l
;
648 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
649 #else // !wxUSE_LONGLONG_NATIVE
651 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
652 #endif // wxUSE_LONGLONG_NATIVE
654 if ( !(nTested
% 1000) )
666 static void TestAddition()
668 puts("*** Testing wxLongLong addition ***\n");
672 for ( size_t n
= 0; n
< 100000; n
++ )
678 #if wxUSE_LONGLONG_NATIVE
679 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
680 wxLongLongNative(b
.GetHi(), b
.GetLo()),
681 "addition failure" );
682 #else // !wxUSE_LONGLONG_NATIVE
683 wxASSERT_MSG( c
- b
== a
, "addition failure" );
684 #endif // wxUSE_LONGLONG_NATIVE
686 if ( !(nTested
% 1000) )
698 static void TestBitOperations()
700 puts("*** Testing wxLongLong bit operation ***\n");
704 for ( size_t n
= 0; n
< 100000; n
++ )
708 #if wxUSE_LONGLONG_NATIVE
709 for ( size_t n
= 0; n
< 33; n
++ )
711 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
716 wxASSERT_MSG( b
== c
, "bit shift failure" );
718 b
= wxLongLongNative(a
.GetHi(), a
.GetLo()) << n
;
721 wxASSERT_MSG( b
== c
, "bit shift failure" );
724 #else // !wxUSE_LONGLONG_NATIVE
725 puts("Can't do it without native long long type, test skipped.");
728 #endif // wxUSE_LONGLONG_NATIVE
730 if ( !(nTested
% 1000) )
745 #endif // TEST_LONGLONG
747 // ----------------------------------------------------------------------------
749 // ----------------------------------------------------------------------------
753 #include <wx/socket.h>
754 #include <wx/protocol/protocol.h>
755 #include <wx/protocol/ftp.h>
756 #include <wx/protocol/http.h>
758 static void TestSocketServer()
760 puts("*** Testing wxSocketServer ***\n");
762 static const int PORT
= 3000;
767 wxSocketServer
*server
= new wxSocketServer(addr
);
770 puts("ERROR: failed to bind");
777 printf("Server: waiting for connection on port %d...\n", PORT
);
779 wxSocketBase
*socket
= server
->Accept();
782 puts("ERROR: wxSocketServer::Accept() failed.");
786 puts("Server: got a client.");
788 server
->SetTimeout(60); // 1 min
790 while ( socket
->IsConnected() )
796 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
798 // don't log error if the client just close the connection
799 if ( socket
->IsConnected() )
801 puts("ERROR: in wxSocket::Read.");
821 printf("Server: got '%s'.\n", s
.c_str());
822 if ( s
== _T("bye") )
829 socket
->Write(s
.MakeUpper().c_str(), s
.length());
830 socket
->Write("\r\n", 2);
831 printf("Server: wrote '%s'.\n", s
.c_str());
834 puts("Server: lost a client.");
839 // same as "delete server" but is consistent with GUI programs
843 static void TestSocketClient()
845 puts("*** Testing wxSocketClient ***\n");
847 static const char *hostname
= "www.wxwindows.org";
850 addr
.Hostname(hostname
);
853 printf("--- Attempting to connect to %s:80...\n", hostname
);
855 wxSocketClient client
;
856 if ( !client
.Connect(addr
) )
858 printf("ERROR: failed to connect to %s\n", hostname
);
862 printf("--- Connected to %s:%u...\n",
863 addr
.Hostname().c_str(), addr
.Service());
867 // could use simply "GET" here I suppose
869 wxString::Format("GET http://%s/\r\n", hostname
);
870 client
.Write(cmdGet
, cmdGet
.length());
871 printf("--- Sent command '%s' to the server\n",
872 MakePrintable(cmdGet
).c_str());
873 client
.Read(buf
, WXSIZEOF(buf
));
874 printf("--- Server replied:\n%s", buf
);
878 static void TestProtocolFtp()
880 puts("*** Testing wxFTP ***\n");
882 wxLog::AddTraceMask(_T("ftp"));
884 static const char *hostname
= "ftp.wxwindows.org";
886 printf("--- Attempting to connect to %s:21...\n", hostname
);
889 if ( !ftp
.Connect(hostname
) )
891 printf("ERROR: failed to connect to %s\n", hostname
);
895 printf("--- Connected to %s, current directory is '%s'\n",
896 hostname
, ftp
.Pwd().c_str());
897 if ( !ftp
.ChDir(_T("pub")) )
899 puts("ERROR: failed to cd to pub");
903 if ( !ftp
.GetList(files
) )
905 puts("ERROR: failed to get list of files");
909 printf("List of files under '%s':\n", ftp
.Pwd().c_str());
910 size_t count
= files
.GetCount();
911 for ( size_t n
= 0; n
< count
; n
++ )
913 printf("\t%s\n", files
[n
].c_str());
915 puts("End of the file list");
918 if ( !ftp
.ChDir(_T("..")) )
920 puts("ERROR: failed to cd to ..");
923 static const char *filename
= "welcome.msg";
924 wxInputStream
*in
= ftp
.GetInputStream(filename
);
927 puts("ERROR: couldn't get input stream");
931 size_t size
= in
->StreamSize();
932 printf("Reading file %s (%u bytes)...", filename
, size
);
934 char *data
= new char[size
];
935 if ( !in
->Read(data
, size
) )
937 puts("ERROR: read error");
941 printf("\nContents of %s:\n%s\n", filename
, data
);
950 #endif // TEST_SOCKETS
952 // ----------------------------------------------------------------------------
954 // ----------------------------------------------------------------------------
958 #include <wx/timer.h>
959 #include <wx/utils.h>
961 static void TestStopWatch()
963 puts("*** Testing wxStopWatch ***\n");
966 printf("Sleeping 3 seconds...");
968 printf("\telapsed time: %ldms\n", sw
.Time());
971 printf("Sleeping 2 more seconds...");
973 printf("\telapsed time: %ldms\n", sw
.Time());
976 printf("And 3 more seconds...");
978 printf("\telapsed time: %ldms\n", sw
.Time());
981 puts("\nChecking for 'backwards clock' bug...");
982 for ( size_t n
= 0; n
< 70; n
++ )
986 for ( size_t m
= 0; m
< 100000; m
++ )
988 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
990 puts("\ntime is negative - ERROR!");
1000 #endif // TEST_TIMER
1002 // ----------------------------------------------------------------------------
1004 // ----------------------------------------------------------------------------
1006 #ifdef TEST_DATETIME
1008 #include <wx/date.h>
1010 #include <wx/datetime.h>
1015 wxDateTime::wxDateTime_t day
;
1016 wxDateTime::Month month
;
1018 wxDateTime::wxDateTime_t hour
, min
, sec
;
1020 wxDateTime::WeekDay wday
;
1021 time_t gmticks
, ticks
;
1023 void Init(const wxDateTime::Tm
& tm
)
1032 gmticks
= ticks
= -1;
1035 wxDateTime
DT() const
1036 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
1038 bool SameDay(const wxDateTime::Tm
& tm
) const
1040 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
1043 wxString
Format() const
1046 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
1048 wxDateTime::GetMonthName(month
).c_str(),
1050 abs(wxDateTime::ConvertYearToBC(year
)),
1051 year
> 0 ? "AD" : "BC");
1055 wxString
FormatDate() const
1058 s
.Printf("%02d-%s-%4d%s",
1060 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1061 abs(wxDateTime::ConvertYearToBC(year
)),
1062 year
> 0 ? "AD" : "BC");
1067 static const Date testDates
[] =
1069 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
1070 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
1071 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
1072 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
1073 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
1074 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
1075 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
1076 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
1077 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
1078 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
1079 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
1080 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
1081 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
1082 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
1083 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
1086 // this test miscellaneous static wxDateTime functions
1087 static void TestTimeStatic()
1089 puts("\n*** wxDateTime static methods test ***");
1091 // some info about the current date
1092 int year
= wxDateTime::GetCurrentYear();
1093 printf("Current year %d is %sa leap one and has %d days.\n",
1095 wxDateTime::IsLeapYear(year
) ? "" : "not ",
1096 wxDateTime::GetNumberOfDays(year
));
1098 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
1099 printf("Current month is '%s' ('%s') and it has %d days\n",
1100 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1101 wxDateTime::GetMonthName(month
).c_str(),
1102 wxDateTime::GetNumberOfDays(month
));
1105 static const size_t nYears
= 5;
1106 static const size_t years
[2][nYears
] =
1108 // first line: the years to test
1109 { 1990, 1976, 2000, 2030, 1984, },
1111 // second line: TRUE if leap, FALSE otherwise
1112 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
1115 for ( size_t n
= 0; n
< nYears
; n
++ )
1117 int year
= years
[0][n
];
1118 bool should
= years
[1][n
] != 0,
1119 is
= wxDateTime::IsLeapYear(year
);
1121 printf("Year %d is %sa leap year (%s)\n",
1124 should
== is
? "ok" : "ERROR");
1126 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
1130 // test constructing wxDateTime objects
1131 static void TestTimeSet()
1133 puts("\n*** wxDateTime construction test ***");
1135 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1137 const Date
& d1
= testDates
[n
];
1138 wxDateTime dt
= d1
.DT();
1141 d2
.Init(dt
.GetTm());
1143 wxString s1
= d1
.Format(),
1146 printf("Date: %s == %s (%s)\n",
1147 s1
.c_str(), s2
.c_str(),
1148 s1
== s2
? "ok" : "ERROR");
1152 // test time zones stuff
1153 static void TestTimeZones()
1155 puts("\n*** wxDateTime timezone test ***");
1157 wxDateTime now
= wxDateTime::Now();
1159 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
1160 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
1161 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
1162 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
1163 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
1164 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
1166 wxDateTime::Tm tm
= now
.GetTm();
1167 if ( wxDateTime(tm
) != now
)
1169 printf("ERROR: got %s instead of %s\n",
1170 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
1174 // test some minimal support for the dates outside the standard range
1175 static void TestTimeRange()
1177 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1179 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
1181 printf("Unix epoch:\t%s\n",
1182 wxDateTime(2440587.5).Format(fmt
).c_str());
1183 printf("Feb 29, 0: \t%s\n",
1184 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
1185 printf("JDN 0: \t%s\n",
1186 wxDateTime(0.0).Format(fmt
).c_str());
1187 printf("Jan 1, 1AD:\t%s\n",
1188 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
1189 printf("May 29, 2099:\t%s\n",
1190 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
1193 static void TestTimeTicks()
1195 puts("\n*** wxDateTime ticks test ***");
1197 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1199 const Date
& d
= testDates
[n
];
1200 if ( d
.ticks
== -1 )
1203 wxDateTime dt
= d
.DT();
1204 long ticks
= (dt
.GetValue() / 1000).ToLong();
1205 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1206 if ( ticks
== d
.ticks
)
1212 printf(" (ERROR: should be %ld, delta = %ld)\n",
1213 d
.ticks
, ticks
- d
.ticks
);
1216 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
1217 ticks
= (dt
.GetValue() / 1000).ToLong();
1218 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1219 if ( ticks
== d
.gmticks
)
1225 printf(" (ERROR: should be %ld, delta = %ld)\n",
1226 d
.gmticks
, ticks
- d
.gmticks
);
1233 // test conversions to JDN &c
1234 static void TestTimeJDN()
1236 puts("\n*** wxDateTime to JDN test ***");
1238 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1240 const Date
& d
= testDates
[n
];
1241 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1242 double jdn
= dt
.GetJulianDayNumber();
1244 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
1251 printf(" (ERROR: should be %f, delta = %f)\n",
1252 d
.jdn
, jdn
- d
.jdn
);
1257 // test week days computation
1258 static void TestTimeWDays()
1260 puts("\n*** wxDateTime weekday test ***");
1262 // test GetWeekDay()
1264 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1266 const Date
& d
= testDates
[n
];
1267 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1269 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
1272 wxDateTime::GetWeekDayName(wday
).c_str());
1273 if ( wday
== d
.wday
)
1279 printf(" (ERROR: should be %s)\n",
1280 wxDateTime::GetWeekDayName(d
.wday
).c_str());
1286 // test SetToWeekDay()
1287 struct WeekDateTestData
1289 Date date
; // the real date (precomputed)
1290 int nWeek
; // its week index in the month
1291 wxDateTime::WeekDay wday
; // the weekday
1292 wxDateTime::Month month
; // the month
1293 int year
; // and the year
1295 wxString
Format() const
1298 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
1300 case 1: which
= "first"; break;
1301 case 2: which
= "second"; break;
1302 case 3: which
= "third"; break;
1303 case 4: which
= "fourth"; break;
1304 case 5: which
= "fifth"; break;
1306 case -1: which
= "last"; break;
1311 which
+= " from end";
1314 s
.Printf("The %s %s of %s in %d",
1316 wxDateTime::GetWeekDayName(wday
).c_str(),
1317 wxDateTime::GetMonthName(month
).c_str(),
1324 // the array data was generated by the following python program
1326 from DateTime import *
1327 from whrandom import *
1328 from string import *
1330 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1331 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1333 week = DateTimeDelta(7)
1336 year = randint(1900, 2100)
1337 month = randint(1, 12)
1338 day = randint(1, 28)
1339 dt = DateTime(year, month, day)
1340 wday = dt.day_of_week
1342 countFromEnd = choice([-1, 1])
1345 while dt.month is month:
1346 dt = dt - countFromEnd * week
1347 weekNum = weekNum + countFromEnd
1349 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1351 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1352 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1355 static const WeekDateTestData weekDatesTestData
[] =
1357 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
1358 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
1359 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
1360 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
1361 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
1362 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
1363 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
1364 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
1365 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
1366 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
1367 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
1368 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
1369 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
1370 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
1371 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
1372 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
1373 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
1374 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
1375 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
1376 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
1379 static const char *fmt
= "%d-%b-%Y";
1382 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
1384 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
1386 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
1388 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
1390 const Date
& d
= wd
.date
;
1391 if ( d
.SameDay(dt
.GetTm()) )
1397 dt
.Set(d
.day
, d
.month
, d
.year
);
1399 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
1404 // test the computation of (ISO) week numbers
1405 static void TestTimeWNumber()
1407 puts("\n*** wxDateTime week number test ***");
1409 struct WeekNumberTestData
1411 Date date
; // the date
1412 wxDateTime::wxDateTime_t week
; // the week number in the year
1413 wxDateTime::wxDateTime_t wmon
; // the week number in the month
1414 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
1415 wxDateTime::wxDateTime_t dnum
; // day number in the year
1418 // data generated with the following python script:
1420 from DateTime import *
1421 from whrandom import *
1422 from string import *
1424 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1425 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1427 def GetMonthWeek(dt):
1428 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1429 if weekNumMonth < 0:
1430 weekNumMonth = weekNumMonth + 53
1433 def GetLastSundayBefore(dt):
1434 if dt.iso_week[2] == 7:
1437 return dt - DateTimeDelta(dt.iso_week[2])
1440 year = randint(1900, 2100)
1441 month = randint(1, 12)
1442 day = randint(1, 28)
1443 dt = DateTime(year, month, day)
1444 dayNum = dt.day_of_year
1445 weekNum = dt.iso_week[1]
1446 weekNumMonth = GetMonthWeek(dt)
1449 dtSunday = GetLastSundayBefore(dt)
1451 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1452 weekNumMonth2 = weekNumMonth2 + 1
1453 dtSunday = dtSunday - DateTimeDelta(7)
1455 data = { 'day': rjust(`day`, 2), \
1456 'month': monthNames[month - 1], \
1458 'weekNum': rjust(`weekNum`, 2), \
1459 'weekNumMonth': weekNumMonth, \
1460 'weekNumMonth2': weekNumMonth2, \
1461 'dayNum': rjust(`dayNum`, 3) }
1463 print " { { %(day)s, "\
1464 "wxDateTime::%(month)s, "\
1467 "%(weekNumMonth)s, "\
1468 "%(weekNumMonth2)s, "\
1469 "%(dayNum)s }," % data
1472 static const WeekNumberTestData weekNumberTestDates
[] =
1474 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
1475 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
1476 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
1477 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
1478 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
1479 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
1480 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
1481 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
1482 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
1483 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
1484 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
1485 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
1486 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
1487 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
1488 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
1489 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
1490 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
1491 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
1492 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
1493 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
1496 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
1498 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
1499 const Date
& d
= wn
.date
;
1501 wxDateTime dt
= d
.DT();
1503 wxDateTime::wxDateTime_t
1504 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
1505 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1506 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1507 dnum
= dt
.GetDayOfYear();
1509 printf("%s: the day number is %d",
1510 d
.FormatDate().c_str(), dnum
);
1511 if ( dnum
== wn
.dnum
)
1517 printf(" (ERROR: should be %d)", wn
.dnum
);
1520 printf(", week in month is %d", wmon
);
1521 if ( wmon
== wn
.wmon
)
1527 printf(" (ERROR: should be %d)", wn
.wmon
);
1530 printf(" or %d", wmon2
);
1531 if ( wmon2
== wn
.wmon2
)
1537 printf(" (ERROR: should be %d)", wn
.wmon2
);
1540 printf(", week in year is %d", week
);
1541 if ( week
== wn
.week
)
1547 printf(" (ERROR: should be %d)\n", wn
.week
);
1552 // test DST calculations
1553 static void TestTimeDST()
1555 puts("\n*** wxDateTime DST test ***");
1557 printf("DST is%s in effect now.\n\n",
1558 wxDateTime::Now().IsDST() ? "" : " not");
1560 // taken from http://www.energy.ca.gov/daylightsaving.html
1561 static const Date datesDST
[2][2004 - 1900 + 1] =
1564 { 1, wxDateTime::Apr
, 1990 },
1565 { 7, wxDateTime::Apr
, 1991 },
1566 { 5, wxDateTime::Apr
, 1992 },
1567 { 4, wxDateTime::Apr
, 1993 },
1568 { 3, wxDateTime::Apr
, 1994 },
1569 { 2, wxDateTime::Apr
, 1995 },
1570 { 7, wxDateTime::Apr
, 1996 },
1571 { 6, wxDateTime::Apr
, 1997 },
1572 { 5, wxDateTime::Apr
, 1998 },
1573 { 4, wxDateTime::Apr
, 1999 },
1574 { 2, wxDateTime::Apr
, 2000 },
1575 { 1, wxDateTime::Apr
, 2001 },
1576 { 7, wxDateTime::Apr
, 2002 },
1577 { 6, wxDateTime::Apr
, 2003 },
1578 { 4, wxDateTime::Apr
, 2004 },
1581 { 28, wxDateTime::Oct
, 1990 },
1582 { 27, wxDateTime::Oct
, 1991 },
1583 { 25, wxDateTime::Oct
, 1992 },
1584 { 31, wxDateTime::Oct
, 1993 },
1585 { 30, wxDateTime::Oct
, 1994 },
1586 { 29, wxDateTime::Oct
, 1995 },
1587 { 27, wxDateTime::Oct
, 1996 },
1588 { 26, wxDateTime::Oct
, 1997 },
1589 { 25, wxDateTime::Oct
, 1998 },
1590 { 31, wxDateTime::Oct
, 1999 },
1591 { 29, wxDateTime::Oct
, 2000 },
1592 { 28, wxDateTime::Oct
, 2001 },
1593 { 27, wxDateTime::Oct
, 2002 },
1594 { 26, wxDateTime::Oct
, 2003 },
1595 { 31, wxDateTime::Oct
, 2004 },
1600 for ( year
= 1990; year
< 2005; year
++ )
1602 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
1603 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
1605 printf("DST period in the US for year %d: from %s to %s",
1606 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
1608 size_t n
= year
- 1990;
1609 const Date
& dBegin
= datesDST
[0][n
];
1610 const Date
& dEnd
= datesDST
[1][n
];
1612 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
1618 printf(" (ERROR: should be %s %d to %s %d)\n",
1619 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
1620 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
1626 for ( year
= 1990; year
< 2005; year
++ )
1628 printf("DST period in Europe for year %d: from %s to %s\n",
1630 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
1631 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
1635 // test wxDateTime -> text conversion
1636 static void TestTimeFormat()
1638 puts("\n*** wxDateTime formatting test ***");
1640 // some information may be lost during conversion, so store what kind
1641 // of info should we recover after a round trip
1644 CompareNone
, // don't try comparing
1645 CompareBoth
, // dates and times should be identical
1646 CompareDate
, // dates only
1647 CompareTime
// time only
1652 CompareKind compareKind
;
1654 } formatTestFormats
[] =
1656 { CompareBoth
, "---> %c" },
1657 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
1658 { CompareBoth
, "Date is %x, time is %X" },
1659 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
1660 { CompareNone
, "The day of year: %j, the week of year: %W" },
1663 static const Date formatTestDates
[] =
1665 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
1666 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
1668 // this test can't work for other centuries because it uses two digit
1669 // years in formats, so don't even try it
1670 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
1671 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
1672 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
1676 // an extra test (as it doesn't depend on date, don't do it in the loop)
1677 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1679 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
1683 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
1684 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
1686 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
1687 printf("%s", s
.c_str());
1689 // what can we recover?
1690 int kind
= formatTestFormats
[n
].compareKind
;
1694 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
1697 // converion failed - should it have?
1698 if ( kind
== CompareNone
)
1701 puts(" (ERROR: conversion back failed)");
1705 // should have parsed the entire string
1706 puts(" (ERROR: conversion back stopped too soon)");
1710 bool equal
= FALSE
; // suppress compilaer warning
1718 equal
= dt
.IsSameDate(dt2
);
1722 equal
= dt
.IsSameTime(dt2
);
1728 printf(" (ERROR: got back '%s' instead of '%s')\n",
1729 dt2
.Format().c_str(), dt
.Format().c_str());
1740 // test text -> wxDateTime conversion
1741 static void TestTimeParse()
1743 puts("\n*** wxDateTime parse test ***");
1745 struct ParseTestData
1752 static const ParseTestData parseTestDates
[] =
1754 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
1755 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
1758 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
1760 const char *format
= parseTestDates
[n
].format
;
1762 printf("%s => ", format
);
1765 if ( dt
.ParseRfc822Date(format
) )
1767 printf("%s ", dt
.Format().c_str());
1769 if ( parseTestDates
[n
].good
)
1771 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
1778 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
1783 puts("(ERROR: bad format)");
1788 printf("bad format (%s)\n",
1789 parseTestDates
[n
].good
? "ERROR" : "ok");
1794 static void TestInteractive()
1796 puts("\n*** interactive wxDateTime tests ***");
1802 printf("Enter a date: ");
1803 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1807 if ( !dt
.ParseDate(buf
) )
1809 puts("failed to parse the date");
1814 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1815 dt
.FormatISODate().c_str(),
1817 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1818 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1819 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
1822 puts("\n*** done ***");
1825 static void TestTimeArithmetics()
1827 puts("\n*** testing arithmetic operations on wxDateTime ***");
1833 } testArithmData
[] =
1835 { wxDateSpan::Day(), "day" },
1836 { wxDateSpan::Week(), "week" },
1837 { wxDateSpan::Month(), "month" },
1838 { wxDateSpan::Year(), "year" },
1839 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1842 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
1844 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
1846 wxDateSpan span
= testArithmData
[n
].span
;
1850 const char *name
= testArithmData
[n
].name
;
1851 printf("%s + %s = %s, %s - %s = %s\n",
1852 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
1853 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
1855 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
1856 if ( dt1
- span
== dt
)
1862 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1865 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
1866 if ( dt2
+ span
== dt
)
1872 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1875 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
1876 if ( dt2
+ 2*span
== dt1
)
1882 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
1889 static void TestTimeHolidays()
1891 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1893 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
1894 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
1895 dtEnd
= dtStart
.GetLastMonthDay();
1897 wxDateTimeArray hol
;
1898 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
1900 const wxChar
*format
= "%d-%b-%Y (%a)";
1902 printf("All holidays between %s and %s:\n",
1903 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
1905 size_t count
= hol
.GetCount();
1906 for ( size_t n
= 0; n
< count
; n
++ )
1908 printf("\t%s\n", hol
[n
].Format(format
).c_str());
1916 // test compatibility with the old wxDate/wxTime classes
1917 static void TestTimeCompatibility()
1919 puts("\n*** wxDateTime compatibility test ***");
1921 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1922 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1924 double jdnNow
= wxDateTime::Now().GetJDN();
1925 long jdnMidnight
= (long)(jdnNow
- 0.5);
1926 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
1928 jdnMidnight
= wxDate().Set().GetJulianDate();
1929 printf("wxDateTime for today: %s\n",
1930 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
1932 int flags
= wxEUROPEAN
;//wxFULL;
1935 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
1936 for ( int n
= 0; n
< 7; n
++ )
1938 printf("Previous %s is %s\n",
1939 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
1940 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
1946 #endif // TEST_DATETIME
1948 // ----------------------------------------------------------------------------
1950 // ----------------------------------------------------------------------------
1954 #include <wx/thread.h>
1956 static size_t gs_counter
= (size_t)-1;
1957 static wxCriticalSection gs_critsect
;
1958 static wxCondition gs_cond
;
1960 class MyJoinableThread
: public wxThread
1963 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
1964 { m_n
= n
; Create(); }
1966 // thread execution starts here
1967 virtual ExitCode
Entry();
1973 wxThread::ExitCode
MyJoinableThread::Entry()
1975 unsigned long res
= 1;
1976 for ( size_t n
= 1; n
< m_n
; n
++ )
1980 // it's a loooong calculation :-)
1984 return (ExitCode
)res
;
1987 class MyDetachedThread
: public wxThread
1990 MyDetachedThread(size_t n
, char ch
)
1994 m_cancelled
= FALSE
;
1999 // thread execution starts here
2000 virtual ExitCode
Entry();
2003 virtual void OnExit();
2006 size_t m_n
; // number of characters to write
2007 char m_ch
; // character to write
2009 bool m_cancelled
; // FALSE if we exit normally
2012 wxThread::ExitCode
MyDetachedThread::Entry()
2015 wxCriticalSectionLocker
lock(gs_critsect
);
2016 if ( gs_counter
== (size_t)-1 )
2022 for ( size_t n
= 0; n
< m_n
; n
++ )
2024 if ( TestDestroy() )
2034 wxThread::Sleep(100);
2040 void MyDetachedThread::OnExit()
2042 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
2044 wxCriticalSectionLocker
lock(gs_critsect
);
2045 if ( !--gs_counter
&& !m_cancelled
)
2049 void TestDetachedThreads()
2051 puts("\n*** Testing detached threads ***");
2053 static const size_t nThreads
= 3;
2054 MyDetachedThread
*threads
[nThreads
];
2056 for ( n
= 0; n
< nThreads
; n
++ )
2058 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
2061 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
2062 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
2064 for ( n
= 0; n
< nThreads
; n
++ )
2069 // wait until all threads terminate
2075 void TestJoinableThreads()
2077 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2079 // calc 10! in the background
2080 MyJoinableThread
thread(10);
2083 printf("\nThread terminated with exit code %lu.\n",
2084 (unsigned long)thread
.Wait());
2087 void TestThreadSuspend()
2089 puts("\n*** Testing thread suspend/resume functions ***");
2091 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
2095 // this is for this demo only, in a real life program we'd use another
2096 // condition variable which would be signaled from wxThread::Entry() to
2097 // tell us that the thread really started running - but here just wait a
2098 // bit and hope that it will be enough (the problem is, of course, that
2099 // the thread might still not run when we call Pause() which will result
2101 wxThread::Sleep(300);
2103 for ( size_t n
= 0; n
< 3; n
++ )
2107 puts("\nThread suspended");
2110 // don't sleep but resume immediately the first time
2111 wxThread::Sleep(300);
2113 puts("Going to resume the thread");
2118 puts("Waiting until it terminates now");
2120 // wait until the thread terminates
2126 void TestThreadDelete()
2128 // As above, using Sleep() is only for testing here - we must use some
2129 // synchronisation object instead to ensure that the thread is still
2130 // running when we delete it - deleting a detached thread which already
2131 // terminated will lead to a crash!
2133 puts("\n*** Testing thread delete function ***");
2135 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
2139 puts("\nDeleted a thread which didn't start to run yet.");
2141 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
2145 wxThread::Sleep(300);
2149 puts("\nDeleted a running thread.");
2151 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
2155 wxThread::Sleep(300);
2161 puts("\nDeleted a sleeping thread.");
2163 MyJoinableThread
thread3(20);
2168 puts("\nDeleted a joinable thread.");
2170 MyJoinableThread
thread4(2);
2173 wxThread::Sleep(300);
2177 puts("\nDeleted a joinable thread which already terminated.");
2182 #endif // TEST_THREADS
2184 // ----------------------------------------------------------------------------
2186 // ----------------------------------------------------------------------------
2190 void PrintArray(const char* name
, const wxArrayString
& array
)
2192 printf("Dump of the array '%s'\n", name
);
2194 size_t nCount
= array
.GetCount();
2195 for ( size_t n
= 0; n
< nCount
; n
++ )
2197 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
2201 #endif // TEST_ARRAYS
2203 // ----------------------------------------------------------------------------
2205 // ----------------------------------------------------------------------------
2209 #include "wx/timer.h"
2210 #include "wx/tokenzr.h"
2212 static void TestStringConstruction()
2214 puts("*** Testing wxString constructores ***");
2216 #define TEST_CTOR(args, res) \
2219 printf("wxString%s = %s ", #args, s.c_str()); \
2226 printf("(ERROR: should be %s)\n", res); \
2230 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2231 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2232 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2233 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2235 static const wxChar
*s
= _T("?really!");
2236 const wxChar
*start
= wxStrchr(s
, _T('r'));
2237 const wxChar
*end
= wxStrchr(s
, _T('!'));
2238 TEST_CTOR((start
, end
), _T("really"));
2243 static void TestString()
2253 for (int i
= 0; i
< 1000000; ++i
)
2257 c
= "! How'ya doin'?";
2260 c
= "Hello world! What's up?";
2265 printf ("TestString elapsed time: %ld\n", sw
.Time());
2268 static void TestPChar()
2276 for (int i
= 0; i
< 1000000; ++i
)
2278 strcpy (a
, "Hello");
2279 strcpy (b
, " world");
2280 strcpy (c
, "! How'ya doin'?");
2283 strcpy (c
, "Hello world! What's up?");
2284 if (strcmp (c
, a
) == 0)
2288 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
2291 static void TestStringSub()
2293 wxString
s("Hello, world!");
2295 puts("*** Testing wxString substring extraction ***");
2297 printf("String = '%s'\n", s
.c_str());
2298 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
2299 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
2300 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2301 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
2302 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
2303 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
2308 static void TestStringFormat()
2310 puts("*** Testing wxString formatting ***");
2313 s
.Printf("%03d", 18);
2315 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2316 printf("Number 18: %s\n", s
.c_str());
2321 // returns "not found" for npos, value for all others
2322 static wxString
PosToString(size_t res
)
2324 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
2325 : wxString::Format(_T("%u"), res
);
2329 static void TestStringFind()
2331 puts("*** Testing wxString find() functions ***");
2333 static const wxChar
*strToFind
= _T("ell");
2334 static const struct StringFindTest
2338 result
; // of searching "ell" in str
2341 { _T("Well, hello world"), 0, 1 },
2342 { _T("Well, hello world"), 6, 7 },
2343 { _T("Well, hello world"), 9, wxString::npos
},
2346 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
2348 const StringFindTest
& ft
= findTestData
[n
];
2349 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
2351 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2352 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
2354 size_t resTrue
= ft
.result
;
2355 if ( res
== resTrue
)
2361 printf(_T("(ERROR: should be %s)\n"),
2362 PosToString(resTrue
).c_str());
2369 static void TestStringTokenizer()
2371 puts("*** Testing wxStringTokenizer ***");
2373 static const wxChar
*modeNames
[] =
2377 _T("return all empty"),
2382 static const struct StringTokenizerTest
2384 const wxChar
*str
; // string to tokenize
2385 const wxChar
*delims
; // delimiters to use
2386 size_t count
; // count of token
2387 wxStringTokenizerMode mode
; // how should we tokenize it
2388 } tokenizerTestData
[] =
2390 { _T(""), _T(" "), 0 },
2391 { _T("Hello, world"), _T(" "), 2 },
2392 { _T("Hello, world "), _T(" "), 2 },
2393 { _T("Hello, world"), _T(","), 2 },
2394 { _T("Hello, world!"), _T(",!"), 2 },
2395 { _T("Hello,, world!"), _T(",!"), 3 },
2396 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
2397 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2398 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
2399 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
2400 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
2401 { _T("01/02/99"), _T("/-"), 3 },
2402 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
2405 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
2407 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
2408 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
2410 size_t count
= tkz
.CountTokens();
2411 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2412 MakePrintable(tt
.str
).c_str(),
2414 MakePrintable(tt
.delims
).c_str(),
2415 modeNames
[tkz
.GetMode()]);
2416 if ( count
== tt
.count
)
2422 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
2427 // if we emulate strtok(), check that we do it correctly
2428 wxChar
*buf
, *s
, *last
;
2430 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
2432 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
2433 wxStrcpy(buf
, tt
.str
);
2435 s
= wxStrtok(buf
, tt
.delims
, &last
);
2442 // now show the tokens themselves
2444 while ( tkz
.HasMoreTokens() )
2446 wxString token
= tkz
.GetNextToken();
2448 printf(_T("\ttoken %u: '%s'"),
2450 MakePrintable(token
).c_str());
2460 printf(" (ERROR: should be %s)\n", s
);
2463 s
= wxStrtok(NULL
, tt
.delims
, &last
);
2467 // nothing to compare with
2472 if ( count2
!= count
)
2474 puts(_T("\tERROR: token count mismatch"));
2483 #endif // TEST_STRINGS
2485 // ----------------------------------------------------------------------------
2487 // ----------------------------------------------------------------------------
2489 int main(int argc
, char **argv
)
2491 if ( !wxInitialize() )
2493 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
2497 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2499 #endif // TEST_USLEEP
2502 static const wxCmdLineEntryDesc cmdLineDesc
[] =
2504 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
2505 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
2507 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
2508 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
2509 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
2510 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
2512 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
2513 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
2518 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
2520 switch ( parser
.Parse() )
2523 wxLogMessage("Help was given, terminating.");
2527 ShowCmdLine(parser
);
2531 wxLogMessage("Syntax error detected, aborting.");
2534 #endif // TEST_CMDLINE
2544 TestStringConstruction();
2548 TestStringTokenizer();
2550 #endif // TEST_STRINGS
2561 puts("*** Initially:");
2563 PrintArray("a1", a1
);
2565 wxArrayString
a2(a1
);
2566 PrintArray("a2", a2
);
2568 wxSortedArrayString
a3(a1
);
2569 PrintArray("a3", a3
);
2571 puts("*** After deleting a string from a1");
2574 PrintArray("a1", a1
);
2575 PrintArray("a2", a2
);
2576 PrintArray("a3", a3
);
2578 puts("*** After reassigning a1 to a2 and a3");
2580 PrintArray("a2", a2
);
2581 PrintArray("a3", a3
);
2582 #endif // TEST_ARRAYS
2590 #endif // TEST_EXECUTE
2592 #ifdef TEST_FILECONF
2594 #endif // TEST_FILECONF
2598 for ( size_t n
= 0; n
< 8000; n
++ )
2600 s
<< (char)('A' + (n
% 26));
2604 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
2606 // this one shouldn't be truncated
2609 // but this one will because log functions use fixed size buffer
2610 // (note that it doesn't need '\n' at the end neither - will be added
2612 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
2616 int nCPUs
= wxThread::GetCPUCount();
2617 printf("This system has %d CPUs\n", nCPUs
);
2619 wxThread::SetConcurrency(nCPUs
);
2621 if ( argc
> 1 && argv
[1][0] == 't' )
2622 wxLog::AddTraceMask("thread");
2625 TestDetachedThreads();
2627 TestJoinableThreads();
2629 TestThreadSuspend();
2633 #endif // TEST_THREADS
2635 #ifdef TEST_LONGLONG
2636 // seed pseudo random generator
2637 srand((unsigned)time(NULL
));
2643 TestMultiplication();
2648 TestLongLongConversion();
2649 TestBitOperations();
2651 #endif // TEST_LONGLONG
2661 #ifdef TEST_INFO_FUNCTIONS
2664 #endif // TEST_INFO_FUNCTIONS
2674 #endif // TEST_SOCKETS
2678 #endif // TEST_TIMER
2680 #ifdef TEST_DATETIME
2694 TestTimeArithmetics();
2699 #endif // TEST_DATETIME