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 static const int PORT
= 3000;
731 wxSocketServer
*server
= new wxSocketServer(addr
);
734 puts("ERROR: failed to bind");
741 printf("Server: waiting for connection on port %d...\n", PORT
);
743 wxSocketBase
*socket
= server
->Accept();
746 puts("ERROR: wxSocketServer::Accept() failed.");
750 puts("Server: got a client.");
752 server
->SetTimeout(60); // 1 min
754 while ( socket
->IsConnected() )
760 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
762 // don't log error if the client just close the connection
763 if ( socket
->IsConnected() )
765 puts("ERROR: in wxSocket::Read.");
785 printf("Server: got '%s'.\n", s
.c_str());
786 if ( s
== _T("bye") )
793 socket
->Write(s
.MakeUpper().c_str(), s
.length());
794 socket
->Write("\r\n", 2);
795 printf("Server: wrote '%s'.\n", s
.c_str());
798 puts("Server: lost a client.");
803 // same as "delete server" but is consistent with GUI programs
807 static void TestSocketClient()
809 puts("*** Testing wxSocketClient ***\n");
811 static const char *hostname
= "www.wxwindows.org";
814 addr
.Hostname(hostname
);
817 printf("--- Attempting to connect to %s:80...\n", hostname
);
819 wxSocketClient client
;
820 if ( !client
.Connect(addr
) )
822 printf("ERROR: failed to connect to %s\n", hostname
);
826 printf("--- Connected to %s:%u...\n",
827 addr
.Hostname().c_str(), addr
.Service());
831 // could use simply "GET" here I suppose
833 wxString::Format("GET http://%s/\r\n", hostname
);
834 client
.Write(cmdGet
, cmdGet
.length());
835 printf("--- Sent command '%s' to the server\n",
836 MakePrintable(cmdGet
).c_str());
837 client
.Read(buf
, WXSIZEOF(buf
));
838 printf("--- Server replied:\n%s", buf
);
842 static void TestProtocolFtp()
844 puts("*** Testing wxFTP ***\n");
846 wxLog::AddTraceMask(_T("ftp"));
848 static const char *hostname
= "ftp.wxwindows.org";
850 printf("--- Attempting to connect to %s:21...\n", hostname
);
853 if ( !ftp
.Connect(hostname
) )
855 printf("ERROR: failed to connect to %s\n", hostname
);
859 printf("--- Connected to %s, current directory is '%s'\n",
860 hostname
, ftp
.Pwd().c_str());
861 if ( !ftp
.ChDir(_T("pub")) )
863 puts("ERROR: failed to cd to pub");
867 if ( !ftp
.GetList(files
) )
869 puts("ERROR: failed to get list of files");
873 printf("List of files under '%s':\n", ftp
.Pwd().c_str());
874 size_t count
= files
.GetCount();
875 for ( size_t n
= 0; n
< count
; n
++ )
877 printf("\t%s\n", files
[n
].c_str());
879 puts("End of the file list");
882 if ( !ftp
.ChDir(_T("..")) )
884 puts("ERROR: failed to cd to ..");
887 static const char *filename
= "welcome.msg";
888 wxInputStream
*in
= ftp
.GetInputStream(filename
);
891 puts("ERROR: couldn't get input stream");
895 size_t size
= in
->StreamSize();
896 printf("Reading file %s (%u bytes)...", filename
, size
);
898 char *data
= new char[size
];
899 if ( !in
->Read(data
, size
) )
901 puts("ERROR: read error");
905 printf("\nContents of %s:\n%s\n", filename
, data
);
914 #endif // TEST_SOCKETS
916 // ----------------------------------------------------------------------------
918 // ----------------------------------------------------------------------------
922 #include <wx/timer.h>
923 #include <wx/utils.h>
925 static void TestStopWatch()
927 puts("*** Testing wxStopWatch ***\n");
930 printf("Sleeping 3 seconds...");
932 printf("\telapsed time: %ldms\n", sw
.Time());
935 printf("Sleeping 2 more seconds...");
937 printf("\telapsed time: %ldms\n", sw
.Time());
940 printf("And 3 more seconds...");
942 printf("\telapsed time: %ldms\n", sw
.Time());
945 puts("\nChecking for 'backwards clock' bug...");
946 for ( size_t n
= 0; n
< 70; n
++ )
950 for ( size_t m
= 0; m
< 100000; m
++ )
952 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
954 puts("\ntime is negative - ERROR!");
966 // ----------------------------------------------------------------------------
968 // ----------------------------------------------------------------------------
974 #include <wx/datetime.h>
979 wxDateTime::wxDateTime_t day
;
980 wxDateTime::Month month
;
982 wxDateTime::wxDateTime_t hour
, min
, sec
;
984 wxDateTime::WeekDay wday
;
985 time_t gmticks
, ticks
;
987 void Init(const wxDateTime::Tm
& tm
)
996 gmticks
= ticks
= -1;
999 wxDateTime
DT() const
1000 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
1002 bool SameDay(const wxDateTime::Tm
& tm
) const
1004 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
1007 wxString
Format() const
1010 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
1012 wxDateTime::GetMonthName(month
).c_str(),
1014 abs(wxDateTime::ConvertYearToBC(year
)),
1015 year
> 0 ? "AD" : "BC");
1019 wxString
FormatDate() const
1022 s
.Printf("%02d-%s-%4d%s",
1024 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1025 abs(wxDateTime::ConvertYearToBC(year
)),
1026 year
> 0 ? "AD" : "BC");
1031 static const Date testDates
[] =
1033 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
1034 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
1035 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
1036 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
1037 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
1038 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
1039 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
1040 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
1041 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
1042 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
1043 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
1044 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
1045 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
1046 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
1047 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
1050 // this test miscellaneous static wxDateTime functions
1051 static void TestTimeStatic()
1053 puts("\n*** wxDateTime static methods test ***");
1055 // some info about the current date
1056 int year
= wxDateTime::GetCurrentYear();
1057 printf("Current year %d is %sa leap one and has %d days.\n",
1059 wxDateTime::IsLeapYear(year
) ? "" : "not ",
1060 wxDateTime::GetNumberOfDays(year
));
1062 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
1063 printf("Current month is '%s' ('%s') and it has %d days\n",
1064 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
1065 wxDateTime::GetMonthName(month
).c_str(),
1066 wxDateTime::GetNumberOfDays(month
));
1069 static const size_t nYears
= 5;
1070 static const size_t years
[2][nYears
] =
1072 // first line: the years to test
1073 { 1990, 1976, 2000, 2030, 1984, },
1075 // second line: TRUE if leap, FALSE otherwise
1076 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
1079 for ( size_t n
= 0; n
< nYears
; n
++ )
1081 int year
= years
[0][n
];
1082 bool should
= years
[1][n
] != 0,
1083 is
= wxDateTime::IsLeapYear(year
);
1085 printf("Year %d is %sa leap year (%s)\n",
1088 should
== is
? "ok" : "ERROR");
1090 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
1094 // test constructing wxDateTime objects
1095 static void TestTimeSet()
1097 puts("\n*** wxDateTime construction test ***");
1099 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1101 const Date
& d1
= testDates
[n
];
1102 wxDateTime dt
= d1
.DT();
1105 d2
.Init(dt
.GetTm());
1107 wxString s1
= d1
.Format(),
1110 printf("Date: %s == %s (%s)\n",
1111 s1
.c_str(), s2
.c_str(),
1112 s1
== s2
? "ok" : "ERROR");
1116 // test time zones stuff
1117 static void TestTimeZones()
1119 puts("\n*** wxDateTime timezone test ***");
1121 wxDateTime now
= wxDateTime::Now();
1123 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
1124 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
1125 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
1126 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
1127 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
1128 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
1130 wxDateTime::Tm tm
= now
.GetTm();
1131 if ( wxDateTime(tm
) != now
)
1133 printf("ERROR: got %s instead of %s\n",
1134 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
1138 // test some minimal support for the dates outside the standard range
1139 static void TestTimeRange()
1141 puts("\n*** wxDateTime out-of-standard-range dates test ***");
1143 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
1145 printf("Unix epoch:\t%s\n",
1146 wxDateTime(2440587.5).Format(fmt
).c_str());
1147 printf("Feb 29, 0: \t%s\n",
1148 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
1149 printf("JDN 0: \t%s\n",
1150 wxDateTime(0.0).Format(fmt
).c_str());
1151 printf("Jan 1, 1AD:\t%s\n",
1152 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
1153 printf("May 29, 2099:\t%s\n",
1154 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
1157 static void TestTimeTicks()
1159 puts("\n*** wxDateTime ticks test ***");
1161 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1163 const Date
& d
= testDates
[n
];
1164 if ( d
.ticks
== -1 )
1167 wxDateTime dt
= d
.DT();
1168 long ticks
= (dt
.GetValue() / 1000).ToLong();
1169 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1170 if ( ticks
== d
.ticks
)
1176 printf(" (ERROR: should be %ld, delta = %ld)\n",
1177 d
.ticks
, ticks
- d
.ticks
);
1180 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
1181 ticks
= (dt
.GetValue() / 1000).ToLong();
1182 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
1183 if ( ticks
== d
.gmticks
)
1189 printf(" (ERROR: should be %ld, delta = %ld)\n",
1190 d
.gmticks
, ticks
- d
.gmticks
);
1197 // test conversions to JDN &c
1198 static void TestTimeJDN()
1200 puts("\n*** wxDateTime to JDN test ***");
1202 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1204 const Date
& d
= testDates
[n
];
1205 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1206 double jdn
= dt
.GetJulianDayNumber();
1208 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
1215 printf(" (ERROR: should be %f, delta = %f)\n",
1216 d
.jdn
, jdn
- d
.jdn
);
1221 // test week days computation
1222 static void TestTimeWDays()
1224 puts("\n*** wxDateTime weekday test ***");
1226 // test GetWeekDay()
1228 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
1230 const Date
& d
= testDates
[n
];
1231 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
1233 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
1236 wxDateTime::GetWeekDayName(wday
).c_str());
1237 if ( wday
== d
.wday
)
1243 printf(" (ERROR: should be %s)\n",
1244 wxDateTime::GetWeekDayName(d
.wday
).c_str());
1250 // test SetToWeekDay()
1251 struct WeekDateTestData
1253 Date date
; // the real date (precomputed)
1254 int nWeek
; // its week index in the month
1255 wxDateTime::WeekDay wday
; // the weekday
1256 wxDateTime::Month month
; // the month
1257 int year
; // and the year
1259 wxString
Format() const
1262 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
1264 case 1: which
= "first"; break;
1265 case 2: which
= "second"; break;
1266 case 3: which
= "third"; break;
1267 case 4: which
= "fourth"; break;
1268 case 5: which
= "fifth"; break;
1270 case -1: which
= "last"; break;
1275 which
+= " from end";
1278 s
.Printf("The %s %s of %s in %d",
1280 wxDateTime::GetWeekDayName(wday
).c_str(),
1281 wxDateTime::GetMonthName(month
).c_str(),
1288 // the array data was generated by the following python program
1290 from DateTime import *
1291 from whrandom import *
1292 from string import *
1294 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1295 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1297 week = DateTimeDelta(7)
1300 year = randint(1900, 2100)
1301 month = randint(1, 12)
1302 day = randint(1, 28)
1303 dt = DateTime(year, month, day)
1304 wday = dt.day_of_week
1306 countFromEnd = choice([-1, 1])
1309 while dt.month is month:
1310 dt = dt - countFromEnd * week
1311 weekNum = weekNum + countFromEnd
1313 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
1315 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
1316 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
1319 static const WeekDateTestData weekDatesTestData
[] =
1321 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
1322 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
1323 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
1324 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
1325 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
1326 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
1327 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
1328 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
1329 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
1330 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
1331 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
1332 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
1333 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
1334 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
1335 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
1336 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
1337 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
1338 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
1339 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
1340 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
1343 static const char *fmt
= "%d-%b-%Y";
1346 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
1348 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
1350 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
1352 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
1354 const Date
& d
= wd
.date
;
1355 if ( d
.SameDay(dt
.GetTm()) )
1361 dt
.Set(d
.day
, d
.month
, d
.year
);
1363 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
1368 // test the computation of (ISO) week numbers
1369 static void TestTimeWNumber()
1371 puts("\n*** wxDateTime week number test ***");
1373 struct WeekNumberTestData
1375 Date date
; // the date
1376 wxDateTime::wxDateTime_t week
; // the week number in the year
1377 wxDateTime::wxDateTime_t wmon
; // the week number in the month
1378 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
1379 wxDateTime::wxDateTime_t dnum
; // day number in the year
1382 // data generated with the following python script:
1384 from DateTime import *
1385 from whrandom import *
1386 from string import *
1388 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
1389 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
1391 def GetMonthWeek(dt):
1392 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
1393 if weekNumMonth < 0:
1394 weekNumMonth = weekNumMonth + 53
1397 def GetLastSundayBefore(dt):
1398 if dt.iso_week[2] == 7:
1401 return dt - DateTimeDelta(dt.iso_week[2])
1404 year = randint(1900, 2100)
1405 month = randint(1, 12)
1406 day = randint(1, 28)
1407 dt = DateTime(year, month, day)
1408 dayNum = dt.day_of_year
1409 weekNum = dt.iso_week[1]
1410 weekNumMonth = GetMonthWeek(dt)
1413 dtSunday = GetLastSundayBefore(dt)
1415 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
1416 weekNumMonth2 = weekNumMonth2 + 1
1417 dtSunday = dtSunday - DateTimeDelta(7)
1419 data = { 'day': rjust(`day`, 2), \
1420 'month': monthNames[month - 1], \
1422 'weekNum': rjust(`weekNum`, 2), \
1423 'weekNumMonth': weekNumMonth, \
1424 'weekNumMonth2': weekNumMonth2, \
1425 'dayNum': rjust(`dayNum`, 3) }
1427 print " { { %(day)s, "\
1428 "wxDateTime::%(month)s, "\
1431 "%(weekNumMonth)s, "\
1432 "%(weekNumMonth2)s, "\
1433 "%(dayNum)s }," % data
1436 static const WeekNumberTestData weekNumberTestDates
[] =
1438 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
1439 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
1440 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
1441 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
1442 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
1443 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
1444 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
1445 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
1446 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
1447 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
1448 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
1449 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
1450 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
1451 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
1452 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
1453 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
1454 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
1455 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
1456 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
1457 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
1460 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
1462 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
1463 const Date
& d
= wn
.date
;
1465 wxDateTime dt
= d
.DT();
1467 wxDateTime::wxDateTime_t
1468 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
1469 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1470 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1471 dnum
= dt
.GetDayOfYear();
1473 printf("%s: the day number is %d",
1474 d
.FormatDate().c_str(), dnum
);
1475 if ( dnum
== wn
.dnum
)
1481 printf(" (ERROR: should be %d)", wn
.dnum
);
1484 printf(", week in month is %d", wmon
);
1485 if ( wmon
== wn
.wmon
)
1491 printf(" (ERROR: should be %d)", wn
.wmon
);
1494 printf(" or %d", wmon2
);
1495 if ( wmon2
== wn
.wmon2
)
1501 printf(" (ERROR: should be %d)", wn
.wmon2
);
1504 printf(", week in year is %d", week
);
1505 if ( week
== wn
.week
)
1511 printf(" (ERROR: should be %d)\n", wn
.week
);
1516 // test DST calculations
1517 static void TestTimeDST()
1519 puts("\n*** wxDateTime DST test ***");
1521 printf("DST is%s in effect now.\n\n",
1522 wxDateTime::Now().IsDST() ? "" : " not");
1524 // taken from http://www.energy.ca.gov/daylightsaving.html
1525 static const Date datesDST
[2][2004 - 1900 + 1] =
1528 { 1, wxDateTime::Apr
, 1990 },
1529 { 7, wxDateTime::Apr
, 1991 },
1530 { 5, wxDateTime::Apr
, 1992 },
1531 { 4, wxDateTime::Apr
, 1993 },
1532 { 3, wxDateTime::Apr
, 1994 },
1533 { 2, wxDateTime::Apr
, 1995 },
1534 { 7, wxDateTime::Apr
, 1996 },
1535 { 6, wxDateTime::Apr
, 1997 },
1536 { 5, wxDateTime::Apr
, 1998 },
1537 { 4, wxDateTime::Apr
, 1999 },
1538 { 2, wxDateTime::Apr
, 2000 },
1539 { 1, wxDateTime::Apr
, 2001 },
1540 { 7, wxDateTime::Apr
, 2002 },
1541 { 6, wxDateTime::Apr
, 2003 },
1542 { 4, wxDateTime::Apr
, 2004 },
1545 { 28, wxDateTime::Oct
, 1990 },
1546 { 27, wxDateTime::Oct
, 1991 },
1547 { 25, wxDateTime::Oct
, 1992 },
1548 { 31, wxDateTime::Oct
, 1993 },
1549 { 30, wxDateTime::Oct
, 1994 },
1550 { 29, wxDateTime::Oct
, 1995 },
1551 { 27, wxDateTime::Oct
, 1996 },
1552 { 26, wxDateTime::Oct
, 1997 },
1553 { 25, wxDateTime::Oct
, 1998 },
1554 { 31, wxDateTime::Oct
, 1999 },
1555 { 29, wxDateTime::Oct
, 2000 },
1556 { 28, wxDateTime::Oct
, 2001 },
1557 { 27, wxDateTime::Oct
, 2002 },
1558 { 26, wxDateTime::Oct
, 2003 },
1559 { 31, wxDateTime::Oct
, 2004 },
1564 for ( year
= 1990; year
< 2005; year
++ )
1566 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
1567 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
1569 printf("DST period in the US for year %d: from %s to %s",
1570 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
1572 size_t n
= year
- 1990;
1573 const Date
& dBegin
= datesDST
[0][n
];
1574 const Date
& dEnd
= datesDST
[1][n
];
1576 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
1582 printf(" (ERROR: should be %s %d to %s %d)\n",
1583 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
1584 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
1590 for ( year
= 1990; year
< 2005; year
++ )
1592 printf("DST period in Europe for year %d: from %s to %s\n",
1594 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
1595 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
1599 // test wxDateTime -> text conversion
1600 static void TestTimeFormat()
1602 puts("\n*** wxDateTime formatting test ***");
1604 // some information may be lost during conversion, so store what kind
1605 // of info should we recover after a round trip
1608 CompareNone
, // don't try comparing
1609 CompareBoth
, // dates and times should be identical
1610 CompareDate
, // dates only
1611 CompareTime
// time only
1616 CompareKind compareKind
;
1618 } formatTestFormats
[] =
1620 { CompareBoth
, "---> %c" },
1621 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
1622 { CompareBoth
, "Date is %x, time is %X" },
1623 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
1624 { CompareNone
, "The day of year: %j, the week of year: %W" },
1627 static const Date formatTestDates
[] =
1629 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
1630 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
1632 // this test can't work for other centuries because it uses two digit
1633 // years in formats, so don't even try it
1634 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
1635 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
1636 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
1640 // an extra test (as it doesn't depend on date, don't do it in the loop)
1641 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
1643 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
1647 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
1648 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
1650 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
1651 printf("%s", s
.c_str());
1653 // what can we recover?
1654 int kind
= formatTestFormats
[n
].compareKind
;
1658 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
1661 // converion failed - should it have?
1662 if ( kind
== CompareNone
)
1665 puts(" (ERROR: conversion back failed)");
1669 // should have parsed the entire string
1670 puts(" (ERROR: conversion back stopped too soon)");
1674 bool equal
= FALSE
; // suppress compilaer warning
1682 equal
= dt
.IsSameDate(dt2
);
1686 equal
= dt
.IsSameTime(dt2
);
1692 printf(" (ERROR: got back '%s' instead of '%s')\n",
1693 dt2
.Format().c_str(), dt
.Format().c_str());
1704 // test text -> wxDateTime conversion
1705 static void TestTimeParse()
1707 puts("\n*** wxDateTime parse test ***");
1709 struct ParseTestData
1716 static const ParseTestData parseTestDates
[] =
1718 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
1719 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
1722 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
1724 const char *format
= parseTestDates
[n
].format
;
1726 printf("%s => ", format
);
1729 if ( dt
.ParseRfc822Date(format
) )
1731 printf("%s ", dt
.Format().c_str());
1733 if ( parseTestDates
[n
].good
)
1735 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
1742 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
1747 puts("(ERROR: bad format)");
1752 printf("bad format (%s)\n",
1753 parseTestDates
[n
].good
? "ERROR" : "ok");
1758 static void TestInteractive()
1760 puts("\n*** interactive wxDateTime tests ***");
1766 printf("Enter a date: ");
1767 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
1771 if ( !dt
.ParseDate(buf
) )
1773 puts("failed to parse the date");
1778 printf("%s: day %u, week of month %u/%u, week of year %u\n",
1779 dt
.FormatISODate().c_str(),
1781 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
1782 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
1783 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
1786 puts("\n*** done ***");
1789 static void TestTimeArithmetics()
1791 puts("\n*** testing arithmetic operations on wxDateTime ***");
1797 } testArithmData
[] =
1799 { wxDateSpan::Day(), "day" },
1800 { wxDateSpan::Week(), "week" },
1801 { wxDateSpan::Month(), "month" },
1802 { wxDateSpan::Year(), "year" },
1803 { wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days" },
1806 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
1808 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
1810 wxDateSpan span
= testArithmData
[n
].span
;
1814 const char *name
= testArithmData
[n
].name
;
1815 printf("%s + %s = %s, %s - %s = %s\n",
1816 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
1817 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
1819 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
1820 if ( dt1
- span
== dt
)
1826 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1829 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
1830 if ( dt2
+ span
== dt
)
1836 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
1839 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
1840 if ( dt2
+ 2*span
== dt1
)
1846 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
1853 static void TestTimeHolidays()
1855 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
1857 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
1858 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
1859 dtEnd
= dtStart
.GetLastMonthDay();
1861 wxDateTimeArray hol
;
1862 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
1864 const wxChar
*format
= "%d-%b-%Y (%a)";
1866 printf("All holidays between %s and %s:\n",
1867 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
1869 size_t count
= hol
.GetCount();
1870 for ( size_t n
= 0; n
< count
; n
++ )
1872 printf("\t%s\n", hol
[n
].Format(format
).c_str());
1880 // test compatibility with the old wxDate/wxTime classes
1881 static void TestTimeCompatibility()
1883 puts("\n*** wxDateTime compatibility test ***");
1885 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
1886 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
1888 double jdnNow
= wxDateTime::Now().GetJDN();
1889 long jdnMidnight
= (long)(jdnNow
- 0.5);
1890 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
1892 jdnMidnight
= wxDate().Set().GetJulianDate();
1893 printf("wxDateTime for today: %s\n",
1894 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
1896 int flags
= wxEUROPEAN
;//wxFULL;
1899 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
1900 for ( int n
= 0; n
< 7; n
++ )
1902 printf("Previous %s is %s\n",
1903 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
1904 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
1910 #endif // TEST_DATETIME
1912 // ----------------------------------------------------------------------------
1914 // ----------------------------------------------------------------------------
1918 #include <wx/thread.h>
1920 static size_t gs_counter
= (size_t)-1;
1921 static wxCriticalSection gs_critsect
;
1922 static wxCondition gs_cond
;
1924 class MyJoinableThread
: public wxThread
1927 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
1928 { m_n
= n
; Create(); }
1930 // thread execution starts here
1931 virtual ExitCode
Entry();
1937 wxThread::ExitCode
MyJoinableThread::Entry()
1939 unsigned long res
= 1;
1940 for ( size_t n
= 1; n
< m_n
; n
++ )
1944 // it's a loooong calculation :-)
1948 return (ExitCode
)res
;
1951 class MyDetachedThread
: public wxThread
1954 MyDetachedThread(size_t n
, char ch
)
1958 m_cancelled
= FALSE
;
1963 // thread execution starts here
1964 virtual ExitCode
Entry();
1967 virtual void OnExit();
1970 size_t m_n
; // number of characters to write
1971 char m_ch
; // character to write
1973 bool m_cancelled
; // FALSE if we exit normally
1976 wxThread::ExitCode
MyDetachedThread::Entry()
1979 wxCriticalSectionLocker
lock(gs_critsect
);
1980 if ( gs_counter
== (size_t)-1 )
1986 for ( size_t n
= 0; n
< m_n
; n
++ )
1988 if ( TestDestroy() )
1998 wxThread::Sleep(100);
2004 void MyDetachedThread::OnExit()
2006 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
2008 wxCriticalSectionLocker
lock(gs_critsect
);
2009 if ( !--gs_counter
&& !m_cancelled
)
2013 void TestDetachedThreads()
2015 puts("\n*** Testing detached threads ***");
2017 static const size_t nThreads
= 3;
2018 MyDetachedThread
*threads
[nThreads
];
2020 for ( n
= 0; n
< nThreads
; n
++ )
2022 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
2025 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
2026 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
2028 for ( n
= 0; n
< nThreads
; n
++ )
2033 // wait until all threads terminate
2039 void TestJoinableThreads()
2041 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
2043 // calc 10! in the background
2044 MyJoinableThread
thread(10);
2047 printf("\nThread terminated with exit code %lu.\n",
2048 (unsigned long)thread
.Wait());
2051 void TestThreadSuspend()
2053 puts("\n*** Testing thread suspend/resume functions ***");
2055 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
2059 // this is for this demo only, in a real life program we'd use another
2060 // condition variable which would be signaled from wxThread::Entry() to
2061 // tell us that the thread really started running - but here just wait a
2062 // bit and hope that it will be enough (the problem is, of course, that
2063 // the thread might still not run when we call Pause() which will result
2065 wxThread::Sleep(300);
2067 for ( size_t n
= 0; n
< 3; n
++ )
2071 puts("\nThread suspended");
2074 // don't sleep but resume immediately the first time
2075 wxThread::Sleep(300);
2077 puts("Going to resume the thread");
2082 puts("Waiting until it terminates now");
2084 // wait until the thread terminates
2090 void TestThreadDelete()
2092 // As above, using Sleep() is only for testing here - we must use some
2093 // synchronisation object instead to ensure that the thread is still
2094 // running when we delete it - deleting a detached thread which already
2095 // terminated will lead to a crash!
2097 puts("\n*** Testing thread delete function ***");
2099 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
2103 puts("\nDeleted a thread which didn't start to run yet.");
2105 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
2109 wxThread::Sleep(300);
2113 puts("\nDeleted a running thread.");
2115 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
2119 wxThread::Sleep(300);
2125 puts("\nDeleted a sleeping thread.");
2127 MyJoinableThread
thread3(20);
2132 puts("\nDeleted a joinable thread.");
2134 MyJoinableThread
thread4(2);
2137 wxThread::Sleep(300);
2141 puts("\nDeleted a joinable thread which already terminated.");
2146 #endif // TEST_THREADS
2148 // ----------------------------------------------------------------------------
2150 // ----------------------------------------------------------------------------
2154 void PrintArray(const char* name
, const wxArrayString
& array
)
2156 printf("Dump of the array '%s'\n", name
);
2158 size_t nCount
= array
.GetCount();
2159 for ( size_t n
= 0; n
< nCount
; n
++ )
2161 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
2165 #endif // TEST_ARRAYS
2167 // ----------------------------------------------------------------------------
2169 // ----------------------------------------------------------------------------
2173 #include "wx/timer.h"
2174 #include "wx/tokenzr.h"
2176 static void TestStringConstruction()
2178 puts("*** Testing wxString constructores ***");
2180 #define TEST_CTOR(args, res) \
2183 printf("wxString%s = %s ", #args, s.c_str()); \
2190 printf("(ERROR: should be %s)\n", res); \
2194 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
2195 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
2196 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
2197 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
2199 static const wxChar
*s
= _T("?really!");
2200 const wxChar
*start
= wxStrchr(s
, _T('r'));
2201 const wxChar
*end
= wxStrchr(s
, _T('!'));
2202 TEST_CTOR((start
, end
), _T("really"));
2207 static void TestString()
2217 for (int i
= 0; i
< 1000000; ++i
)
2221 c
= "! How'ya doin'?";
2224 c
= "Hello world! What's up?";
2229 printf ("TestString elapsed time: %ld\n", sw
.Time());
2232 static void TestPChar()
2240 for (int i
= 0; i
< 1000000; ++i
)
2242 strcpy (a
, "Hello");
2243 strcpy (b
, " world");
2244 strcpy (c
, "! How'ya doin'?");
2247 strcpy (c
, "Hello world! What's up?");
2248 if (strcmp (c
, a
) == 0)
2252 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
2255 static void TestStringSub()
2257 wxString
s("Hello, world!");
2259 puts("*** Testing wxString substring extraction ***");
2261 printf("String = '%s'\n", s
.c_str());
2262 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
2263 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
2264 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
2265 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
2266 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
2267 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
2272 static void TestStringFormat()
2274 puts("*** Testing wxString formatting ***");
2277 s
.Printf("%03d", 18);
2279 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
2280 printf("Number 18: %s\n", s
.c_str());
2285 // returns "not found" for npos, value for all others
2286 static wxString
PosToString(size_t res
)
2288 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
2289 : wxString::Format(_T("%u"), res
);
2293 static void TestStringFind()
2295 puts("*** Testing wxString find() functions ***");
2297 static const wxChar
*strToFind
= _T("ell");
2298 static const struct StringFindTest
2302 result
; // of searching "ell" in str
2305 { _T("Well, hello world"), 0, 1 },
2306 { _T("Well, hello world"), 6, 7 },
2307 { _T("Well, hello world"), 9, wxString::npos
},
2310 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
2312 const StringFindTest
& ft
= findTestData
[n
];
2313 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
2315 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
2316 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
2318 size_t resTrue
= ft
.result
;
2319 if ( res
== resTrue
)
2325 printf(_T("(ERROR: should be %s)\n"),
2326 PosToString(resTrue
).c_str());
2333 static void TestStringTokenizer()
2335 puts("*** Testing wxStringTokenizer ***");
2337 static const wxChar
*modeNames
[] =
2341 _T("return all empty"),
2346 static const struct StringTokenizerTest
2348 const wxChar
*str
; // string to tokenize
2349 const wxChar
*delims
; // delimiters to use
2350 size_t count
; // count of token
2351 wxStringTokenizerMode mode
; // how should we tokenize it
2352 } tokenizerTestData
[] =
2354 { _T(""), _T(" "), 0 },
2355 { _T("Hello, world"), _T(" "), 2 },
2356 { _T("Hello, world "), _T(" "), 2 },
2357 { _T("Hello, world"), _T(","), 2 },
2358 { _T("Hello, world!"), _T(",!"), 2 },
2359 { _T("Hello,, world!"), _T(",!"), 3 },
2360 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
2361 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
2362 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
2363 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
2364 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
2365 { _T("01/02/99"), _T("/-"), 3 },
2366 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
2369 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
2371 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
2372 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
2374 size_t count
= tkz
.CountTokens();
2375 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
2376 MakePrintable(tt
.str
).c_str(),
2378 MakePrintable(tt
.delims
).c_str(),
2379 modeNames
[tkz
.GetMode()]);
2380 if ( count
== tt
.count
)
2386 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
2391 // if we emulate strtok(), check that we do it correctly
2392 wxChar
*buf
, *s
, *last
;
2394 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
2396 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
2397 wxStrcpy(buf
, tt
.str
);
2399 s
= wxStrtok(buf
, tt
.delims
, &last
);
2406 // now show the tokens themselves
2408 while ( tkz
.HasMoreTokens() )
2410 wxString token
= tkz
.GetNextToken();
2412 printf(_T("\ttoken %u: '%s'"),
2414 MakePrintable(token
).c_str());
2424 printf(" (ERROR: should be %s)\n", s
);
2427 s
= wxStrtok(NULL
, tt
.delims
, &last
);
2431 // nothing to compare with
2436 if ( count2
!= count
)
2438 puts(_T("\tERROR: token count mismatch"));
2447 #endif // TEST_STRINGS
2449 // ----------------------------------------------------------------------------
2451 // ----------------------------------------------------------------------------
2453 int main(int argc
, char **argv
)
2455 if ( !wxInitialize() )
2457 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
2461 puts("Sleeping for 3 seconds... z-z-z-z-z...");
2463 #endif // TEST_USLEEP
2466 static const wxCmdLineEntryDesc cmdLineDesc
[] =
2468 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
2469 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
2471 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
2472 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
2473 { wxCMD_LINE_OPTION
, "s", "size", "output block size", wxCMD_LINE_VAL_NUMBER
},
2474 { wxCMD_LINE_OPTION
, "d", "date", "output file date", wxCMD_LINE_VAL_DATE
},
2476 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
2477 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
2482 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
2484 switch ( parser
.Parse() )
2487 wxLogMessage("Help was given, terminating.");
2491 ShowCmdLine(parser
);
2495 wxLogMessage("Syntax error detected, aborting.");
2498 #endif // TEST_CMDLINE
2508 TestStringConstruction();
2512 TestStringTokenizer();
2514 #endif // TEST_STRINGS
2525 puts("*** Initially:");
2527 PrintArray("a1", a1
);
2529 wxArrayString
a2(a1
);
2530 PrintArray("a2", a2
);
2532 wxSortedArrayString
a3(a1
);
2533 PrintArray("a3", a3
);
2535 puts("*** After deleting a string from a1");
2538 PrintArray("a1", a1
);
2539 PrintArray("a2", a2
);
2540 PrintArray("a3", a3
);
2542 puts("*** After reassigning a1 to a2 and a3");
2544 PrintArray("a2", a2
);
2545 PrintArray("a3", a3
);
2546 #endif // TEST_ARRAYS
2554 #endif // TEST_EXECUTE
2556 #ifdef TEST_FILECONF
2558 #endif // TEST_FILECONF
2562 for ( size_t n
= 0; n
< 8000; n
++ )
2564 s
<< (char)('A' + (n
% 26));
2568 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
2570 // this one shouldn't be truncated
2573 // but this one will because log functions use fixed size buffer
2574 // (note that it doesn't need '\n' at the end neither - will be added
2576 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
2580 int nCPUs
= wxThread::GetCPUCount();
2581 printf("This system has %d CPUs\n", nCPUs
);
2583 wxThread::SetConcurrency(nCPUs
);
2585 if ( argc
> 1 && argv
[1][0] == 't' )
2586 wxLog::AddTraceMask("thread");
2589 TestDetachedThreads();
2591 TestJoinableThreads();
2593 TestThreadSuspend();
2597 #endif // TEST_THREADS
2599 #ifdef TEST_LONGLONG
2600 // seed pseudo random generator
2601 srand((unsigned)time(NULL
));
2607 TestMultiplication();
2612 TestLongLongConversion();
2613 TestBitOperations();
2615 #endif // TEST_LONGLONG
2633 #endif // TEST_SOCKETS
2637 #endif // TEST_TIMER
2639 #ifdef TEST_DATETIME
2653 TestTimeArithmetics();
2658 #endif // TEST_DATETIME