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());
792 static void TestSocketClient()
794 puts("*** Testing wxSocketClient ***\n");
796 static const char *hostname
= "www.wxwindows.org";
799 addr
.Hostname(hostname
);
802 printf("--- Attempting to connect to %s:80...\n", hostname
);
804 wxSocketClient client
;
805 if ( !client
.Connect(addr
) )
807 printf("ERROR: failed to connect to %s\n", hostname
);
811 printf("--- Connected to %s:%u...\n",
812 addr
.Hostname().c_str(), addr
.Service());
816 // could use simply "GET" here I suppose
818 wxString::Format("GET http://%s/\r\n", hostname
);
819 client
.Write(cmdGet
, cmdGet
.length());
820 printf("--- Sent command '%s' to the server\n",
821 MakePrintable(cmdGet
).c_str());
822 client
.Read(buf
, WXSIZEOF(buf
));
823 printf("--- Server replied:\n%s", buf
);
827 static void TestProtocolFtp()
829 puts("*** Testing wxFTP ***\n");
831 wxLog::AddTraceMask(_T("ftp"));
833 static const char *hostname
= "ftp.wxwindows.org";
835 printf("--- Attempting to connect to %s:21...\n", hostname
);
838 if ( !ftp
.Connect(hostname
) )
840 printf("ERROR: failed to connect to %s\n", hostname
);
844 printf("--- Connected to %s, current directory is '%s'\n",
845 hostname
, ftp
.Pwd().c_str());
846 if ( !ftp
.ChDir(_T("pub")) )
848 puts("ERROR: failed to cd to pub");
852 if ( !ftp
.GetList(files
) )
854 puts("ERROR: failed to get list of files");
858 printf("List of files under '%s':\n", ftp
.Pwd().c_str());
859 size_t count
= files
.GetCount();
860 for ( size_t n
= 0; n
< count
; n
++ )
862 printf("\t%s\n", files
[n
].c_str());
864 puts("End of the file list");
867 if ( !ftp
.ChDir(_T("..")) )
869 puts("ERROR: failed to cd to ..");
872 static const char *filename
= "welcome.msg";
873 wxInputStream
*in
= ftp
.GetInputStream(filename
);
876 puts("ERROR: couldn't get input stream");
880 size_t size
= in
->StreamSize();
881 printf("Reading file %s (%u bytes)...", filename
, size
);
883 char *data
= new char[size
];
884 if ( !in
->Read(data
, size
) )
886 puts("ERROR: read error");
890 printf("\nContents of %s:\n%s\n", filename
, data
);
899 #endif // TEST_SOCKETS
901 // ----------------------------------------------------------------------------
903 // ----------------------------------------------------------------------------
907 #include <wx/timer.h>
908 #include <wx/utils.h>
910 static void TestStopWatch()
912 puts("*** Testing wxStopWatch ***\n");
915 printf("Sleeping 3 seconds...");
917 printf("\telapsed time: %ldms\n", sw
.Time());
920 printf("Sleeping 2 more seconds...");
922 printf("\telapsed time: %ldms\n", sw
.Time());
925 printf("And 3 more seconds...");
927 printf("\telapsed time: %ldms\n", sw
.Time());
930 puts("\nChecking for 'backwards clock' bug...");
931 for ( size_t n
= 0; n
< 70; n
++ )
935 for ( size_t m
= 0; m
< 100000; m
++ )
937 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
939 puts("\ntime is negative - ERROR!");
951 // ----------------------------------------------------------------------------
953 // ----------------------------------------------------------------------------
959 #include <wx/datetime.h>
964 wxDateTime::wxDateTime_t day
;
965 wxDateTime::Month month
;
967 wxDateTime::wxDateTime_t hour
, min
, sec
;
969 wxDateTime::WeekDay wday
;
970 time_t gmticks
, ticks
;
972 void Init(const wxDateTime::Tm
& tm
)
981 gmticks
= ticks
= -1;
984 wxDateTime
DT() const
985 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
987 bool SameDay(const wxDateTime::Tm
& tm
) const
989 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
992 wxString
Format() const
995 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
997 wxDateTime::GetMonthName(month
).c_str(),
999 abs(wxDateTime::ConvertYearToBC(year
)),
1000 year
> 0 ? "AD" : "BC");
1004 wxString
FormatDate() const
1007 s
.Printf("%02d-%s-%4d%s",
1009 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1010 abs(wxDateTime::ConvertYearToBC(year
)),
1011 year
> 0 ? "AD" : "BC");
1016 static const Date testDates
[] =
1018 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
1019 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
1020 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
1021 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
1022 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
1023 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
1024 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
1025 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
1026 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
1027 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
1028 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
1029 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
1030 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
1031 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
1032 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
1035 // this test miscellaneous static wxDateTime functions
1036 static void TestTimeStatic()
1038 puts("\n*** wxDateTime static methods test ***");
1040 // some info about the current date
1041 int year
= wxDateTime::GetCurrentYear();
1042 printf("Current year %d is %sa leap one and has %d days.\n",
1044 wxDateTime::IsLeapYear(year
) ? "" : "not ",
1045 wxDateTime::GetNumberOfDays(year
));
1047 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
1048 printf("Current month is '%s' ('%s') and it has %d days\n",
1049 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1050 wxDateTime::GetMonthName(month
).c_str(),
1051 wxDateTime::GetNumberOfDays(month
));
1054 static const size_t nYears
= 5;
1055 static const size_t years
[2][nYears
] =
1057 // first line: the years to test
1058 { 1990, 1976, 2000, 2030, 1984, },
1060 // second line: TRUE if leap, FALSE otherwise
1061 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
1064 for ( size_t n
= 0; n
< nYears
; n
++ )
1066 int year
= years
[0][n
];
1067 bool should
= years
[1][n
] != 0,
1068 is
= wxDateTime::IsLeapYear(year
);
1070 printf("Year %d is %sa leap year (%s)\n",
1073 should
== is
? "ok" : "ERROR");
1075 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
1079 // test constructing wxDateTime objects
1080 static void TestTimeSet()
1082 puts("\n*** wxDateTime construction test ***");
1084 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1086 const Date
& d1
= testDates
[n
];
1087 wxDateTime dt
= d1
.DT();
1090 d2
.Init(dt
.GetTm());
1092 wxString s1
= d1
.Format(),
1095 printf("Date: %s == %s (%s)\n",
1096 s1
.c_str(), s2
.c_str(),
1097 s1
== s2
? "ok" : "ERROR");
1101 // test time zones stuff
1102 static void TestTimeZones()
1104 puts("\n*** wxDateTime timezone test ***");
1106 wxDateTime now
= wxDateTime::Now();
1108 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
1109 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
1110 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
1111 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
1112 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
1113 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
1115 wxDateTime::Tm tm
= now
.GetTm();
1116 if ( wxDateTime(tm
) != now
)
1118 printf("ERROR: got %s instead of %s\n",
1119 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
1123 // test some minimal support for the dates outside the standard range
1124 static void TestTimeRange()
1126 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1128 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
1130 printf("Unix epoch:\t%s\n",
1131 wxDateTime(2440587.5).Format(fmt
).c_str());
1132 printf("Feb 29, 0: \t%s\n",
1133 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
1134 printf("JDN 0: \t%s\n",
1135 wxDateTime(0.0).Format(fmt
).c_str());
1136 printf("Jan 1, 1AD:\t%s\n",
1137 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
1138 printf("May 29, 2099:\t%s\n",
1139 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
1142 static void TestTimeTicks()
1144 puts("\n*** wxDateTime ticks test ***");
1146 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1148 const Date
& d
= testDates
[n
];
1149 if ( d
.ticks
== -1 )
1152 wxDateTime dt
= d
.DT();
1153 long ticks
= (dt
.GetValue() / 1000).ToLong();
1154 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1155 if ( ticks
== d
.ticks
)
1161 printf(" (ERROR: should be %ld, delta = %ld)\n",
1162 d
.ticks
, ticks
- d
.ticks
);
1165 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
1166 ticks
= (dt
.GetValue() / 1000).ToLong();
1167 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1168 if ( ticks
== d
.gmticks
)
1174 printf(" (ERROR: should be %ld, delta = %ld)\n",
1175 d
.gmticks
, ticks
- d
.gmticks
);
1182 // test conversions to JDN &c
1183 static void TestTimeJDN()
1185 puts("\n*** wxDateTime to JDN test ***");
1187 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1189 const Date
& d
= testDates
[n
];
1190 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1191 double jdn
= dt
.GetJulianDayNumber();
1193 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
1200 printf(" (ERROR: should be %f, delta = %f)\n",
1201 d
.jdn
, jdn
- d
.jdn
);
1206 // test week days computation
1207 static void TestTimeWDays()
1209 puts("\n*** wxDateTime weekday test ***");
1211 // test GetWeekDay()
1213 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1215 const Date
& d
= testDates
[n
];
1216 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1218 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
1221 wxDateTime::GetWeekDayName(wday
).c_str());
1222 if ( wday
== d
.wday
)
1228 printf(" (ERROR: should be %s)\n",
1229 wxDateTime::GetWeekDayName(d
.wday
).c_str());
1235 // test SetToWeekDay()
1236 struct WeekDateTestData
1238 Date date
; // the real date (precomputed)
1239 int nWeek
; // its week index in the month
1240 wxDateTime::WeekDay wday
; // the weekday
1241 wxDateTime::Month month
; // the month
1242 int year
; // and the year
1244 wxString
Format() const
1247 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
1249 case 1: which
= "first"; break;
1250 case 2: which
= "second"; break;
1251 case 3: which
= "third"; break;
1252 case 4: which
= "fourth"; break;
1253 case 5: which
= "fifth"; break;
1255 case -1: which
= "last"; break;
1260 which
+= " from end";
1263 s
.Printf("The %s %s of %s in %d",
1265 wxDateTime::GetWeekDayName(wday
).c_str(),
1266 wxDateTime::GetMonthName(month
).c_str(),
1273 // the array data was generated by the following python program
1275 from DateTime import *
1276 from whrandom import *
1277 from string import *
1279 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1280 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1282 week = DateTimeDelta(7)
1285 year = randint(1900, 2100)
1286 month = randint(1, 12)
1287 day = randint(1, 28)
1288 dt = DateTime(year, month, day)
1289 wday = dt.day_of_week
1291 countFromEnd = choice([-1, 1])
1294 while dt.month is month:
1295 dt = dt - countFromEnd * week
1296 weekNum = weekNum + countFromEnd
1298 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1300 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1301 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1304 static const WeekDateTestData weekDatesTestData
[] =
1306 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
1307 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
1308 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
1309 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
1310 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
1311 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
1312 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
1313 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
1314 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
1315 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
1316 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
1317 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
1318 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
1319 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
1320 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
1321 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
1322 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
1323 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
1324 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
1325 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
1328 static const char *fmt
= "%d-%b-%Y";
1331 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
1333 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
1335 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
1337 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
1339 const Date
& d
= wd
.date
;
1340 if ( d
.SameDay(dt
.GetTm()) )
1346 dt
.Set(d
.day
, d
.month
, d
.year
);
1348 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
1353 // test the computation of (ISO) week numbers
1354 static void TestTimeWNumber()
1356 puts("\n*** wxDateTime week number test ***");
1358 struct WeekNumberTestData
1360 Date date
; // the date
1361 wxDateTime::wxDateTime_t week
; // the week number in the year
1362 wxDateTime::wxDateTime_t wmon
; // the week number in the month
1363 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
1364 wxDateTime::wxDateTime_t dnum
; // day number in the year
1367 // data generated with the following python script:
1369 from DateTime import *
1370 from whrandom import *
1371 from string import *
1373 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1374 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1376 def GetMonthWeek(dt):
1377 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1378 if weekNumMonth < 0:
1379 weekNumMonth = weekNumMonth + 53
1382 def GetLastSundayBefore(dt):
1383 if dt.iso_week[2] == 7:
1386 return dt - DateTimeDelta(dt.iso_week[2])
1389 year = randint(1900, 2100)
1390 month = randint(1, 12)
1391 day = randint(1, 28)
1392 dt = DateTime(year, month, day)
1393 dayNum = dt.day_of_year
1394 weekNum = dt.iso_week[1]
1395 weekNumMonth = GetMonthWeek(dt)
1398 dtSunday = GetLastSundayBefore(dt)
1400 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1401 weekNumMonth2 = weekNumMonth2 + 1
1402 dtSunday = dtSunday - DateTimeDelta(7)
1404 data = { 'day': rjust(`day`, 2), \
1405 'month': monthNames[month - 1], \
1407 'weekNum': rjust(`weekNum`, 2), \
1408 'weekNumMonth': weekNumMonth, \
1409 'weekNumMonth2': weekNumMonth2, \
1410 'dayNum': rjust(`dayNum`, 3) }
1412 print " { { %(day)s, "\
1413 "wxDateTime::%(month)s, "\
1416 "%(weekNumMonth)s, "\
1417 "%(weekNumMonth2)s, "\
1418 "%(dayNum)s }," % data
1421 static const WeekNumberTestData weekNumberTestDates
[] =
1423 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
1424 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
1425 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
1426 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
1427 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
1428 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
1429 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
1430 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
1431 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
1432 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
1433 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
1434 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
1435 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
1436 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
1437 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
1438 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
1439 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
1440 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
1441 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
1442 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
1445 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
1447 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
1448 const Date
& d
= wn
.date
;
1450 wxDateTime dt
= d
.DT();
1452 wxDateTime::wxDateTime_t
1453 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
1454 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1455 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1456 dnum
= dt
.GetDayOfYear();
1458 printf("%s: the day number is %d",
1459 d
.FormatDate().c_str(), dnum
);
1460 if ( dnum
== wn
.dnum
)
1466 printf(" (ERROR: should be %d)", wn
.dnum
);
1469 printf(", week in month is %d", wmon
);
1470 if ( wmon
== wn
.wmon
)
1476 printf(" (ERROR: should be %d)", wn
.wmon
);
1479 printf(" or %d", wmon2
);
1480 if ( wmon2
== wn
.wmon2
)
1486 printf(" (ERROR: should be %d)", wn
.wmon2
);
1489 printf(", week in year is %d", week
);
1490 if ( week
== wn
.week
)
1496 printf(" (ERROR: should be %d)\n", wn
.week
);
1501 // test DST calculations
1502 static void TestTimeDST()
1504 puts("\n*** wxDateTime DST test ***");
1506 printf("DST is%s in effect now.\n\n",
1507 wxDateTime::Now().IsDST() ? "" : " not");
1509 // taken from http://www.energy.ca.gov/daylightsaving.html
1510 static const Date datesDST
[2][2004 - 1900 + 1] =
1513 { 1, wxDateTime::Apr
, 1990 },
1514 { 7, wxDateTime::Apr
, 1991 },
1515 { 5, wxDateTime::Apr
, 1992 },
1516 { 4, wxDateTime::Apr
, 1993 },
1517 { 3, wxDateTime::Apr
, 1994 },
1518 { 2, wxDateTime::Apr
, 1995 },
1519 { 7, wxDateTime::Apr
, 1996 },
1520 { 6, wxDateTime::Apr
, 1997 },
1521 { 5, wxDateTime::Apr
, 1998 },
1522 { 4, wxDateTime::Apr
, 1999 },
1523 { 2, wxDateTime::Apr
, 2000 },
1524 { 1, wxDateTime::Apr
, 2001 },
1525 { 7, wxDateTime::Apr
, 2002 },
1526 { 6, wxDateTime::Apr
, 2003 },
1527 { 4, wxDateTime::Apr
, 2004 },
1530 { 28, wxDateTime::Oct
, 1990 },
1531 { 27, wxDateTime::Oct
, 1991 },
1532 { 25, wxDateTime::Oct
, 1992 },
1533 { 31, wxDateTime::Oct
, 1993 },
1534 { 30, wxDateTime::Oct
, 1994 },
1535 { 29, wxDateTime::Oct
, 1995 },
1536 { 27, wxDateTime::Oct
, 1996 },
1537 { 26, wxDateTime::Oct
, 1997 },
1538 { 25, wxDateTime::Oct
, 1998 },
1539 { 31, wxDateTime::Oct
, 1999 },
1540 { 29, wxDateTime::Oct
, 2000 },
1541 { 28, wxDateTime::Oct
, 2001 },
1542 { 27, wxDateTime::Oct
, 2002 },
1543 { 26, wxDateTime::Oct
, 2003 },
1544 { 31, wxDateTime::Oct
, 2004 },
1549 for ( year
= 1990; year
< 2005; year
++ )
1551 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
1552 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
1554 printf("DST period in the US for year %d: from %s to %s",
1555 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
1557 size_t n
= year
- 1990;
1558 const Date
& dBegin
= datesDST
[0][n
];
1559 const Date
& dEnd
= datesDST
[1][n
];
1561 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
1567 printf(" (ERROR: should be %s %d to %s %d)\n",
1568 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
1569 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
1575 for ( year
= 1990; year
< 2005; year
++ )
1577 printf("DST period in Europe for year %d: from %s to %s\n",
1579 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
1580 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
1584 // test wxDateTime -> text conversion
1585 static void TestTimeFormat()
1587 puts("\n*** wxDateTime formatting test ***");
1589 // some information may be lost during conversion, so store what kind
1590 // of info should we recover after a round trip
1593 CompareNone
, // don't try comparing
1594 CompareBoth
, // dates and times should be identical
1595 CompareDate
, // dates only
1596 CompareTime
// time only
1601 CompareKind compareKind
;
1603 } formatTestFormats
[] =
1605 { CompareBoth
, "---> %c" },
1606 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
1607 { CompareBoth
, "Date is %x, time is %X" },
1608 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
1609 { CompareNone
, "The day of year: %j, the week of year: %W" },
1612 static const Date formatTestDates
[] =
1614 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
1615 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
1617 // this test can't work for other centuries because it uses two digit
1618 // years in formats, so don't even try it
1619 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
1620 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
1621 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
1625 // an extra test (as it doesn't depend on date, don't do it in the loop)
1626 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1628 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
1632 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
1633 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
1635 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
1636 printf("%s", s
.c_str());
1638 // what can we recover?
1639 int kind
= formatTestFormats
[n
].compareKind
;
1643 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
1646 // converion failed - should it have?
1647 if ( kind
== CompareNone
)
1650 puts(" (ERROR: conversion back failed)");
1654 // should have parsed the entire string
1655 puts(" (ERROR: conversion back stopped too soon)");
1659 bool equal
= FALSE
; // suppress compilaer warning
1667 equal
= dt
.IsSameDate(dt2
);
1671 equal
= dt
.IsSameTime(dt2
);
1677 printf(" (ERROR: got back '%s' instead of '%s')\n",
1678 dt2
.Format().c_str(), dt
.Format().c_str());
1689 // test text -> wxDateTime conversion
1690 static void TestTimeParse()
1692 puts("\n*** wxDateTime parse test ***");
1694 struct ParseTestData
1701 static const ParseTestData parseTestDates
[] =
1703 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
1704 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
1707 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
1709 const char *format
= parseTestDates
[n
].format
;
1711 printf("%s => ", format
);
1714 if ( dt
.ParseRfc822Date(format
) )
1716 printf("%s ", dt
.Format().c_str());
1718 if ( parseTestDates
[n
].good
)
1720 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
1727 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
1732 puts("(ERROR: bad format)");
1737 printf("bad format (%s)\n",
1738 parseTestDates
[n
].good
? "ERROR" : "ok");
1743 static void TestInteractive()
1745 puts("\n*** interactive wxDateTime tests ***");
1751 printf("Enter a date: ");
1752 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1756 if ( !dt
.ParseDate(buf
) )
1758 puts("failed to parse the date");
1763 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1764 dt
.FormatISODate().c_str(),
1766 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1767 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1768 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
1771 puts("\n*** done ***");
1774 static void TestTimeArithmetics()
1776 puts("\n*** testing arithmetic operations on wxDateTime ***");
1782 } testArithmData
[] =
1784 { wxDateSpan::Day(), "day" },
1785 { wxDateSpan::Week(), "week" },
1786 { wxDateSpan::Month(), "month" },
1787 { wxDateSpan::Year(), "year" },
1788 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1791 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
1793 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
1795 wxDateSpan span
= testArithmData
[n
].span
;
1799 const char *name
= testArithmData
[n
].name
;
1800 printf("%s + %s = %s, %s - %s = %s\n",
1801 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
1802 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
1804 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
1805 if ( dt1
- span
== dt
)
1811 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1814 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
1815 if ( dt2
+ span
== dt
)
1821 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1824 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
1825 if ( dt2
+ 2*span
== dt1
)
1831 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
1838 static void TestTimeHolidays()
1840 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1842 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
1843 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
1844 dtEnd
= dtStart
.GetLastMonthDay();
1846 wxDateTimeArray hol
;
1847 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
1849 const wxChar
*format
= "%d-%b-%Y (%a)";
1851 printf("All holidays between %s and %s:\n",
1852 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
1854 size_t count
= hol
.GetCount();
1855 for ( size_t n
= 0; n
< count
; n
++ )
1857 printf("\t%s\n", hol
[n
].Format(format
).c_str());
1865 // test compatibility with the old wxDate/wxTime classes
1866 static void TestTimeCompatibility()
1868 puts("\n*** wxDateTime compatibility test ***");
1870 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1871 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1873 double jdnNow
= wxDateTime::Now().GetJDN();
1874 long jdnMidnight
= (long)(jdnNow
- 0.5);
1875 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
1877 jdnMidnight
= wxDate().Set().GetJulianDate();
1878 printf("wxDateTime for today: %s\n",
1879 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
1881 int flags
= wxEUROPEAN
;//wxFULL;
1884 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
1885 for ( int n
= 0; n
< 7; n
++ )
1887 printf("Previous %s is %s\n",
1888 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
1889 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
1895 #endif // TEST_DATETIME
1897 // ----------------------------------------------------------------------------
1899 // ----------------------------------------------------------------------------
1903 #include <wx/thread.h>
1905 static size_t gs_counter
= (size_t)-1;
1906 static wxCriticalSection gs_critsect
;
1907 static wxCondition gs_cond
;
1909 class MyJoinableThread
: public wxThread
1912 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
1913 { m_n
= n
; Create(); }
1915 // thread execution starts here
1916 virtual ExitCode
Entry();
1922 wxThread::ExitCode
MyJoinableThread::Entry()
1924 unsigned long res
= 1;
1925 for ( size_t n
= 1; n
< m_n
; n
++ )
1929 // it's a loooong calculation :-)
1933 return (ExitCode
)res
;
1936 class MyDetachedThread
: public wxThread
1939 MyDetachedThread(size_t n
, char ch
)
1943 m_cancelled
= FALSE
;
1948 // thread execution starts here
1949 virtual ExitCode
Entry();
1952 virtual void OnExit();
1955 size_t m_n
; // number of characters to write
1956 char m_ch
; // character to write
1958 bool m_cancelled
; // FALSE if we exit normally
1961 wxThread::ExitCode
MyDetachedThread::Entry()
1964 wxCriticalSectionLocker
lock(gs_critsect
);
1965 if ( gs_counter
== (size_t)-1 )
1971 for ( size_t n
= 0; n
< m_n
; n
++ )
1973 if ( TestDestroy() )
1983 wxThread::Sleep(100);
1989 void MyDetachedThread::OnExit()
1991 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
1993 wxCriticalSectionLocker
lock(gs_critsect
);
1994 if ( !--gs_counter
&& !m_cancelled
)
1998 void TestDetachedThreads()
2000 puts("\n*** Testing detached threads ***");
2002 static const size_t nThreads
= 3;
2003 MyDetachedThread
*threads
[nThreads
];
2005 for ( n
= 0; n
< nThreads
; n
++ )
2007 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
2010 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
2011 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
2013 for ( n
= 0; n
< nThreads
; n
++ )
2018 // wait until all threads terminate
2024 void TestJoinableThreads()
2026 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2028 // calc 10! in the background
2029 MyJoinableThread
thread(10);
2032 printf("\nThread terminated with exit code %lu.\n",
2033 (unsigned long)thread
.Wait());
2036 void TestThreadSuspend()
2038 puts("\n*** Testing thread suspend/resume functions ***");
2040 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
2044 // this is for this demo only, in a real life program we'd use another
2045 // condition variable which would be signaled from wxThread::Entry() to
2046 // tell us that the thread really started running - but here just wait a
2047 // bit and hope that it will be enough (the problem is, of course, that
2048 // the thread might still not run when we call Pause() which will result
2050 wxThread::Sleep(300);
2052 for ( size_t n
= 0; n
< 3; n
++ )
2056 puts("\nThread suspended");
2059 // don't sleep but resume immediately the first time
2060 wxThread::Sleep(300);
2062 puts("Going to resume the thread");
2067 puts("Waiting until it terminates now");
2069 // wait until the thread terminates
2075 void TestThreadDelete()
2077 // As above, using Sleep() is only for testing here - we must use some
2078 // synchronisation object instead to ensure that the thread is still
2079 // running when we delete it - deleting a detached thread which already
2080 // terminated will lead to a crash!
2082 puts("\n*** Testing thread delete function ***");
2084 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
2088 puts("\nDeleted a thread which didn't start to run yet.");
2090 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
2094 wxThread::Sleep(300);
2098 puts("\nDeleted a running thread.");
2100 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
2104 wxThread::Sleep(300);
2110 puts("\nDeleted a sleeping thread.");
2112 MyJoinableThread
thread3(20);
2117 puts("\nDeleted a joinable thread.");
2119 MyJoinableThread
thread4(2);
2122 wxThread::Sleep(300);
2126 puts("\nDeleted a joinable thread which already terminated.");
2131 #endif // TEST_THREADS
2133 // ----------------------------------------------------------------------------
2135 // ----------------------------------------------------------------------------
2139 void PrintArray(const char* name
, const wxArrayString
& array
)
2141 printf("Dump of the array '%s'\n", name
);
2143 size_t nCount
= array
.GetCount();
2144 for ( size_t n
= 0; n
< nCount
; n
++ )
2146 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
2150 #endif // TEST_ARRAYS
2152 // ----------------------------------------------------------------------------
2154 // ----------------------------------------------------------------------------
2158 #include "wx/timer.h"
2159 #include "wx/tokenzr.h"
2161 static void TestStringConstruction()
2163 puts("*** Testing wxString constructores ***");
2165 #define TEST_CTOR(args, res) \
2168 printf("wxString%s = %s ", #args, s.c_str()); \
2175 printf("(ERROR: should be %s)\n", res); \
2179 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2180 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2181 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2182 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2184 static const wxChar
*s
= _T("?really!");
2185 const wxChar
*start
= wxStrchr(s
, _T('r'));
2186 const wxChar
*end
= wxStrchr(s
, _T('!'));
2187 TEST_CTOR((start
, end
), _T("really"));
2192 static void TestString()
2202 for (int i
= 0; i
< 1000000; ++i
)
2206 c
= "! How'ya doin'?";
2209 c
= "Hello world! What's up?";
2214 printf ("TestString elapsed time: %ld\n", sw
.Time());
2217 static void TestPChar()
2225 for (int i
= 0; i
< 1000000; ++i
)
2227 strcpy (a
, "Hello");
2228 strcpy (b
, " world");
2229 strcpy (c
, "! How'ya doin'?");
2232 strcpy (c
, "Hello world! What's up?");
2233 if (strcmp (c
, a
) == 0)
2237 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
2240 static void TestStringSub()
2242 wxString
s("Hello, world!");
2244 puts("*** Testing wxString substring extraction ***");
2246 printf("String = '%s'\n", s
.c_str());
2247 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
2248 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
2249 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2250 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
2251 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
2252 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
2257 static void TestStringFormat()
2259 puts("*** Testing wxString formatting ***");
2262 s
.Printf("%03d", 18);
2264 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2265 printf("Number 18: %s\n", s
.c_str());
2270 // returns "not found" for npos, value for all others
2271 static wxString
PosToString(size_t res
)
2273 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
2274 : wxString::Format(_T("%u"), res
);
2278 static void TestStringFind()
2280 puts("*** Testing wxString find() functions ***");
2282 static const wxChar
*strToFind
= _T("ell");
2283 static const struct StringFindTest
2287 result
; // of searching "ell" in str
2290 { _T("Well, hello world"), 0, 1 },
2291 { _T("Well, hello world"), 6, 7 },
2292 { _T("Well, hello world"), 9, wxString::npos
},
2295 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
2297 const StringFindTest
& ft
= findTestData
[n
];
2298 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
2300 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2301 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
2303 size_t resTrue
= ft
.result
;
2304 if ( res
== resTrue
)
2310 printf(_T("(ERROR: should be %s)\n"),
2311 PosToString(resTrue
).c_str());
2318 static void TestStringTokenizer()
2320 puts("*** Testing wxStringTokenizer ***");
2322 static const wxChar
*modeNames
[] =
2326 _T("return all empty"),
2331 static const struct StringTokenizerTest
2333 const wxChar
*str
; // string to tokenize
2334 const wxChar
*delims
; // delimiters to use
2335 size_t count
; // count of token
2336 wxStringTokenizerMode mode
; // how should we tokenize it
2337 } tokenizerTestData
[] =
2339 { _T(""), _T(" "), 0 },
2340 { _T("Hello, world"), _T(" "), 2 },
2341 { _T("Hello, world "), _T(" "), 2 },
2342 { _T("Hello, world"), _T(","), 2 },
2343 { _T("Hello, world!"), _T(",!"), 2 },
2344 { _T("Hello,, world!"), _T(",!"), 3 },
2345 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
2346 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2347 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
2348 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
2349 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
2350 { _T("01/02/99"), _T("/-"), 3 },
2351 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
2354 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
2356 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
2357 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
2359 size_t count
= tkz
.CountTokens();
2360 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2361 MakePrintable(tt
.str
).c_str(),
2363 MakePrintable(tt
.delims
).c_str(),
2364 modeNames
[tkz
.GetMode()]);
2365 if ( count
== tt
.count
)
2371 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
2376 // if we emulate strtok(), check that we do it correctly
2377 wxChar
*buf
, *s
, *last
;
2379 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
2381 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
2382 wxStrcpy(buf
, tt
.str
);
2384 s
= wxStrtok(buf
, tt
.delims
, &last
);
2391 // now show the tokens themselves
2393 while ( tkz
.HasMoreTokens() )
2395 wxString token
= tkz
.GetNextToken();
2397 printf(_T("\ttoken %u: '%s'"),
2399 MakePrintable(token
).c_str());
2409 printf(" (ERROR: should be %s)\n", s
);
2412 s
= wxStrtok(NULL
, tt
.delims
, &last
);
2416 // nothing to compare with
2421 if ( count2
!= count
)
2423 puts(_T("\tERROR: token count mismatch"));
2432 #endif // TEST_STRINGS
2434 // ----------------------------------------------------------------------------
2436 // ----------------------------------------------------------------------------
2438 int main(int argc
, char **argv
)
2440 if ( !wxInitialize() )
2442 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
2446 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2448 #endif // TEST_USLEEP
2451 static const wxCmdLineEntryDesc cmdLineDesc
[] =
2453 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
2454 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
2456 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
2457 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
2458 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
2459 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
2461 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
2462 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
2467 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
2469 switch ( parser
.Parse() )
2472 wxLogMessage("Help was given, terminating.");
2476 ShowCmdLine(parser
);
2480 wxLogMessage("Syntax error detected, aborting.");
2483 #endif // TEST_CMDLINE
2493 TestStringConstruction();
2497 TestStringTokenizer();
2499 #endif // TEST_STRINGS
2510 puts("*** Initially:");
2512 PrintArray("a1", a1
);
2514 wxArrayString
a2(a1
);
2515 PrintArray("a2", a2
);
2517 wxSortedArrayString
a3(a1
);
2518 PrintArray("a3", a3
);
2520 puts("*** After deleting a string from a1");
2523 PrintArray("a1", a1
);
2524 PrintArray("a2", a2
);
2525 PrintArray("a3", a3
);
2527 puts("*** After reassigning a1 to a2 and a3");
2529 PrintArray("a2", a2
);
2530 PrintArray("a3", a3
);
2531 #endif // TEST_ARRAYS
2539 #endif // TEST_EXECUTE
2541 #ifdef TEST_FILECONF
2543 #endif // TEST_FILECONF
2547 for ( size_t n
= 0; n
< 8000; n
++ )
2549 s
<< (char)('A' + (n
% 26));
2553 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
2555 // this one shouldn't be truncated
2558 // but this one will because log functions use fixed size buffer
2559 // (note that it doesn't need '\n' at the end neither - will be added
2561 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
2565 int nCPUs
= wxThread::GetCPUCount();
2566 printf("This system has %d CPUs\n", nCPUs
);
2568 wxThread::SetConcurrency(nCPUs
);
2570 if ( argc
> 1 && argv
[1][0] == 't' )
2571 wxLog::AddTraceMask("thread");
2574 TestDetachedThreads();
2576 TestJoinableThreads();
2578 TestThreadSuspend();
2582 #endif // TEST_THREADS
2584 #ifdef TEST_LONGLONG
2585 // seed pseudo random generator
2586 srand((unsigned)time(NULL
));
2592 TestMultiplication();
2597 TestLongLongConversion();
2598 TestBitOperations();
2600 #endif // TEST_LONGLONG
2618 #endif // TEST_SOCKETS
2622 #endif // TEST_TIMER
2624 #ifdef TEST_DATETIME
2638 TestTimeArithmetics();
2643 #endif // TEST_DATETIME