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
49 //#define TEST_STRINGS
50 //#define TEST_THREADS
53 // ============================================================================
55 // ============================================================================
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
61 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
63 // replace TABs with \t and CRs with \n
64 static wxString
MakePrintable(const wxChar
*s
)
67 (void)str
.Replace(_T("\t"), _T("\\t"));
68 (void)str
.Replace(_T("\n"), _T("\\n"));
69 (void)str
.Replace(_T("\r"), _T("\\r"));
74 #endif // MakePrintable() is used
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
82 #include <wx/cmdline.h>
83 #include <wx/datetime.h>
85 static void ShowCmdLine(const wxCmdLineParser
& parser
)
87 wxString s
= "Input files: ";
89 size_t count
= parser
.GetParamCount();
90 for ( size_t param
= 0; param
< count
; param
++ )
92 s
<< parser
.GetParam(param
) << ' ';
96 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
97 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
102 if ( parser
.Found("o", &strVal
) )
103 s
<< "Output file:\t" << strVal
<< '\n';
104 if ( parser
.Found("i", &strVal
) )
105 s
<< "Input dir:\t" << strVal
<< '\n';
106 if ( parser
.Found("s", &lVal
) )
107 s
<< "Size:\t" << lVal
<< '\n';
108 if ( parser
.Found("d", &dt
) )
109 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
114 #endif // TEST_CMDLINE
116 // ----------------------------------------------------------------------------
118 // ----------------------------------------------------------------------------
124 static void TestDirEnumHelper(wxDir
& dir
,
125 int flags
= wxDIR_DEFAULT
,
126 const wxString
& filespec
= wxEmptyString
)
130 if ( !dir
.IsOpened() )
133 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
136 printf("\t%s\n", filename
.c_str());
138 cont
= dir
.GetNext(&filename
);
144 static void TestDirEnum()
146 wxDir
dir(wxGetCwd());
148 puts("Enumerating everything in current directory:");
149 TestDirEnumHelper(dir
);
151 puts("Enumerating really everything in current directory:");
152 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
154 puts("Enumerating object files in current directory:");
155 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
157 puts("Enumerating directories in current directory:");
158 TestDirEnumHelper(dir
, wxDIR_DIRS
);
160 puts("Enumerating files in current directory:");
161 TestDirEnumHelper(dir
, wxDIR_FILES
);
163 puts("Enumerating files including hidden in current directory:");
164 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
168 #elif defined(__WXMSW__)
171 #error "don't know where the root directory is"
174 puts("Enumerating everything in root directory:");
175 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
177 puts("Enumerating directories in root directory:");
178 TestDirEnumHelper(dir
, wxDIR_DIRS
);
180 puts("Enumerating files in root directory:");
181 TestDirEnumHelper(dir
, wxDIR_FILES
);
183 puts("Enumerating files including hidden in root directory:");
184 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
186 puts("Enumerating files in non existing directory:");
187 wxDir
dirNo("nosuchdir");
188 TestDirEnumHelper(dirNo
);
193 // ----------------------------------------------------------------------------
195 // ----------------------------------------------------------------------------
199 #include <wx/utils.h>
201 static void TestExecute()
203 puts("*** testing wxExecute ***");
206 #define COMMAND "echo hi"
207 #define SHELL_COMMAND "echo hi from shell"
208 #define REDIRECT_COMMAND "date"
209 #elif defined(__WXMSW__)
210 #define COMMAND "command.com -c 'echo hi'"
211 #define SHELL_COMMAND "echo hi"
212 #define REDIRECT_COMMAND COMMAND
214 #error "no command to exec"
217 printf("Testing wxShell: ");
219 if ( wxShell(SHELL_COMMAND
) )
224 printf("Testing wxExecute: ");
226 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
231 #if 0 // no, it doesn't work (yet?)
232 printf("Testing async wxExecute: ");
234 if ( wxExecute(COMMAND
) != 0 )
235 puts("Ok (command launched).");
240 printf("Testing wxExecute with redirection:\n");
241 wxArrayString output
;
242 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
248 size_t count
= output
.GetCount();
249 for ( size_t n
= 0; n
< count
; n
++ )
251 printf("\t%s\n", output
[n
].c_str());
258 #endif // TEST_EXECUTE
260 // ----------------------------------------------------------------------------
262 // ----------------------------------------------------------------------------
266 #include <wx/confbase.h>
267 #include <wx/fileconf.h>
269 static const struct FileConfTestData
271 const wxChar
*name
; // value name
272 const wxChar
*value
; // the value from the file
275 { _T("value1"), _T("one") },
276 { _T("value2"), _T("two") },
277 { _T("novalue"), _T("default") },
280 static void TestFileConfRead()
282 puts("*** testing wxFileConfig loading/reading ***");
284 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
285 _T("testdata.fc"), wxEmptyString
,
286 wxCONFIG_USE_RELATIVE_PATH
);
288 // test simple reading
289 puts("\nReading config file:");
290 wxString
defValue(_T("default")), value
;
291 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
293 const FileConfTestData
& data
= fcTestData
[n
];
294 value
= fileconf
.Read(data
.name
, defValue
);
295 printf("\t%s = %s ", data
.name
, value
.c_str());
296 if ( value
== data
.value
)
302 printf("(ERROR: should be %s)\n", data
.value
);
306 // test enumerating the entries
307 puts("\nEnumerating all root entries:");
310 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
313 printf("\t%s = %s\n",
315 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
317 cont
= fileconf
.GetNextEntry(name
, dummy
);
321 #endif // TEST_FILECONF
323 // ----------------------------------------------------------------------------
325 // ----------------------------------------------------------------------------
333 Foo(int n_
) { n
= n_
; count
++; }
341 size_t Foo::count
= 0;
343 WX_DECLARE_LIST(Foo
, wxListFoos
);
344 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
346 #include <wx/listimpl.cpp>
348 WX_DEFINE_LIST(wxListFoos
);
350 static void TestHash()
352 puts("*** Testing wxHashTable ***\n");
356 hash
.DeleteContents(TRUE
);
358 printf("Hash created: %u foos in hash, %u foos totally\n",
359 hash
.GetCount(), Foo::count
);
361 static const int hashTestData
[] =
363 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
367 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
369 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
372 printf("Hash filled: %u foos in hash, %u foos totally\n",
373 hash
.GetCount(), Foo::count
);
375 puts("Hash access test:");
376 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
378 printf("\tGetting element with key %d, value %d: ",
380 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
383 printf("ERROR, not found.\n");
387 printf("%d (%s)\n", foo
->n
,
388 (size_t)foo
->n
== n
? "ok" : "ERROR");
392 printf("\nTrying to get an element not in hash: ");
394 if ( hash
.Get(1234) || hash
.Get(1, 0) )
396 puts("ERROR: found!");
400 puts("ok (not found)");
404 printf("Hash destroyed: %u foos left\n", Foo::count
);
409 // ----------------------------------------------------------------------------
411 // ----------------------------------------------------------------------------
415 #include <wx/mimetype.h>
417 static void TestMimeEnum()
419 wxMimeTypesManager mimeTM
;
420 wxArrayString mimetypes
;
422 size_t count
= mimeTM
.EnumAllFileTypes(mimetypes
);
424 printf("*** All %u known filetypes: ***\n", count
);
429 for ( size_t n
= 0; n
< count
; n
++ )
431 wxFileType
*filetype
= mimeTM
.GetFileTypeFromMimeType(mimetypes
[n
]);
434 printf("nothing known about the filetype '%s'!\n",
435 mimetypes
[n
].c_str());
439 filetype
->GetDescription(&desc
);
440 filetype
->GetExtensions(exts
);
442 filetype
->GetIcon(NULL
);
445 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
452 printf("\t%s: %s (%s)\n",
453 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
459 // ----------------------------------------------------------------------------
461 // ----------------------------------------------------------------------------
465 #include <wx/longlong.h>
466 #include <wx/timer.h>
468 // make a 64 bit number from 4 16 bit ones
469 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
471 // get a random 64 bit number
472 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
474 #if wxUSE_LONGLONG_WX
475 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
476 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
477 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
478 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
479 #endif // wxUSE_LONGLONG_WX
481 static void TestSpeed()
483 static const long max
= 100000000;
490 for ( n
= 0; n
< max
; n
++ )
495 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
498 #if wxUSE_LONGLONG_NATIVE
503 for ( n
= 0; n
< max
; n
++ )
508 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
510 #endif // wxUSE_LONGLONG_NATIVE
516 for ( n
= 0; n
< max
; n
++ )
521 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
525 static void TestLongLongConversion()
527 puts("*** Testing wxLongLong conversions ***\n");
531 for ( size_t n
= 0; n
< 100000; n
++ )
535 #if wxUSE_LONGLONG_NATIVE
536 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
538 wxASSERT_MSG( a
== b
, "conversions failure" );
540 puts("Can't do it without native long long type, test skipped.");
543 #endif // wxUSE_LONGLONG_NATIVE
545 if ( !(nTested
% 1000) )
557 static void TestMultiplication()
559 puts("*** Testing wxLongLong multiplication ***\n");
563 for ( size_t n
= 0; n
< 100000; n
++ )
568 #if wxUSE_LONGLONG_NATIVE
569 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
570 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
572 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
573 #else // !wxUSE_LONGLONG_NATIVE
574 puts("Can't do it without native long long type, test skipped.");
577 #endif // wxUSE_LONGLONG_NATIVE
579 if ( !(nTested
% 1000) )
591 static void TestDivision()
593 puts("*** Testing wxLongLong division ***\n");
597 for ( size_t n
= 0; n
< 100000; n
++ )
599 // get a random wxLongLong (shifting by 12 the MSB ensures that the
600 // multiplication will not overflow)
601 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
603 // get a random long (not wxLongLong for now) to divide it with
608 #if wxUSE_LONGLONG_NATIVE
609 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
611 wxLongLongNative p
= m
/ l
, s
= m
% l
;
612 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
613 #else // !wxUSE_LONGLONG_NATIVE
615 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
616 #endif // wxUSE_LONGLONG_NATIVE
618 if ( !(nTested
% 1000) )
630 static void TestAddition()
632 puts("*** Testing wxLongLong addition ***\n");
636 for ( size_t n
= 0; n
< 100000; n
++ )
642 #if wxUSE_LONGLONG_NATIVE
643 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
644 wxLongLongNative(b
.GetHi(), b
.GetLo()),
645 "addition failure" );
646 #else // !wxUSE_LONGLONG_NATIVE
647 wxASSERT_MSG( c
- b
== a
, "addition failure" );
648 #endif // wxUSE_LONGLONG_NATIVE
650 if ( !(nTested
% 1000) )
662 static void TestBitOperations()
664 puts("*** Testing wxLongLong bit operation ***\n");
668 for ( size_t n
= 0; n
< 100000; n
++ )
672 #if wxUSE_LONGLONG_NATIVE
673 for ( size_t n
= 0; n
< 33; n
++ )
675 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
680 wxASSERT_MSG( b
== c
, "bit shift failure" );
682 b
= wxLongLongNative(a
.GetHi(), a
.GetLo()) << n
;
685 wxASSERT_MSG( b
== c
, "bit shift failure" );
688 #else // !wxUSE_LONGLONG_NATIVE
689 puts("Can't do it without native long long type, test skipped.");
692 #endif // wxUSE_LONGLONG_NATIVE
694 if ( !(nTested
% 1000) )
709 #endif // TEST_LONGLONG
711 // ----------------------------------------------------------------------------
713 // ----------------------------------------------------------------------------
717 #include <wx/socket.h>
718 #include <wx/protocol/protocol.h>
719 #include <wx/protocol/ftp.h>
720 #include <wx/protocol/http.h>
722 static void TestSocketServer()
724 puts("*** Testing wxSocketServer ***\n");
726 // we want to launch a server
730 wxSocketServer
*server
= new wxSocketServer(addr
);
733 puts("ERROR: failed to bind");
738 puts("Server: waiting for connection...");
740 wxSocketBase
*socket
= server
->Accept();
743 puts("ERROR: wxSocketServer::Accept() failed.");
747 puts("Server: got a client.");
753 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
755 puts("ERROR: in wxSocket::Read.");
774 printf("Server: got '%s'.\n", s
.c_str());
775 if ( s
== _T("bye") )
782 socket
->Write(s
.MakeUpper().c_str(), s
.length());
783 socket
->Write("\r\n", 2);
784 printf("Server: wrote '%s'.\n", s
.c_str());
790 static void TestSocketClient()
792 puts("*** Testing wxSocketClient ***\n");
794 static const char *hostname
= "www.wxwindows.org";
797 addr
.Hostname(hostname
);
800 printf("--- Attempting to connect to %s:80...\n", hostname
);
802 wxSocketClient client
;
803 if ( !client
.Connect(addr
) )
805 printf("ERROR: failed to connect to %s\n", hostname
);
809 printf("--- Connected to %s:%u...\n",
810 addr
.Hostname().c_str(), addr
.Service());
814 // could use simply "GET" here I suppose
816 wxString::Format("GET http://%s/\r\n", hostname
);
817 client
.Write(cmdGet
, cmdGet
.length());
818 printf("--- Sent command '%s' to the server\n",
819 MakePrintable(cmdGet
).c_str());
820 client
.Read(buf
, WXSIZEOF(buf
));
821 printf("--- Server replied:\n%s", buf
);
825 static void TestProtocolFtp()
827 puts("*** Testing wxFTP ***\n");
829 wxLog::AddTraceMask(_T("ftp"));
831 static const char *hostname
= "ftp.wxwindows.org";
833 printf("--- Attempting to connect to %s:21...\n", hostname
);
836 if ( !ftp
.Connect(hostname
) )
838 printf("ERROR: failed to connect to %s\n", hostname
);
842 printf("--- Connected to %s, current directory is '%s'\n",
843 hostname
, ftp
.Pwd().c_str());
844 if ( !ftp
.ChDir(_T("pub")) )
846 puts("ERROR: failed to cd to pub");
850 if ( !ftp
.GetList(files
) )
852 puts("ERROR: failed to get list of files");
856 printf("List of files under '%s':\n", ftp
.Pwd().c_str());
857 size_t count
= files
.GetCount();
858 for ( size_t n
= 0; n
< count
; n
++ )
860 printf("\t%s\n", files
[n
].c_str());
862 puts("End of the file list");
865 if ( !ftp
.ChDir(_T("..")) )
867 puts("ERROR: failed to cd to ..");
870 static const char *filename
= "welcome.msg";
871 wxInputStream
*in
= ftp
.GetInputStream(filename
);
874 puts("ERROR: couldn't get input stream");
878 size_t size
= in
->StreamSize();
879 printf("Reading file %s (%u bytes)...", filename
, size
);
881 char *data
= new char[size
];
882 if ( !in
->Read(data
, size
) )
884 puts("ERROR: read error");
888 printf("\nContents of %s:\n%s\n", filename
, data
);
897 #endif // TEST_SOCKETS
899 // ----------------------------------------------------------------------------
901 // ----------------------------------------------------------------------------
905 #include <wx/timer.h>
906 #include <wx/utils.h>
908 static void TestStopWatch()
910 puts("*** Testing wxStopWatch ***\n");
913 printf("Sleeping 3 seconds...");
915 printf("\telapsed time: %ldms\n", sw
.Time());
918 printf("Sleeping 2 more seconds...");
920 printf("\telapsed time: %ldms\n", sw
.Time());
923 printf("And 3 more seconds...");
925 printf("\telapsed time: %ldms\n", sw
.Time());
928 puts("\nChecking for 'backwards clock' bug...");
929 for ( size_t n
= 0; n
< 70; n
++ )
933 for ( size_t m
= 0; m
< 100000; m
++ )
935 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
937 puts("\ntime is negative - ERROR!");
949 // ----------------------------------------------------------------------------
951 // ----------------------------------------------------------------------------
957 #include <wx/datetime.h>
962 wxDateTime::wxDateTime_t day
;
963 wxDateTime::Month month
;
965 wxDateTime::wxDateTime_t hour
, min
, sec
;
967 wxDateTime::WeekDay wday
;
968 time_t gmticks
, ticks
;
970 void Init(const wxDateTime::Tm
& tm
)
979 gmticks
= ticks
= -1;
982 wxDateTime
DT() const
983 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
985 bool SameDay(const wxDateTime::Tm
& tm
) const
987 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
990 wxString
Format() const
993 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
995 wxDateTime::GetMonthName(month
).c_str(),
997 abs(wxDateTime::ConvertYearToBC(year
)),
998 year
> 0 ? "AD" : "BC");
1002 wxString
FormatDate() const
1005 s
.Printf("%02d-%s-%4d%s",
1007 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1008 abs(wxDateTime::ConvertYearToBC(year
)),
1009 year
> 0 ? "AD" : "BC");
1014 static const Date testDates
[] =
1016 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
1017 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
1018 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
1019 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
1020 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
1021 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
1022 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
1023 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
1024 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
1025 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
1026 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
1027 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
1028 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
1029 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
1030 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
1033 // this test miscellaneous static wxDateTime functions
1034 static void TestTimeStatic()
1036 puts("\n*** wxDateTime static methods test ***");
1038 // some info about the current date
1039 int year
= wxDateTime::GetCurrentYear();
1040 printf("Current year %d is %sa leap one and has %d days.\n",
1042 wxDateTime::IsLeapYear(year
) ? "" : "not ",
1043 wxDateTime::GetNumberOfDays(year
));
1045 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
1046 printf("Current month is '%s' ('%s') and it has %d days\n",
1047 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1048 wxDateTime::GetMonthName(month
).c_str(),
1049 wxDateTime::GetNumberOfDays(month
));
1052 static const size_t nYears
= 5;
1053 static const size_t years
[2][nYears
] =
1055 // first line: the years to test
1056 { 1990, 1976, 2000, 2030, 1984, },
1058 // second line: TRUE if leap, FALSE otherwise
1059 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
1062 for ( size_t n
= 0; n
< nYears
; n
++ )
1064 int year
= years
[0][n
];
1065 bool should
= years
[1][n
] != 0,
1066 is
= wxDateTime::IsLeapYear(year
);
1068 printf("Year %d is %sa leap year (%s)\n",
1071 should
== is
? "ok" : "ERROR");
1073 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
1077 // test constructing wxDateTime objects
1078 static void TestTimeSet()
1080 puts("\n*** wxDateTime construction test ***");
1082 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1084 const Date
& d1
= testDates
[n
];
1085 wxDateTime dt
= d1
.DT();
1088 d2
.Init(dt
.GetTm());
1090 wxString s1
= d1
.Format(),
1093 printf("Date: %s == %s (%s)\n",
1094 s1
.c_str(), s2
.c_str(),
1095 s1
== s2
? "ok" : "ERROR");
1099 // test time zones stuff
1100 static void TestTimeZones()
1102 puts("\n*** wxDateTime timezone test ***");
1104 wxDateTime now
= wxDateTime::Now();
1106 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
1107 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
1108 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
1109 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
1110 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
1111 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
1113 wxDateTime::Tm tm
= now
.GetTm();
1114 if ( wxDateTime(tm
) != now
)
1116 printf("ERROR: got %s instead of %s\n",
1117 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
1121 // test some minimal support for the dates outside the standard range
1122 static void TestTimeRange()
1124 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1126 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
1128 printf("Unix epoch:\t%s\n",
1129 wxDateTime(2440587.5).Format(fmt
).c_str());
1130 printf("Feb 29, 0: \t%s\n",
1131 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
1132 printf("JDN 0: \t%s\n",
1133 wxDateTime(0.0).Format(fmt
).c_str());
1134 printf("Jan 1, 1AD:\t%s\n",
1135 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
1136 printf("May 29, 2099:\t%s\n",
1137 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
1140 static void TestTimeTicks()
1142 puts("\n*** wxDateTime ticks test ***");
1144 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1146 const Date
& d
= testDates
[n
];
1147 if ( d
.ticks
== -1 )
1150 wxDateTime dt
= d
.DT();
1151 long ticks
= (dt
.GetValue() / 1000).ToLong();
1152 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1153 if ( ticks
== d
.ticks
)
1159 printf(" (ERROR: should be %ld, delta = %ld)\n",
1160 d
.ticks
, ticks
- d
.ticks
);
1163 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
1164 ticks
= (dt
.GetValue() / 1000).ToLong();
1165 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1166 if ( ticks
== d
.gmticks
)
1172 printf(" (ERROR: should be %ld, delta = %ld)\n",
1173 d
.gmticks
, ticks
- d
.gmticks
);
1180 // test conversions to JDN &c
1181 static void TestTimeJDN()
1183 puts("\n*** wxDateTime to JDN test ***");
1185 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1187 const Date
& d
= testDates
[n
];
1188 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1189 double jdn
= dt
.GetJulianDayNumber();
1191 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
1198 printf(" (ERROR: should be %f, delta = %f)\n",
1199 d
.jdn
, jdn
- d
.jdn
);
1204 // test week days computation
1205 static void TestTimeWDays()
1207 puts("\n*** wxDateTime weekday test ***");
1209 // test GetWeekDay()
1211 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1213 const Date
& d
= testDates
[n
];
1214 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1216 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
1219 wxDateTime::GetWeekDayName(wday
).c_str());
1220 if ( wday
== d
.wday
)
1226 printf(" (ERROR: should be %s)\n",
1227 wxDateTime::GetWeekDayName(d
.wday
).c_str());
1233 // test SetToWeekDay()
1234 struct WeekDateTestData
1236 Date date
; // the real date (precomputed)
1237 int nWeek
; // its week index in the month
1238 wxDateTime::WeekDay wday
; // the weekday
1239 wxDateTime::Month month
; // the month
1240 int year
; // and the year
1242 wxString
Format() const
1245 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
1247 case 1: which
= "first"; break;
1248 case 2: which
= "second"; break;
1249 case 3: which
= "third"; break;
1250 case 4: which
= "fourth"; break;
1251 case 5: which
= "fifth"; break;
1253 case -1: which
= "last"; break;
1258 which
+= " from end";
1261 s
.Printf("The %s %s of %s in %d",
1263 wxDateTime::GetWeekDayName(wday
).c_str(),
1264 wxDateTime::GetMonthName(month
).c_str(),
1271 // the array data was generated by the following python program
1273 from DateTime import *
1274 from whrandom import *
1275 from string import *
1277 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1278 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1280 week = DateTimeDelta(7)
1283 year = randint(1900, 2100)
1284 month = randint(1, 12)
1285 day = randint(1, 28)
1286 dt = DateTime(year, month, day)
1287 wday = dt.day_of_week
1289 countFromEnd = choice([-1, 1])
1292 while dt.month is month:
1293 dt = dt - countFromEnd * week
1294 weekNum = weekNum + countFromEnd
1296 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1298 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1299 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1302 static const WeekDateTestData weekDatesTestData
[] =
1304 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
1305 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
1306 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
1307 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
1308 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
1309 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
1310 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
1311 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
1312 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
1313 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
1314 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
1315 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
1316 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
1317 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
1318 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
1319 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
1320 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
1321 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
1322 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
1323 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
1326 static const char *fmt
= "%d-%b-%Y";
1329 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
1331 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
1333 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
1335 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
1337 const Date
& d
= wd
.date
;
1338 if ( d
.SameDay(dt
.GetTm()) )
1344 dt
.Set(d
.day
, d
.month
, d
.year
);
1346 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
1351 // test the computation of (ISO) week numbers
1352 static void TestTimeWNumber()
1354 puts("\n*** wxDateTime week number test ***");
1356 struct WeekNumberTestData
1358 Date date
; // the date
1359 wxDateTime::wxDateTime_t week
; // the week number in the year
1360 wxDateTime::wxDateTime_t wmon
; // the week number in the month
1361 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
1362 wxDateTime::wxDateTime_t dnum
; // day number in the year
1365 // data generated with the following python script:
1367 from DateTime import *
1368 from whrandom import *
1369 from string import *
1371 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1372 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1374 def GetMonthWeek(dt):
1375 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1376 if weekNumMonth < 0:
1377 weekNumMonth = weekNumMonth + 53
1380 def GetLastSundayBefore(dt):
1381 if dt.iso_week[2] == 7:
1384 return dt - DateTimeDelta(dt.iso_week[2])
1387 year = randint(1900, 2100)
1388 month = randint(1, 12)
1389 day = randint(1, 28)
1390 dt = DateTime(year, month, day)
1391 dayNum = dt.day_of_year
1392 weekNum = dt.iso_week[1]
1393 weekNumMonth = GetMonthWeek(dt)
1396 dtSunday = GetLastSundayBefore(dt)
1398 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1399 weekNumMonth2 = weekNumMonth2 + 1
1400 dtSunday = dtSunday - DateTimeDelta(7)
1402 data = { 'day': rjust(`day`, 2), \
1403 'month': monthNames[month - 1], \
1405 'weekNum': rjust(`weekNum`, 2), \
1406 'weekNumMonth': weekNumMonth, \
1407 'weekNumMonth2': weekNumMonth2, \
1408 'dayNum': rjust(`dayNum`, 3) }
1410 print " { { %(day)s, "\
1411 "wxDateTime::%(month)s, "\
1414 "%(weekNumMonth)s, "\
1415 "%(weekNumMonth2)s, "\
1416 "%(dayNum)s }," % data
1419 static const WeekNumberTestData weekNumberTestDates
[] =
1421 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
1422 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
1423 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
1424 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
1425 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
1426 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
1427 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
1428 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
1429 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
1430 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
1431 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
1432 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
1433 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
1434 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
1435 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
1436 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
1437 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
1438 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
1439 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
1440 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
1443 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
1445 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
1446 const Date
& d
= wn
.date
;
1448 wxDateTime dt
= d
.DT();
1450 wxDateTime::wxDateTime_t
1451 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
1452 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1453 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1454 dnum
= dt
.GetDayOfYear();
1456 printf("%s: the day number is %d",
1457 d
.FormatDate().c_str(), dnum
);
1458 if ( dnum
== wn
.dnum
)
1464 printf(" (ERROR: should be %d)", wn
.dnum
);
1467 printf(", week in month is %d", wmon
);
1468 if ( wmon
== wn
.wmon
)
1474 printf(" (ERROR: should be %d)", wn
.wmon
);
1477 printf(" or %d", wmon2
);
1478 if ( wmon2
== wn
.wmon2
)
1484 printf(" (ERROR: should be %d)", wn
.wmon2
);
1487 printf(", week in year is %d", week
);
1488 if ( week
== wn
.week
)
1494 printf(" (ERROR: should be %d)\n", wn
.week
);
1499 // test DST calculations
1500 static void TestTimeDST()
1502 puts("\n*** wxDateTime DST test ***");
1504 printf("DST is%s in effect now.\n\n",
1505 wxDateTime::Now().IsDST() ? "" : " not");
1507 // taken from http://www.energy.ca.gov/daylightsaving.html
1508 static const Date datesDST
[2][2004 - 1900 + 1] =
1511 { 1, wxDateTime::Apr
, 1990 },
1512 { 7, wxDateTime::Apr
, 1991 },
1513 { 5, wxDateTime::Apr
, 1992 },
1514 { 4, wxDateTime::Apr
, 1993 },
1515 { 3, wxDateTime::Apr
, 1994 },
1516 { 2, wxDateTime::Apr
, 1995 },
1517 { 7, wxDateTime::Apr
, 1996 },
1518 { 6, wxDateTime::Apr
, 1997 },
1519 { 5, wxDateTime::Apr
, 1998 },
1520 { 4, wxDateTime::Apr
, 1999 },
1521 { 2, wxDateTime::Apr
, 2000 },
1522 { 1, wxDateTime::Apr
, 2001 },
1523 { 7, wxDateTime::Apr
, 2002 },
1524 { 6, wxDateTime::Apr
, 2003 },
1525 { 4, wxDateTime::Apr
, 2004 },
1528 { 28, wxDateTime::Oct
, 1990 },
1529 { 27, wxDateTime::Oct
, 1991 },
1530 { 25, wxDateTime::Oct
, 1992 },
1531 { 31, wxDateTime::Oct
, 1993 },
1532 { 30, wxDateTime::Oct
, 1994 },
1533 { 29, wxDateTime::Oct
, 1995 },
1534 { 27, wxDateTime::Oct
, 1996 },
1535 { 26, wxDateTime::Oct
, 1997 },
1536 { 25, wxDateTime::Oct
, 1998 },
1537 { 31, wxDateTime::Oct
, 1999 },
1538 { 29, wxDateTime::Oct
, 2000 },
1539 { 28, wxDateTime::Oct
, 2001 },
1540 { 27, wxDateTime::Oct
, 2002 },
1541 { 26, wxDateTime::Oct
, 2003 },
1542 { 31, wxDateTime::Oct
, 2004 },
1547 for ( year
= 1990; year
< 2005; year
++ )
1549 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
1550 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
1552 printf("DST period in the US for year %d: from %s to %s",
1553 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
1555 size_t n
= year
- 1990;
1556 const Date
& dBegin
= datesDST
[0][n
];
1557 const Date
& dEnd
= datesDST
[1][n
];
1559 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
1565 printf(" (ERROR: should be %s %d to %s %d)\n",
1566 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
1567 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
1573 for ( year
= 1990; year
< 2005; year
++ )
1575 printf("DST period in Europe for year %d: from %s to %s\n",
1577 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
1578 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
1582 // test wxDateTime -> text conversion
1583 static void TestTimeFormat()
1585 puts("\n*** wxDateTime formatting test ***");
1587 // some information may be lost during conversion, so store what kind
1588 // of info should we recover after a round trip
1591 CompareNone
, // don't try comparing
1592 CompareBoth
, // dates and times should be identical
1593 CompareDate
, // dates only
1594 CompareTime
// time only
1599 CompareKind compareKind
;
1601 } formatTestFormats
[] =
1603 { CompareBoth
, "---> %c" },
1604 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
1605 { CompareBoth
, "Date is %x, time is %X" },
1606 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
1607 { CompareNone
, "The day of year: %j, the week of year: %W" },
1610 static const Date formatTestDates
[] =
1612 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
1613 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
1615 // this test can't work for other centuries because it uses two digit
1616 // years in formats, so don't even try it
1617 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
1618 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
1619 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
1623 // an extra test (as it doesn't depend on date, don't do it in the loop)
1624 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1626 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
1630 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
1631 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
1633 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
1634 printf("%s", s
.c_str());
1636 // what can we recover?
1637 int kind
= formatTestFormats
[n
].compareKind
;
1641 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
1644 // converion failed - should it have?
1645 if ( kind
== CompareNone
)
1648 puts(" (ERROR: conversion back failed)");
1652 // should have parsed the entire string
1653 puts(" (ERROR: conversion back stopped too soon)");
1657 bool equal
= FALSE
; // suppress compilaer warning
1665 equal
= dt
.IsSameDate(dt2
);
1669 equal
= dt
.IsSameTime(dt2
);
1675 printf(" (ERROR: got back '%s' instead of '%s')\n",
1676 dt2
.Format().c_str(), dt
.Format().c_str());
1687 // test text -> wxDateTime conversion
1688 static void TestTimeParse()
1690 puts("\n*** wxDateTime parse test ***");
1692 struct ParseTestData
1699 static const ParseTestData parseTestDates
[] =
1701 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
1702 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
1705 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
1707 const char *format
= parseTestDates
[n
].format
;
1709 printf("%s => ", format
);
1712 if ( dt
.ParseRfc822Date(format
) )
1714 printf("%s ", dt
.Format().c_str());
1716 if ( parseTestDates
[n
].good
)
1718 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
1725 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
1730 puts("(ERROR: bad format)");
1735 printf("bad format (%s)\n",
1736 parseTestDates
[n
].good
? "ERROR" : "ok");
1741 static void TestInteractive()
1743 puts("\n*** interactive wxDateTime tests ***");
1749 printf("Enter a date: ");
1750 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1754 if ( !dt
.ParseDate(buf
) )
1756 puts("failed to parse the date");
1761 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1762 dt
.FormatISODate().c_str(),
1764 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1765 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1766 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
1769 puts("\n*** done ***");
1772 static void TestTimeArithmetics()
1774 puts("\n*** testing arithmetic operations on wxDateTime ***");
1780 } testArithmData
[] =
1782 { wxDateSpan::Day(), "day" },
1783 { wxDateSpan::Week(), "week" },
1784 { wxDateSpan::Month(), "month" },
1785 { wxDateSpan::Year(), "year" },
1786 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1789 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
1791 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
1793 wxDateSpan span
= testArithmData
[n
].span
;
1797 const char *name
= testArithmData
[n
].name
;
1798 printf("%s + %s = %s, %s - %s = %s\n",
1799 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
1800 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
1802 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
1803 if ( dt1
- span
== dt
)
1809 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1812 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
1813 if ( dt2
+ span
== dt
)
1819 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1822 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
1823 if ( dt2
+ 2*span
== dt1
)
1829 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
1836 static void TestTimeHolidays()
1838 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1840 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
1841 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
1842 dtEnd
= dtStart
.GetLastMonthDay();
1844 wxDateTimeArray hol
;
1845 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
1847 const wxChar
*format
= "%d-%b-%Y (%a)";
1849 printf("All holidays between %s and %s:\n",
1850 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
1852 size_t count
= hol
.GetCount();
1853 for ( size_t n
= 0; n
< count
; n
++ )
1855 printf("\t%s\n", hol
[n
].Format(format
).c_str());
1863 // test compatibility with the old wxDate/wxTime classes
1864 static void TestTimeCompatibility()
1866 puts("\n*** wxDateTime compatibility test ***");
1868 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1869 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1871 double jdnNow
= wxDateTime::Now().GetJDN();
1872 long jdnMidnight
= (long)(jdnNow
- 0.5);
1873 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
1875 jdnMidnight
= wxDate().Set().GetJulianDate();
1876 printf("wxDateTime for today: %s\n",
1877 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
1879 int flags
= wxEUROPEAN
;//wxFULL;
1882 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
1883 for ( int n
= 0; n
< 7; n
++ )
1885 printf("Previous %s is %s\n",
1886 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
1887 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
1893 #endif // TEST_DATETIME
1895 // ----------------------------------------------------------------------------
1897 // ----------------------------------------------------------------------------
1901 #include <wx/thread.h>
1903 static size_t gs_counter
= (size_t)-1;
1904 static wxCriticalSection gs_critsect
;
1905 static wxCondition gs_cond
;
1907 class MyJoinableThread
: public wxThread
1910 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
1911 { m_n
= n
; Create(); }
1913 // thread execution starts here
1914 virtual ExitCode
Entry();
1920 wxThread::ExitCode
MyJoinableThread::Entry()
1922 unsigned long res
= 1;
1923 for ( size_t n
= 1; n
< m_n
; n
++ )
1927 // it's a loooong calculation :-)
1931 return (ExitCode
)res
;
1934 class MyDetachedThread
: public wxThread
1937 MyDetachedThread(size_t n
, char ch
)
1941 m_cancelled
= FALSE
;
1946 // thread execution starts here
1947 virtual ExitCode
Entry();
1950 virtual void OnExit();
1953 size_t m_n
; // number of characters to write
1954 char m_ch
; // character to write
1956 bool m_cancelled
; // FALSE if we exit normally
1959 wxThread::ExitCode
MyDetachedThread::Entry()
1962 wxCriticalSectionLocker
lock(gs_critsect
);
1963 if ( gs_counter
== (size_t)-1 )
1969 for ( size_t n
= 0; n
< m_n
; n
++ )
1971 if ( TestDestroy() )
1981 wxThread::Sleep(100);
1987 void MyDetachedThread::OnExit()
1989 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
1991 wxCriticalSectionLocker
lock(gs_critsect
);
1992 if ( !--gs_counter
&& !m_cancelled
)
1996 void TestDetachedThreads()
1998 puts("\n*** Testing detached threads ***");
2000 static const size_t nThreads
= 3;
2001 MyDetachedThread
*threads
[nThreads
];
2003 for ( n
= 0; n
< nThreads
; n
++ )
2005 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
2008 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
2009 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
2011 for ( n
= 0; n
< nThreads
; n
++ )
2016 // wait until all threads terminate
2022 void TestJoinableThreads()
2024 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2026 // calc 10! in the background
2027 MyJoinableThread
thread(10);
2030 printf("\nThread terminated with exit code %lu.\n",
2031 (unsigned long)thread
.Wait());
2034 void TestThreadSuspend()
2036 puts("\n*** Testing thread suspend/resume functions ***");
2038 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
2042 // this is for this demo only, in a real life program we'd use another
2043 // condition variable which would be signaled from wxThread::Entry() to
2044 // tell us that the thread really started running - but here just wait a
2045 // bit and hope that it will be enough (the problem is, of course, that
2046 // the thread might still not run when we call Pause() which will result
2048 wxThread::Sleep(300);
2050 for ( size_t n
= 0; n
< 3; n
++ )
2054 puts("\nThread suspended");
2057 // don't sleep but resume immediately the first time
2058 wxThread::Sleep(300);
2060 puts("Going to resume the thread");
2065 puts("Waiting until it terminates now");
2067 // wait until the thread terminates
2073 void TestThreadDelete()
2075 // As above, using Sleep() is only for testing here - we must use some
2076 // synchronisation object instead to ensure that the thread is still
2077 // running when we delete it - deleting a detached thread which already
2078 // terminated will lead to a crash!
2080 puts("\n*** Testing thread delete function ***");
2082 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
2086 puts("\nDeleted a thread which didn't start to run yet.");
2088 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
2092 wxThread::Sleep(300);
2096 puts("\nDeleted a running thread.");
2098 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
2102 wxThread::Sleep(300);
2108 puts("\nDeleted a sleeping thread.");
2110 MyJoinableThread
thread3(20);
2115 puts("\nDeleted a joinable thread.");
2117 MyJoinableThread
thread4(2);
2120 wxThread::Sleep(300);
2124 puts("\nDeleted a joinable thread which already terminated.");
2129 #endif // TEST_THREADS
2131 // ----------------------------------------------------------------------------
2133 // ----------------------------------------------------------------------------
2137 void PrintArray(const char* name
, const wxArrayString
& array
)
2139 printf("Dump of the array '%s'\n", name
);
2141 size_t nCount
= array
.GetCount();
2142 for ( size_t n
= 0; n
< nCount
; n
++ )
2144 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
2148 #endif // TEST_ARRAYS
2150 // ----------------------------------------------------------------------------
2152 // ----------------------------------------------------------------------------
2156 #include "wx/timer.h"
2157 #include "wx/tokenzr.h"
2159 static void TestStringConstruction()
2161 puts("*** Testing wxString constructores ***");
2163 #define TEST_CTOR(args, res) \
2166 printf("wxString%s = %s ", #args, s.c_str()); \
2173 printf("(ERROR: should be %s)\n", res); \
2177 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2178 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2179 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2180 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2182 static const wxChar
*s
= _T("?really!");
2183 const wxChar
*start
= wxStrchr(s
, _T('r'));
2184 const wxChar
*end
= wxStrchr(s
, _T('!'));
2185 TEST_CTOR((start
, end
), _T("really"));
2190 static void TestString()
2200 for (int i
= 0; i
< 1000000; ++i
)
2204 c
= "! How'ya doin'?";
2207 c
= "Hello world! What's up?";
2212 printf ("TestString elapsed time: %ld\n", sw
.Time());
2215 static void TestPChar()
2223 for (int i
= 0; i
< 1000000; ++i
)
2225 strcpy (a
, "Hello");
2226 strcpy (b
, " world");
2227 strcpy (c
, "! How'ya doin'?");
2230 strcpy (c
, "Hello world! What's up?");
2231 if (strcmp (c
, a
) == 0)
2235 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
2238 static void TestStringSub()
2240 wxString
s("Hello, world!");
2242 puts("*** Testing wxString substring extraction ***");
2244 printf("String = '%s'\n", s
.c_str());
2245 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
2246 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
2247 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2248 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
2249 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
2250 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
2255 static void TestStringFormat()
2257 puts("*** Testing wxString formatting ***");
2260 s
.Printf("%03d", 18);
2262 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2263 printf("Number 18: %s\n", s
.c_str());
2268 // returns "not found" for npos, value for all others
2269 static wxString
PosToString(size_t res
)
2271 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
2272 : wxString::Format(_T("%u"), res
);
2276 static void TestStringFind()
2278 puts("*** Testing wxString find() functions ***");
2280 static const wxChar
*strToFind
= _T("ell");
2281 static const struct StringFindTest
2285 result
; // of searching "ell" in str
2288 { _T("Well, hello world"), 0, 1 },
2289 { _T("Well, hello world"), 6, 7 },
2290 { _T("Well, hello world"), 9, wxString::npos
},
2293 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
2295 const StringFindTest
& ft
= findTestData
[n
];
2296 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
2298 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2299 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
2301 size_t resTrue
= ft
.result
;
2302 if ( res
== resTrue
)
2308 printf(_T("(ERROR: should be %s)\n"),
2309 PosToString(resTrue
).c_str());
2316 static void TestStringTokenizer()
2318 puts("*** Testing wxStringTokenizer ***");
2320 static const wxChar
*modeNames
[] =
2324 _T("return all empty"),
2329 static const struct StringTokenizerTest
2331 const wxChar
*str
; // string to tokenize
2332 const wxChar
*delims
; // delimiters to use
2333 size_t count
; // count of token
2334 wxStringTokenizerMode mode
; // how should we tokenize it
2335 } tokenizerTestData
[] =
2337 { _T(""), _T(" "), 0 },
2338 { _T("Hello, world"), _T(" "), 2 },
2339 { _T("Hello, world "), _T(" "), 2 },
2340 { _T("Hello, world"), _T(","), 2 },
2341 { _T("Hello, world!"), _T(",!"), 2 },
2342 { _T("Hello,, world!"), _T(",!"), 3 },
2343 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
2344 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2345 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
2346 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
2347 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
2348 { _T("01/02/99"), _T("/-"), 3 },
2349 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
2352 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
2354 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
2355 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
2357 size_t count
= tkz
.CountTokens();
2358 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2359 MakePrintable(tt
.str
).c_str(),
2361 MakePrintable(tt
.delims
).c_str(),
2362 modeNames
[tkz
.GetMode()]);
2363 if ( count
== tt
.count
)
2369 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
2374 // if we emulate strtok(), check that we do it correctly
2375 wxChar
*buf
, *s
, *last
;
2377 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
2379 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
2380 wxStrcpy(buf
, tt
.str
);
2382 s
= wxStrtok(buf
, tt
.delims
, &last
);
2389 // now show the tokens themselves
2391 while ( tkz
.HasMoreTokens() )
2393 wxString token
= tkz
.GetNextToken();
2395 printf(_T("\ttoken %u: '%s'"),
2397 MakePrintable(token
).c_str());
2407 printf(" (ERROR: should be %s)\n", s
);
2410 s
= wxStrtok(NULL
, tt
.delims
, &last
);
2414 // nothing to compare with
2419 if ( count2
!= count
)
2421 puts(_T("\tERROR: token count mismatch"));
2430 #endif // TEST_STRINGS
2432 // ----------------------------------------------------------------------------
2434 // ----------------------------------------------------------------------------
2436 int main(int argc
, char **argv
)
2438 if ( !wxInitialize() )
2440 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
2444 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2446 #endif // TEST_USLEEP
2449 static const wxCmdLineEntryDesc cmdLineDesc
[] =
2451 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
2452 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
2454 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
2455 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
2456 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
2457 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
2459 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
2460 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
2465 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
2467 switch ( parser
.Parse() )
2470 wxLogMessage("Help was given, terminating.");
2474 ShowCmdLine(parser
);
2478 wxLogMessage("Syntax error detected, aborting.");
2481 #endif // TEST_CMDLINE
2491 TestStringConstruction();
2495 TestStringTokenizer();
2497 #endif // TEST_STRINGS
2508 puts("*** Initially:");
2510 PrintArray("a1", a1
);
2512 wxArrayString
a2(a1
);
2513 PrintArray("a2", a2
);
2515 wxSortedArrayString
a3(a1
);
2516 PrintArray("a3", a3
);
2518 puts("*** After deleting a string from a1");
2521 PrintArray("a1", a1
);
2522 PrintArray("a2", a2
);
2523 PrintArray("a3", a3
);
2525 puts("*** After reassigning a1 to a2 and a3");
2527 PrintArray("a2", a2
);
2528 PrintArray("a3", a3
);
2529 #endif // TEST_ARRAYS
2537 #endif // TEST_EXECUTE
2539 #ifdef TEST_FILECONF
2541 #endif // TEST_FILECONF
2545 for ( size_t n
= 0; n
< 8000; n
++ )
2547 s
<< (char)('A' + (n
% 26));
2551 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
2553 // this one shouldn't be truncated
2556 // but this one will because log functions use fixed size buffer
2557 // (note that it doesn't need '\n' at the end neither - will be added
2559 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
2563 int nCPUs
= wxThread::GetCPUCount();
2564 printf("This system has %d CPUs\n", nCPUs
);
2566 wxThread::SetConcurrency(nCPUs
);
2568 if ( argc
> 1 && argv
[1][0] == 't' )
2569 wxLog::AddTraceMask("thread");
2572 TestDetachedThreads();
2574 TestJoinableThreads();
2576 TestThreadSuspend();
2580 #endif // TEST_THREADS
2582 #ifdef TEST_LONGLONG
2583 // seed pseudo random generator
2584 srand((unsigned)time(NULL
));
2590 TestMultiplication();
2595 TestLongLongConversion();
2596 TestBitOperations();
2598 #endif // TEST_LONGLONG
2616 #endif // TEST_SOCKETS
2620 #endif // TEST_TIMER
2622 #ifdef TEST_DATETIME
2636 TestTimeArithmetics();
2641 #endif // TEST_DATETIME