1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWidgets
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
24 #include "wx/string.h"
29 // without this pragma, the stupid compiler precompiles #defines below so that
30 // changing them doesn't "take place" later!
35 // ----------------------------------------------------------------------------
36 // conditional compilation
37 // ----------------------------------------------------------------------------
40 A note about all these conditional compilation macros: this file is used
41 both as a test suite for various non-GUI wxWidgets classes and as a
42 scratchpad for quick tests. So there are two compilation modes: if you
43 define TEST_ALL all tests are run, otherwise you may enable the individual
44 tests individually in the "#else" branch below.
47 // what to test (in alphabetic order)? Define TEST_ALL to 0 to do a single
48 // test, define it to 1 to do all tests.
56 #define TEST_DLLLOADER
63 // #define TEST_FTP --FIXME! (RN)
64 #define TEST_INFO_FUNCTIONS
74 #define TEST_SCOPEGUARD
76 // #define TEST_SOCKETS --FIXME! (RN)
77 #define TEST_STACKWALKER
80 #define TEST_TEXTSTREAM
83 // #define TEST_VCARD -- don't enable this (VZ)
84 // #define TEST_VOLUME --FIXME! (RN)
88 #define TEST_STACKWALKER
91 // some tests are interactive, define this to run them
92 #ifdef TEST_INTERACTIVE
93 #undef TEST_INTERACTIVE
95 #define TEST_INTERACTIVE 1
97 #define TEST_INTERACTIVE 0
100 // ============================================================================
102 // ============================================================================
104 // ----------------------------------------------------------------------------
106 // ----------------------------------------------------------------------------
108 #if defined(TEST_SOCKETS)
110 // replace TABs with \t and CRs with \n
111 static wxString
MakePrintable(const wxChar
*s
)
114 (void)str
.Replace(_T("\t"), _T("\\t"));
115 (void)str
.Replace(_T("\n"), _T("\\n"));
116 (void)str
.Replace(_T("\r"), _T("\\r"));
121 #endif // MakePrintable() is used
123 // ----------------------------------------------------------------------------
125 // ----------------------------------------------------------------------------
129 #include "wx/cmdline.h"
130 #include "wx/datetime.h"
132 #if wxUSE_CMDLINE_PARSER
134 static void ShowCmdLine(const wxCmdLineParser
& parser
)
136 wxString s
= _T("Input files: ");
138 size_t count
= parser
.GetParamCount();
139 for ( size_t param
= 0; param
< count
; param
++ )
141 s
<< parser
.GetParam(param
) << ' ';
145 << _T("Verbose:\t") << (parser
.Found(_T("v")) ? _T("yes") : _T("no")) << '\n'
146 << _T("Quiet:\t") << (parser
.Found(_T("q")) ? _T("yes") : _T("no")) << '\n';
151 if ( parser
.Found(_T("o"), &strVal
) )
152 s
<< _T("Output file:\t") << strVal
<< '\n';
153 if ( parser
.Found(_T("i"), &strVal
) )
154 s
<< _T("Input dir:\t") << strVal
<< '\n';
155 if ( parser
.Found(_T("s"), &lVal
) )
156 s
<< _T("Size:\t") << lVal
<< '\n';
157 if ( parser
.Found(_T("d"), &dt
) )
158 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
159 if ( parser
.Found(_T("project_name"), &strVal
) )
160 s
<< _T("Project:\t") << strVal
<< '\n';
165 #endif // wxUSE_CMDLINE_PARSER
167 static void TestCmdLineConvert()
169 static const wxChar
*cmdlines
[] =
172 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
173 _T("literal \\\" and \"\""),
176 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
178 const wxChar
*cmdline
= cmdlines
[n
];
179 wxPrintf(_T("Parsing: %s\n"), cmdline
);
180 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
182 size_t count
= args
.GetCount();
183 wxPrintf(_T("\targc = %u\n"), count
);
184 for ( size_t arg
= 0; arg
< count
; arg
++ )
186 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
191 #endif // TEST_CMDLINE
193 // ----------------------------------------------------------------------------
195 // ----------------------------------------------------------------------------
202 static const wxChar
*ROOTDIR
= _T("/");
203 static const wxChar
*TESTDIR
= _T("/usr/local/share");
204 #elif defined(__WXMSW__)
205 static const wxChar
*ROOTDIR
= _T("c:\\");
206 static const wxChar
*TESTDIR
= _T("d:\\");
208 #error "don't know where the root directory is"
211 static void TestDirEnumHelper(wxDir
& dir
,
212 int flags
= wxDIR_DEFAULT
,
213 const wxString
& filespec
= wxEmptyString
)
217 if ( !dir
.IsOpened() )
220 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
223 wxPrintf(_T("\t%s\n"), filename
.c_str());
225 cont
= dir
.GetNext(&filename
);
228 wxPuts(wxEmptyString
);
231 static void TestDirEnum()
233 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
235 wxString cwd
= wxGetCwd();
236 if ( !wxDir::Exists(cwd
) )
238 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
243 if ( !dir
.IsOpened() )
245 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
249 wxPuts(_T("Enumerating everything in current directory:"));
250 TestDirEnumHelper(dir
);
252 wxPuts(_T("Enumerating really everything in current directory:"));
253 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
255 wxPuts(_T("Enumerating object files in current directory:"));
256 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, _T("*.o*"));
258 wxPuts(_T("Enumerating directories in current directory:"));
259 TestDirEnumHelper(dir
, wxDIR_DIRS
);
261 wxPuts(_T("Enumerating files in current directory:"));
262 TestDirEnumHelper(dir
, wxDIR_FILES
);
264 wxPuts(_T("Enumerating files including hidden in current directory:"));
265 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
269 wxPuts(_T("Enumerating everything in root directory:"));
270 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
272 wxPuts(_T("Enumerating directories in root directory:"));
273 TestDirEnumHelper(dir
, wxDIR_DIRS
);
275 wxPuts(_T("Enumerating files in root directory:"));
276 TestDirEnumHelper(dir
, wxDIR_FILES
);
278 wxPuts(_T("Enumerating files including hidden in root directory:"));
279 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
281 wxPuts(_T("Enumerating files in non existing directory:"));
282 wxDir
dirNo(_T("nosuchdir"));
283 TestDirEnumHelper(dirNo
);
286 class DirPrintTraverser
: public wxDirTraverser
289 virtual wxDirTraverseResult
OnFile(const wxString
& WXUNUSED(filename
))
291 return wxDIR_CONTINUE
;
294 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
296 wxString path
, name
, ext
;
297 wxSplitPath(dirname
, &path
, &name
, &ext
);
300 name
<< _T('.') << ext
;
303 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
305 if ( wxIsPathSeparator(*p
) )
309 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
311 return wxDIR_CONTINUE
;
315 static void TestDirTraverse()
317 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
321 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
322 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
325 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
326 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
329 // enum again with custom traverser
330 wxPuts(_T("Now enumerating directories:"));
332 DirPrintTraverser traverser
;
333 dir
.Traverse(traverser
, wxEmptyString
, wxDIR_DIRS
| wxDIR_HIDDEN
);
336 static void TestDirExists()
338 wxPuts(_T("*** Testing wxDir::Exists() ***"));
340 static const wxChar
*dirnames
[] =
343 #if defined(__WXMSW__)
346 _T("\\\\share\\file"),
350 _T("c:\\autoexec.bat"),
351 #elif defined(__UNIX__)
360 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
362 wxPrintf(_T("%-40s: %s\n"),
364 wxDir::Exists(dirnames
[n
]) ? _T("exists")
365 : _T("doesn't exist"));
371 // ----------------------------------------------------------------------------
373 // ----------------------------------------------------------------------------
375 #ifdef TEST_DLLLOADER
377 #include "wx/dynlib.h"
379 static void TestDllLoad()
381 #if defined(__WXMSW__)
382 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
383 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
384 #elif defined(__UNIX__)
385 // weird: using just libc.so does *not* work!
386 static const wxChar
*LIB_NAME
= _T("/lib/libc.so.6");
387 static const wxChar
*FUNC_NAME
= _T("strlen");
389 #error "don't know how to test wxDllLoader on this platform"
392 wxPuts(_T("*** testing basic wxDynamicLibrary functions ***\n"));
394 wxDynamicLibrary
lib(LIB_NAME
);
395 if ( !lib
.IsLoaded() )
397 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
401 typedef int (*wxStrlenType
)(const char *);
402 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
405 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
406 FUNC_NAME
, LIB_NAME
);
410 wxPrintf(_T("Calling %s dynamically loaded from %s "),
411 FUNC_NAME
, LIB_NAME
);
413 if ( pfnStrlen("foo") != 3 )
415 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
419 wxPuts(_T("... ok"));
425 #if defined(__WXMSW__) || defined(__UNIX__)
427 static void TestDllListLoaded()
429 wxPuts(_T("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
431 puts("\nLoaded modules:");
432 wxDynamicLibraryDetailsArray dlls
= wxDynamicLibrary::ListLoaded();
433 const size_t count
= dlls
.GetCount();
434 for ( size_t n
= 0; n
< count
; ++n
)
436 const wxDynamicLibraryDetails
& details
= dlls
[n
];
437 printf("%-45s", details
.GetPath().mb_str());
441 if ( details
.GetAddress(&addr
, &len
) )
443 printf(" %08lx:%08lx",
444 (unsigned long)addr
, (unsigned long)((char *)addr
+ len
));
447 printf(" %s\n", details
.GetVersion().mb_str());
453 #endif // TEST_DLLLOADER
455 // ----------------------------------------------------------------------------
457 // ----------------------------------------------------------------------------
461 #include "wx/utils.h"
463 static wxString
MyGetEnv(const wxString
& var
)
466 if ( !wxGetEnv(var
, &val
) )
469 val
= wxString(_T('\'')) + val
+ _T('\'');
474 static void TestEnvironment()
476 const wxChar
*var
= _T("wxTestVar");
478 wxPuts(_T("*** testing environment access functions ***"));
480 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
481 wxSetEnv(var
, _T("value for wxTestVar"));
482 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
483 wxSetEnv(var
, _T("another value"));
484 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
486 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
487 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
490 #endif // TEST_ENVIRON
492 // ----------------------------------------------------------------------------
494 // ----------------------------------------------------------------------------
498 #include "wx/utils.h"
500 static void TestExecute()
502 wxPuts(_T("*** testing wxExecute ***"));
505 #define COMMAND "cat -n ../../Makefile" // "echo hi"
506 #define SHELL_COMMAND "echo hi from shell"
507 #define REDIRECT_COMMAND COMMAND // "date"
508 #elif defined(__WXMSW__)
509 #define COMMAND "command.com /c echo hi"
510 #define SHELL_COMMAND "echo hi"
511 #define REDIRECT_COMMAND COMMAND
513 #error "no command to exec"
516 wxPrintf(_T("Testing wxShell: "));
518 if ( wxShell(_T(SHELL_COMMAND
)) )
521 wxPuts(_T("ERROR."));
523 wxPrintf(_T("Testing wxExecute: "));
525 if ( wxExecute(_T(COMMAND
), true /* sync */) == 0 )
528 wxPuts(_T("ERROR."));
530 #if 0 // no, it doesn't work (yet?)
531 wxPrintf(_T("Testing async wxExecute: "));
533 if ( wxExecute(COMMAND
) != 0 )
534 wxPuts(_T("Ok (command launched)."));
536 wxPuts(_T("ERROR."));
539 wxPrintf(_T("Testing wxExecute with redirection:\n"));
540 wxArrayString output
;
541 if ( wxExecute(_T(REDIRECT_COMMAND
), output
) != 0 )
543 wxPuts(_T("ERROR."));
547 size_t count
= output
.GetCount();
548 for ( size_t n
= 0; n
< count
; n
++ )
550 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
557 #endif // TEST_EXECUTE
559 // ----------------------------------------------------------------------------
561 // ----------------------------------------------------------------------------
566 #include "wx/ffile.h"
567 #include "wx/textfile.h"
569 static void TestFileRead()
571 wxPuts(_T("*** wxFile read test ***"));
573 wxFile
file(_T("testdata.fc"));
574 if ( file
.IsOpened() )
576 wxPrintf(_T("File length: %lu\n"), file
.Length());
578 wxPuts(_T("File dump:\n----------"));
580 static const size_t len
= 1024;
584 size_t nRead
= file
.Read(buf
, len
);
585 if ( nRead
== (size_t)wxInvalidOffset
)
587 wxPrintf(_T("Failed to read the file."));
591 fwrite(buf
, nRead
, 1, stdout
);
597 wxPuts(_T("----------"));
601 wxPrintf(_T("ERROR: can't open test file.\n"));
604 wxPuts(wxEmptyString
);
607 static void TestTextFileRead()
609 wxPuts(_T("*** wxTextFile read test ***"));
611 wxTextFile
file(_T("testdata.fc"));
614 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
615 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
619 wxPuts(_T("\nDumping the entire file:"));
620 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
622 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
624 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
626 wxPuts(_T("\nAnd now backwards:"));
627 for ( s
= file
.GetLastLine();
628 file
.GetCurrentLine() != 0;
629 s
= file
.GetPrevLine() )
631 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
633 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
637 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
640 wxPuts(wxEmptyString
);
643 static void TestFileCopy()
645 wxPuts(_T("*** Testing wxCopyFile ***"));
647 static const wxChar
*filename1
= _T("testdata.fc");
648 static const wxChar
*filename2
= _T("test2");
649 if ( !wxCopyFile(filename1
, filename2
) )
651 wxPuts(_T("ERROR: failed to copy file"));
655 wxFFile
f1(filename1
, _T("rb")),
656 f2(filename2
, _T("rb"));
658 if ( !f1
.IsOpened() || !f2
.IsOpened() )
660 wxPuts(_T("ERROR: failed to open file(s)"));
665 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
667 wxPuts(_T("ERROR: failed to read file(s)"));
671 if ( (s1
.length() != s2
.length()) ||
672 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
674 wxPuts(_T("ERROR: copy error!"));
678 wxPuts(_T("File was copied ok."));
684 if ( !wxRemoveFile(filename2
) )
686 wxPuts(_T("ERROR: failed to remove the file"));
689 wxPuts(wxEmptyString
);
694 // ----------------------------------------------------------------------------
696 // ----------------------------------------------------------------------------
700 #include "wx/confbase.h"
701 #include "wx/fileconf.h"
703 static const struct FileConfTestData
705 const wxChar
*name
; // value name
706 const wxChar
*value
; // the value from the file
709 { _T("value1"), _T("one") },
710 { _T("value2"), _T("two") },
711 { _T("novalue"), _T("default") },
714 static void TestFileConfRead()
716 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
718 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
719 _T("testdata.fc"), wxEmptyString
,
720 wxCONFIG_USE_RELATIVE_PATH
);
722 // test simple reading
723 wxPuts(_T("\nReading config file:"));
724 wxString
defValue(_T("default")), value
;
725 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
727 const FileConfTestData
& data
= fcTestData
[n
];
728 value
= fileconf
.Read(data
.name
, defValue
);
729 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
730 if ( value
== data
.value
)
736 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
740 // test enumerating the entries
741 wxPuts(_T("\nEnumerating all root entries:"));
744 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
747 wxPrintf(_T("\t%s = %s\n"),
749 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
751 cont
= fileconf
.GetNextEntry(name
, dummy
);
754 static const wxChar
*testEntry
= _T("TestEntry");
755 wxPrintf(_T("\nTesting deletion of newly created \"Test\" entry: "));
756 fileconf
.Write(testEntry
, _T("A value"));
757 fileconf
.DeleteEntry(testEntry
);
758 wxPrintf(fileconf
.HasEntry(testEntry
) ? _T("ERROR\n") : _T("ok\n"));
761 #endif // TEST_FILECONF
763 // ----------------------------------------------------------------------------
765 // ----------------------------------------------------------------------------
769 #include "wx/filename.h"
772 static void DumpFileName(const wxChar
*desc
, const wxFileName
& fn
)
776 wxString full
= fn
.GetFullPath();
778 wxString vol
, path
, name
, ext
;
779 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
781 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
782 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
784 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
785 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
786 path
.c_str(), name
.c_str(), ext
.c_str());
788 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
789 wxPrintf(_T("with volume: \t'%s'\n"),
790 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
791 wxPrintf(_T("with separator:\t'%s'\n"),
792 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
793 wxPrintf(_T("with both: \t'%s'\n"),
794 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
796 wxPuts(_T("The directories in the path are:"));
797 wxArrayString dirs
= fn
.GetDirs();
798 size_t count
= dirs
.GetCount();
799 for ( size_t n
= 0; n
< count
; n
++ )
801 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
806 static void TestFileNameTemp()
808 wxPuts(_T("*** testing wxFileName temp file creation ***"));
810 static const wxChar
*tmpprefixes
[] =
818 _T("/tmp/foo/bar"), // this one must be an error
822 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
824 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
827 // "error" is not in upper case because it may be ok
828 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
832 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
833 tmpprefixes
[n
], path
.c_str());
835 if ( !wxRemoveFile(path
) )
837 wxLogWarning(_T("Failed to remove temp file '%s'"),
844 static void TestFileNameMakeRelative()
846 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
848 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
850 const FileNameInfo
& fni
= filenames
[n
];
852 wxFileName
fn(fni
.fullname
, fni
.format
);
854 // choose the base dir of the same format
856 switch ( fni
.format
)
859 base
= _T("/usr/bin/");
868 // TODO: I don't know how this is supposed to work there
871 case wxPATH_NATIVE
: // make gcc happy
873 wxFAIL_MSG( _T("unexpected path format") );
876 wxPrintf(_T("'%s' relative to '%s': "),
877 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
879 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
881 wxPuts(_T("unchanged"));
885 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
890 static void TestFileNameMakeAbsolute()
892 wxPuts(_T("*** testing wxFileName::MakeAbsolute() ***"));
894 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
896 const FileNameInfo
& fni
= filenames
[n
];
897 wxFileName
fn(fni
.fullname
, fni
.format
);
899 wxPrintf(_T("'%s' absolutized: "),
900 fn
.GetFullPath(fni
.format
).c_str());
902 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
905 wxPuts(wxEmptyString
);
908 static void TestFileNameDirManip()
910 // TODO: test AppendDir(), RemoveDir(), ...
913 static void TestFileNameComparison()
918 static void TestFileNameOperations()
923 static void TestFileNameCwd()
928 #endif // TEST_FILENAME
930 // ----------------------------------------------------------------------------
931 // wxFileName time functions
932 // ----------------------------------------------------------------------------
936 #include <wx/filename.h>
937 #include <wx/datetime.h>
939 static void TestFileGetTimes()
941 wxFileName
fn(_T("testdata.fc"));
943 wxDateTime dtAccess
, dtMod
, dtCreate
;
944 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
946 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
950 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
952 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
953 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
954 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
955 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
960 static void TestFileSetTimes()
962 wxFileName
fn(_T("testdata.fc"));
966 wxPrintf(_T("ERROR: Touch() failed.\n"));
971 #endif // TEST_FILETIME
973 // ----------------------------------------------------------------------------
975 // ----------------------------------------------------------------------------
980 #include "wx/utils.h" // for wxSetEnv
982 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
984 // find the name of the language from its value
985 static const wxChar
*GetLangName(int lang
)
987 static const wxChar
*languageNames
[] =
997 _T("ARABIC_ALGERIA"),
998 _T("ARABIC_BAHRAIN"),
1001 _T("ARABIC_JORDAN"),
1002 _T("ARABIC_KUWAIT"),
1003 _T("ARABIC_LEBANON"),
1005 _T("ARABIC_MOROCCO"),
1008 _T("ARABIC_SAUDI_ARABIA"),
1011 _T("ARABIC_TUNISIA"),
1018 _T("AZERI_CYRILLIC"),
1033 _T("CHINESE_SIMPLIFIED"),
1034 _T("CHINESE_TRADITIONAL"),
1035 _T("CHINESE_HONGKONG"),
1036 _T("CHINESE_MACAU"),
1037 _T("CHINESE_SINGAPORE"),
1038 _T("CHINESE_TAIWAN"),
1044 _T("DUTCH_BELGIAN"),
1048 _T("ENGLISH_AUSTRALIA"),
1049 _T("ENGLISH_BELIZE"),
1050 _T("ENGLISH_BOTSWANA"),
1051 _T("ENGLISH_CANADA"),
1052 _T("ENGLISH_CARIBBEAN"),
1053 _T("ENGLISH_DENMARK"),
1055 _T("ENGLISH_JAMAICA"),
1056 _T("ENGLISH_NEW_ZEALAND"),
1057 _T("ENGLISH_PHILIPPINES"),
1058 _T("ENGLISH_SOUTH_AFRICA"),
1059 _T("ENGLISH_TRINIDAD"),
1060 _T("ENGLISH_ZIMBABWE"),
1068 _T("FRENCH_BELGIAN"),
1069 _T("FRENCH_CANADIAN"),
1070 _T("FRENCH_LUXEMBOURG"),
1071 _T("FRENCH_MONACO"),
1077 _T("GERMAN_AUSTRIAN"),
1078 _T("GERMAN_BELGIUM"),
1079 _T("GERMAN_LIECHTENSTEIN"),
1080 _T("GERMAN_LUXEMBOURG"),
1098 _T("ITALIAN_SWISS"),
1103 _T("KASHMIRI_INDIA"),
1121 _T("MALAY_BRUNEI_DARUSSALAM"),
1122 _T("MALAY_MALAYSIA"),
1132 _T("NORWEGIAN_BOKMAL"),
1133 _T("NORWEGIAN_NYNORSK"),
1140 _T("PORTUGUESE_BRAZILIAN"),
1143 _T("RHAETO_ROMANCE"),
1146 _T("RUSSIAN_UKRAINE"),
1152 _T("SERBIAN_CYRILLIC"),
1153 _T("SERBIAN_LATIN"),
1154 _T("SERBO_CROATIAN"),
1165 _T("SPANISH_ARGENTINA"),
1166 _T("SPANISH_BOLIVIA"),
1167 _T("SPANISH_CHILE"),
1168 _T("SPANISH_COLOMBIA"),
1169 _T("SPANISH_COSTA_RICA"),
1170 _T("SPANISH_DOMINICAN_REPUBLIC"),
1171 _T("SPANISH_ECUADOR"),
1172 _T("SPANISH_EL_SALVADOR"),
1173 _T("SPANISH_GUATEMALA"),
1174 _T("SPANISH_HONDURAS"),
1175 _T("SPANISH_MEXICAN"),
1176 _T("SPANISH_MODERN"),
1177 _T("SPANISH_NICARAGUA"),
1178 _T("SPANISH_PANAMA"),
1179 _T("SPANISH_PARAGUAY"),
1181 _T("SPANISH_PUERTO_RICO"),
1182 _T("SPANISH_URUGUAY"),
1184 _T("SPANISH_VENEZUELA"),
1188 _T("SWEDISH_FINLAND"),
1206 _T("URDU_PAKISTAN"),
1208 _T("UZBEK_CYRILLIC"),
1221 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1222 return languageNames
[lang
];
1224 return _T("INVALID");
1227 static void TestDefaultLang()
1229 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1231 static const wxChar
*langStrings
[] =
1233 NULL
, // system default
1240 _T("de_DE.iso88591"),
1242 _T("?"), // invalid lang spec
1243 _T("klingonese"), // I bet on some systems it does exist...
1246 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1247 wxLocale::GetSystemEncodingName().c_str(),
1248 wxLocale::GetSystemEncoding());
1250 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1252 const wxChar
*langStr
= langStrings
[n
];
1255 // FIXME: this doesn't do anything at all under Windows, we need
1256 // to create a new wxLocale!
1257 wxSetEnv(_T("LC_ALL"), langStr
);
1260 int lang
= gs_localeDefault
.GetSystemLanguage();
1261 wxPrintf(_T("Locale for '%s' is %s.\n"),
1262 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1266 #endif // TEST_LOCALE
1268 // ----------------------------------------------------------------------------
1270 // ----------------------------------------------------------------------------
1274 #include "wx/mimetype.h"
1276 static void TestMimeEnum()
1278 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1280 wxArrayString mimetypes
;
1282 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1284 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1289 for ( size_t n
= 0; n
< count
; n
++ )
1291 wxFileType
*filetype
=
1292 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1295 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1296 mimetypes
[n
].c_str());
1300 filetype
->GetDescription(&desc
);
1301 filetype
->GetExtensions(exts
);
1303 filetype
->GetIcon(NULL
);
1306 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1309 extsAll
<< _T(", ");
1313 wxPrintf(_T("\t%s: %s (%s)\n"),
1314 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1317 wxPuts(wxEmptyString
);
1320 static void TestMimeOverride()
1322 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1324 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1325 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1327 if ( wxFile::Exists(mailcap
) )
1328 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1330 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1332 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1335 if ( wxFile::Exists(mimetypes
) )
1336 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1338 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1340 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1343 wxPuts(wxEmptyString
);
1346 static void TestMimeFilename()
1348 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1350 static const wxChar
*filenames
[] =
1358 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1360 const wxString fname
= filenames
[n
];
1361 wxString ext
= fname
.AfterLast(_T('.'));
1362 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1365 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1370 if ( !ft
->GetDescription(&desc
) )
1371 desc
= _T("<no description>");
1374 if ( !ft
->GetOpenCommand(&cmd
,
1375 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
1376 cmd
= _T("<no command available>");
1378 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1380 wxPrintf(_T("To open %s (%s) do %s.\n"),
1381 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1387 wxPuts(wxEmptyString
);
1390 static void TestMimeAssociate()
1392 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1394 wxFileTypeInfo
ftInfo(
1395 _T("application/x-xyz"),
1396 _T("xyzview '%s'"), // open cmd
1397 _T(""), // print cmd
1398 _T("XYZ File"), // description
1399 _T(".xyz"), // extensions
1400 NULL
// end of extensions
1402 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1404 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1407 wxPuts(_T("ERROR: failed to create association!"));
1411 // TODO: read it back
1415 wxPuts(wxEmptyString
);
1420 // ----------------------------------------------------------------------------
1421 // misc information functions
1422 // ----------------------------------------------------------------------------
1424 #ifdef TEST_INFO_FUNCTIONS
1426 #include "wx/utils.h"
1428 static void TestDiskInfo()
1430 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1434 wxChar pathname
[128];
1435 wxPrintf(_T("\nEnter a directory name: "));
1436 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1439 // kill the last '\n'
1440 pathname
[wxStrlen(pathname
) - 1] = 0;
1442 wxLongLong total
, free
;
1443 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1445 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1449 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1450 (total
/ 1024).ToString().c_str(),
1451 (free
/ 1024).ToString().c_str(),
1457 static void TestOsInfo()
1459 wxPuts(_T("*** Testing OS info functions ***\n"));
1462 wxGetOsVersion(&major
, &minor
);
1463 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1464 wxGetOsDescription().c_str(), major
, minor
);
1466 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1468 wxPrintf(_T("Host name is %s (%s).\n"),
1469 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1471 wxPuts(wxEmptyString
);
1474 static void TestUserInfo()
1476 wxPuts(_T("*** Testing user info functions ***\n"));
1478 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1479 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1480 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1481 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1483 wxPuts(wxEmptyString
);
1486 #endif // TEST_INFO_FUNCTIONS
1488 // ----------------------------------------------------------------------------
1490 // ----------------------------------------------------------------------------
1492 #ifdef TEST_PATHLIST
1495 #define CMD_IN_PATH _T("ls")
1497 #define CMD_IN_PATH _T("command.com")
1500 static void TestPathList()
1502 wxPuts(_T("*** Testing wxPathList ***\n"));
1504 wxPathList pathlist
;
1505 pathlist
.AddEnvList(_T("PATH"));
1506 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
1509 wxPrintf(_T("ERROR: command not found in the path.\n"));
1513 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
1517 #endif // TEST_PATHLIST
1519 // ----------------------------------------------------------------------------
1520 // regular expressions
1521 // ----------------------------------------------------------------------------
1525 #include "wx/regex.h"
1527 static void TestRegExInteractive()
1529 wxPuts(_T("*** Testing RE interactively ***"));
1533 wxChar pattern
[128];
1534 wxPrintf(_T("\nEnter a pattern: "));
1535 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1538 // kill the last '\n'
1539 pattern
[wxStrlen(pattern
) - 1] = 0;
1542 if ( !re
.Compile(pattern
) )
1550 wxPrintf(_T("Enter text to match: "));
1551 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
1554 // kill the last '\n'
1555 text
[wxStrlen(text
) - 1] = 0;
1557 if ( !re
.Matches(text
) )
1559 wxPrintf(_T("No match.\n"));
1563 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
1566 for ( size_t n
= 1; ; n
++ )
1568 if ( !re
.GetMatch(&start
, &len
, n
) )
1573 wxPrintf(_T("Subexpr %u matched '%s'\n"),
1574 n
, wxString(text
+ start
, len
).c_str());
1581 #endif // TEST_REGEX
1583 // ----------------------------------------------------------------------------
1585 // ----------------------------------------------------------------------------
1595 static void TestDbOpen()
1603 // ----------------------------------------------------------------------------
1605 // ----------------------------------------------------------------------------
1608 NB: this stuff was taken from the glibc test suite and modified to build
1609 in wxWidgets: if I read the copyright below properly, this shouldn't
1615 #ifdef wxTEST_PRINTF
1616 // use our functions from wxchar.cpp
1620 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
1621 // in the tests below
1622 int wxPrintf( const wxChar
*format
, ... );
1623 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
1626 #include "wx/longlong.h"
1630 static void rfg1 (void);
1631 static void rfg2 (void);
1635 fmtchk (const wxChar
*fmt
)
1637 (void) wxPrintf(_T("%s:\t`"), fmt
);
1638 (void) wxPrintf(fmt
, 0x12);
1639 (void) wxPrintf(_T("'\n"));
1643 fmtst1chk (const wxChar
*fmt
)
1645 (void) wxPrintf(_T("%s:\t`"), fmt
);
1646 (void) wxPrintf(fmt
, 4, 0x12);
1647 (void) wxPrintf(_T("'\n"));
1651 fmtst2chk (const wxChar
*fmt
)
1653 (void) wxPrintf(_T("%s:\t`"), fmt
);
1654 (void) wxPrintf(fmt
, 4, 4, 0x12);
1655 (void) wxPrintf(_T("'\n"));
1658 /* This page is covered by the following copyright: */
1660 /* (C) Copyright C E Chew
1662 * Feel free to copy, use and distribute this software provided:
1664 * 1. you do not pretend that you wrote it
1665 * 2. you leave this copyright notice intact.
1669 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
1676 /* Formatted Output Test
1678 * This exercises the output formatting code.
1681 wxChar
*PointerNull
= NULL
;
1688 wxChar
*prefix
= buf
;
1691 wxPuts(_T("\nFormatted output test"));
1692 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
1693 wxStrcpy(prefix
, _T("%"));
1694 for (i
= 0; i
< 2; i
++) {
1695 for (j
= 0; j
< 2; j
++) {
1696 for (k
= 0; k
< 2; k
++) {
1697 for (l
= 0; l
< 2; l
++) {
1698 wxStrcpy(prefix
, _T("%"));
1699 if (i
== 0) wxStrcat(prefix
, _T("-"));
1700 if (j
== 0) wxStrcat(prefix
, _T("+"));
1701 if (k
== 0) wxStrcat(prefix
, _T("#"));
1702 if (l
== 0) wxStrcat(prefix
, _T("0"));
1703 wxPrintf(_T("%5s |"), prefix
);
1704 wxStrcpy(tp
, prefix
);
1705 wxStrcat(tp
, _T("6d |"));
1707 wxStrcpy(tp
, prefix
);
1708 wxStrcat(tp
, _T("6o |"));
1710 wxStrcpy(tp
, prefix
);
1711 wxStrcat(tp
, _T("6x |"));
1713 wxStrcpy(tp
, prefix
);
1714 wxStrcat(tp
, _T("6X |"));
1716 wxStrcpy(tp
, prefix
);
1717 wxStrcat(tp
, _T("6u |"));
1724 wxPrintf(_T("%10s\n"), PointerNull
);
1725 wxPrintf(_T("%-10s\n"), PointerNull
);
1728 static void TestPrintf()
1730 static wxChar shortstr
[] = _T("Hi, Z.");
1731 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
1732 I am ready for my first lesson today.");
1734 wxString test_format
;
1738 fmtchk(_T("%4.4x"));
1739 fmtchk(_T("%04.4x"));
1740 fmtchk(_T("%4.3x"));
1741 fmtchk(_T("%04.3x"));
1743 fmtst1chk(_T("%.*x"));
1744 fmtst1chk(_T("%0*x"));
1745 fmtst2chk(_T("%*.*x"));
1746 fmtst2chk(_T("%0*.*x"));
1748 wxString bad_format
= _T("bad format:\t\"%b\"\n");
1749 wxPrintf(bad_format
.c_str());
1750 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
1752 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
1753 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
1754 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
1755 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
1756 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
1757 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
1758 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
1759 test_format
= _T("left-adjusted ZLDN:\t\"%-010ld\"\n");
1760 wxPrintf(test_format
.c_str(), -123456);
1761 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
1762 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
1764 test_format
= _T("zero-padded string:\t\"%010s\"\n");
1765 wxPrintf(test_format
.c_str(), shortstr
);
1766 test_format
= _T("left-adjusted Z string:\t\"%-010s\"\n");
1767 wxPrintf(test_format
.c_str(), shortstr
);
1768 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
1769 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
1770 wxPrintf(_T("null string:\t\"%s\"\n"), PointerNull
);
1771 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
1773 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
1774 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
1775 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
1776 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
1777 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
1778 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
1779 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
1780 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
1781 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
1782 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
1783 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
1784 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
1786 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
1787 wxPrintf (_T(" %6.5f\n"), .1);
1788 wxPrintf (_T("x%5.4fx\n"), .5);
1790 wxPrintf (_T("%#03x\n"), 1);
1792 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
1798 while (niter
-- != 0)
1799 wxPrintf (_T("%.17e\n"), d
/ 2);
1804 // Open Watcom cause compiler error here
1805 // Error! E173: col(24) floating-point constant too small to represent
1806 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
1809 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
1810 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
1811 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
1812 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
1813 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
1814 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
1815 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
1816 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
1817 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
1818 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
1823 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
1825 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
1826 rc
, WXSIZEOF(buf
), buf
);
1829 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
1830 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
1836 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
1837 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
1838 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
1839 wxPrintf (_T("%g should be 123.456\n"), 123.456);
1840 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
1841 wxPrintf (_T("%g should be 10\n"), 10.0);
1842 wxPrintf (_T("%g should be 0.02\n"), 0.02);
1846 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
1852 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
1854 result
|= wxStrcmp (buf
,
1855 _T("onetwo three "));
1857 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
1864 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
1866 // for some reason below line fails under Borland
1867 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
1870 if (wxStrcmp (buf
, _T("40000000000")) != 0)
1873 wxPuts (_T("\tFAILED"));
1875 wxUnusedVar(result
);
1876 wxPuts (wxEmptyString
);
1878 #endif // wxLongLong_t
1880 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
1881 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
1883 wxPuts (_T("--- Should be no further output. ---"));
1892 memset (bytes
, '\xff', sizeof bytes
);
1893 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
1894 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
1895 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
1897 wxPuts (_T("%hhn overwrite more bytes"));
1902 wxPuts (_T("%hhn wrote incorrect value"));
1914 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
1915 if (wxStrcmp (buf
, _T(" ")) != 0)
1916 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
1917 wxSprintf (buf
, _T("%5.f"), 33.3);
1918 if (wxStrcmp (buf
, _T(" 33")) != 0)
1919 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
1920 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
1921 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
1922 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
1923 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
1924 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
1925 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
1926 wxSprintf (buf
, _T("%.g"), 33.3);
1927 if (wxStrcmp (buf
, _T("3e+01")) != 0)
1928 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
1929 wxSprintf (buf
, _T("%.G"), 33.3);
1930 if (wxStrcmp (buf
, _T("3E+01")) != 0)
1931 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
1939 wxString test_format
;
1942 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
1943 if (wxStrcmp (buf
, _T("3")) != 0)
1944 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1946 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
1947 if (wxStrcmp (buf
, _T("3")) != 0)
1948 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1950 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
1951 if (wxStrcmp (buf
, _T(" 3")) != 0)
1952 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
1954 test_format
= _T("%04.*o");
1955 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1956 if (wxStrcmp (buf
, _T(" 041")) != 0)
1957 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
1959 test_format
= _T("%09.*u");
1960 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1961 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
1962 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
1964 test_format
= _T("%04.*x");
1965 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1966 if (wxStrcmp (buf
, _T(" 021")) != 0)
1967 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1969 test_format
= _T("%04.*X");
1970 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1971 if (wxStrcmp (buf
, _T(" 021")) != 0)
1972 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1975 #endif // TEST_PRINTF
1977 // ----------------------------------------------------------------------------
1978 // registry and related stuff
1979 // ----------------------------------------------------------------------------
1981 // this is for MSW only
1984 #undef TEST_REGISTRY
1989 #include "wx/confbase.h"
1990 #include "wx/msw/regconf.h"
1993 static void TestRegConfWrite()
1995 wxConfig
*config
= new wxConfig(_T("myapp"));
1996 config
->SetPath(_T("/group1"));
1997 config
->Write(_T("entry1"), _T("foo"));
1998 config
->SetPath(_T("/group2"));
1999 config
->Write(_T("entry1"), _T("bar"));
2003 static void TestRegConfRead()
2005 wxConfig
*config
= new wxConfig(_T("myapp"));
2009 config
->SetPath(_T("/"));
2010 wxPuts(_T("Enumerating / subgroups:"));
2011 bool bCont
= config
->GetFirstGroup(str
, dummy
);
2015 bCont
= config
->GetNextGroup(str
, dummy
);
2019 #endif // TEST_REGCONF
2021 #ifdef TEST_REGISTRY
2023 #include "wx/msw/registry.h"
2025 // I chose this one because I liked its name, but it probably only exists under
2027 static const wxChar
*TESTKEY
=
2028 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2030 static void TestRegistryRead()
2032 wxPuts(_T("*** testing registry reading ***"));
2034 wxRegKey
key(TESTKEY
);
2035 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2038 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2043 size_t nSubKeys
, nValues
;
2044 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2046 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2049 wxPrintf(_T("Enumerating values:\n"));
2053 bool cont
= key
.GetFirstValue(value
, dummy
);
2056 wxPrintf(_T("Value '%s': type "), value
.c_str());
2057 switch ( key
.GetValueType(value
) )
2059 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2060 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2061 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2062 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2063 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2064 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2065 default: wxPrintf(_T("other (unknown)")); break;
2068 wxPrintf(_T(", value = "));
2069 if ( key
.IsNumericValue(value
) )
2072 key
.QueryValue(value
, &val
);
2073 wxPrintf(_T("%ld"), val
);
2078 key
.QueryValue(value
, val
);
2079 wxPrintf(_T("'%s'"), val
.c_str());
2081 key
.QueryRawValue(value
, val
);
2082 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2087 cont
= key
.GetNextValue(value
, dummy
);
2091 static void TestRegistryAssociation()
2094 The second call to deleteself genertaes an error message, with a
2095 messagebox saying .flo is crucial to system operation, while the .ddf
2096 call also fails, but with no error message
2101 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2103 key
= _T("ddxf_auto_file") ;
2104 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2106 key
= _T("ddxf_auto_file") ;
2107 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2109 key
= _T("program,0") ;
2110 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2112 key
= _T("program \"%1\"") ;
2114 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2116 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2118 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2120 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2124 #endif // TEST_REGISTRY
2126 // ----------------------------------------------------------------------------
2128 // ----------------------------------------------------------------------------
2130 #ifdef TEST_SCOPEGUARD
2132 #include "wx/scopeguard.h"
2134 static void function0() { puts("function0()"); }
2135 static void function1(int n
) { printf("function1(%d)\n", n
); }
2136 static void function2(double x
, char c
) { printf("function2(%g, %c)\n", x
, c
); }
2140 void method0() { printf("method0()\n"); }
2141 void method1(int n
) { printf("method1(%d)\n", n
); }
2142 void method2(double x
, char c
) { printf("method2(%g, %c)\n", x
, c
); }
2145 static void TestScopeGuard()
2147 wxON_BLOCK_EXIT0(function0
);
2148 wxON_BLOCK_EXIT1(function1
, 17);
2149 wxON_BLOCK_EXIT2(function2
, 3.14, 'p');
2152 wxON_BLOCK_EXIT_OBJ0(obj
, &Object::method0
);
2153 wxON_BLOCK_EXIT_OBJ1(obj
, &Object::method1
, 7);
2154 wxON_BLOCK_EXIT_OBJ2(obj
, &Object::method2
, 2.71, 'e');
2156 wxScopeGuard dismissed
= wxMakeGuard(function0
);
2157 dismissed
.Dismiss();
2162 // ----------------------------------------------------------------------------
2164 // ----------------------------------------------------------------------------
2168 #include "wx/socket.h"
2169 #include "wx/protocol/protocol.h"
2170 #include "wx/protocol/http.h"
2172 static void TestSocketServer()
2174 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2176 static const int PORT
= 3000;
2181 wxSocketServer
*server
= new wxSocketServer(addr
);
2182 if ( !server
->Ok() )
2184 wxPuts(_T("ERROR: failed to bind"));
2192 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2194 wxSocketBase
*socket
= server
->Accept();
2197 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2201 wxPuts(_T("Server: got a client."));
2203 server
->SetTimeout(60); // 1 min
2206 while ( !close
&& socket
->IsConnected() )
2209 wxChar ch
= _T('\0');
2212 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2214 // don't log error if the client just close the connection
2215 if ( socket
->IsConnected() )
2217 wxPuts(_T("ERROR: in wxSocket::Read."));
2237 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
2238 if ( s
== _T("close") )
2240 wxPuts(_T("Closing connection"));
2244 else if ( s
== _T("quit") )
2249 wxPuts(_T("Shutting down the server"));
2251 else // not a special command
2253 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2254 socket
->Write("\r\n", 2);
2255 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
2261 wxPuts(_T("Server: lost a client unexpectedly."));
2267 // same as "delete server" but is consistent with GUI programs
2271 static void TestSocketClient()
2273 wxPuts(_T("*** Testing wxSocketClient ***\n"));
2275 static const wxChar
*hostname
= _T("www.wxwidgets.org");
2278 addr
.Hostname(hostname
);
2281 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
2283 wxSocketClient client
;
2284 if ( !client
.Connect(addr
) )
2286 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2290 wxPrintf(_T("--- Connected to %s:%u...\n"),
2291 addr
.Hostname().c_str(), addr
.Service());
2295 // could use simply "GET" here I suppose
2297 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
2298 client
.Write(cmdGet
, cmdGet
.length());
2299 wxPrintf(_T("--- Sent command '%s' to the server\n"),
2300 MakePrintable(cmdGet
).c_str());
2301 client
.Read(buf
, WXSIZEOF(buf
));
2302 wxPrintf(_T("--- Server replied:\n%s"), buf
);
2306 #endif // TEST_SOCKETS
2308 // ----------------------------------------------------------------------------
2310 // ----------------------------------------------------------------------------
2314 #include "wx/protocol/ftp.h"
2318 #define FTP_ANONYMOUS
2320 #ifdef FTP_ANONYMOUS
2321 static const wxChar
*directory
= _T("/pub");
2322 static const wxChar
*filename
= _T("welcome.msg");
2324 static const wxChar
*directory
= _T("/etc");
2325 static const wxChar
*filename
= _T("issue");
2328 static bool TestFtpConnect()
2330 wxPuts(_T("*** Testing FTP connect ***"));
2332 #ifdef FTP_ANONYMOUS
2333 static const wxChar
*hostname
= _T("ftp.wxwidgets.org");
2335 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
2336 #else // !FTP_ANONYMOUS
2337 static const wxChar
*hostname
= "localhost";
2340 wxFgets(user
, WXSIZEOF(user
), stdin
);
2341 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
2344 wxChar password
[256];
2345 wxPrintf(_T("Password for %s: "), password
);
2346 wxFgets(password
, WXSIZEOF(password
), stdin
);
2347 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
2348 ftp
.SetPassword(password
);
2350 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
2351 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2353 if ( !ftp
.Connect(hostname
) )
2355 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2361 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
2362 hostname
, ftp
.Pwd().c_str());
2369 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2370 static void TestFtpWuFtpd()
2373 static const wxChar
*hostname
= _T("ftp.eudora.com");
2374 if ( !ftp
.Connect(hostname
) )
2376 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2380 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
2381 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2384 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2388 size_t size
= in
->GetSize();
2389 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2391 wxChar
*data
= new wxChar
[size
];
2392 if ( !in
->Read(data
, size
) )
2394 wxPuts(_T("ERROR: read error"));
2398 wxPrintf(_T("Successfully retrieved the file.\n"));
2407 static void TestFtpList()
2409 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
2412 if ( !ftp
.ChDir(directory
) )
2414 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2417 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2419 // test NLIST and LIST
2420 wxArrayString files
;
2421 if ( !ftp
.GetFilesList(files
) )
2423 wxPuts(_T("ERROR: failed to get NLIST of files"));
2427 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
2428 size_t count
= files
.GetCount();
2429 for ( size_t n
= 0; n
< count
; n
++ )
2431 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2433 wxPuts(_T("End of the file list"));
2436 if ( !ftp
.GetDirList(files
) )
2438 wxPuts(_T("ERROR: failed to get LIST of files"));
2442 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
2443 size_t count
= files
.GetCount();
2444 for ( size_t n
= 0; n
< count
; n
++ )
2446 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2448 wxPuts(_T("End of the file list"));
2451 if ( !ftp
.ChDir(_T("..")) )
2453 wxPuts(_T("ERROR: failed to cd to .."));
2456 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2459 static void TestFtpDownload()
2461 wxPuts(_T("*** Testing wxFTP download ***\n"));
2464 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2467 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2471 size_t size
= in
->GetSize();
2472 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2475 wxChar
*data
= new wxChar
[size
];
2476 if ( !in
->Read(data
, size
) )
2478 wxPuts(_T("ERROR: read error"));
2482 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
2490 static void TestFtpFileSize()
2492 wxPuts(_T("*** Testing FTP SIZE command ***"));
2494 if ( !ftp
.ChDir(directory
) )
2496 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2499 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2501 if ( ftp
.FileExists(filename
) )
2503 int size
= ftp
.GetFileSize(filename
);
2505 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
2507 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
2511 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
2515 static void TestFtpMisc()
2517 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
2519 if ( ftp
.SendCommand(_T("STAT")) != '2' )
2521 wxPuts(_T("ERROR: STAT failed"));
2525 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
2528 if ( ftp
.SendCommand(_T("HELP SITE")) != '2' )
2530 wxPuts(_T("ERROR: HELP SITE failed"));
2534 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
2535 ftp
.GetLastResult().c_str());
2539 static void TestFtpInteractive()
2541 wxPuts(_T("\n*** Interactive wxFTP test ***"));
2547 wxPrintf(_T("Enter FTP command: "));
2548 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
2551 // kill the last '\n'
2552 buf
[wxStrlen(buf
) - 1] = 0;
2554 // special handling of LIST and NLST as they require data connection
2555 wxString
start(buf
, 4);
2557 if ( start
== _T("LIST") || start
== _T("NLST") )
2560 if ( wxStrlen(buf
) > 4 )
2563 wxArrayString files
;
2564 if ( !ftp
.GetList(files
, wildcard
, start
== _T("LIST")) )
2566 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
2570 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
2571 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2572 size_t count
= files
.GetCount();
2573 for ( size_t n
= 0; n
< count
; n
++ )
2575 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2577 wxPuts(_T("--- End of the file list"));
2582 wxChar ch
= ftp
.SendCommand(buf
);
2583 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
2586 wxPrintf(_T(" (return code %c)"), ch
);
2589 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
2593 wxPuts(_T("\n*** done ***"));
2596 static void TestFtpUpload()
2598 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
2601 static const wxChar
*file1
= _T("test1");
2602 static const wxChar
*file2
= _T("test2");
2603 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2606 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2607 out
->Write("First hello", 11);
2611 // send a command to check the remote file
2612 if ( ftp
.SendCommand(wxString(_T("STAT ")) + file1
) != '2' )
2614 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
2618 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
2619 file1
, ftp
.GetLastResult().c_str());
2622 out
= ftp
.GetOutputStream(file2
);
2625 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2626 out
->Write("Second hello", 12);
2633 // ----------------------------------------------------------------------------
2635 // ----------------------------------------------------------------------------
2637 #ifdef TEST_STACKWALKER
2639 #if wxUSE_STACKWALKER
2641 #include "wx/stackwalk.h"
2643 class StackDump
: public wxStackWalker
2646 StackDump(const char *argv0
)
2647 : wxStackWalker(argv0
)
2653 wxPuts(_T("Stack dump:"));
2655 wxStackWalker::Walk();
2659 virtual void OnStackFrame(const wxStackFrame
& frame
)
2661 printf("[%2d] ", frame
.GetLevel());
2663 wxString name
= frame
.GetName();
2664 if ( !name
.empty() )
2666 printf("%-20.40s", name
.mb_str());
2670 printf("0x%08lx", (unsigned long)frame
.GetAddress());
2673 if ( frame
.HasSourceLocation() )
2676 frame
.GetFileName().mb_str(),
2683 for ( size_t n
= 0; frame
.GetParam(n
, &type
, &name
, &val
); n
++ )
2685 printf("\t%s %s = %s\n", type
.mb_str(), name
.mb_str(), val
.mb_str());
2690 static void TestStackWalk(const char *argv0
)
2692 wxPuts(_T("*** Testing wxStackWalker ***\n"));
2694 StackDump
dump(argv0
);
2698 #endif // wxUSE_STACKWALKER
2700 #endif // TEST_STACKWALKER
2702 // ----------------------------------------------------------------------------
2704 // ----------------------------------------------------------------------------
2706 #ifdef TEST_STDPATHS
2708 #include "wx/stdpaths.h"
2710 static void TestStandardPaths()
2712 wxPuts(_T("*** Testing wxStandardPaths ***\n"));
2714 wxTheApp
->SetAppName(_T("console"));
2716 wxStandardPaths
& stdp
= wxStandardPaths::Get();
2717 wxPrintf(_T("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
2718 wxPrintf(_T("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
2719 wxPrintf(_T("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
2720 wxPrintf(_T("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
2721 wxPrintf(_T("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
2722 wxPrintf(_T("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
2723 wxPrintf(_T("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
2726 #endif // TEST_STDPATHS
2728 // ----------------------------------------------------------------------------
2730 // ----------------------------------------------------------------------------
2734 #include "wx/wfstream.h"
2735 #include "wx/mstream.h"
2737 static void TestFileStream()
2739 wxPuts(_T("*** Testing wxFileInputStream ***"));
2741 static const wxString filename
= _T("testdata.fs");
2743 wxFileOutputStream
fsOut(filename
);
2744 fsOut
.Write("foo", 3);
2747 wxFileInputStream
fsIn(filename
);
2748 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
2749 while ( !fsIn
.Eof() )
2751 wxPutchar(fsIn
.GetC());
2754 if ( !wxRemoveFile(filename
) )
2756 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
.c_str());
2759 wxPuts(_T("\n*** wxFileInputStream test done ***"));
2762 static void TestMemoryStream()
2764 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
2766 wxMemoryOutputStream memOutStream
;
2767 wxPrintf(_T("Initially out stream offset: %lu\n"),
2768 (unsigned long)memOutStream
.TellO());
2770 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
2772 memOutStream
.PutC(*p
);
2775 wxPrintf(_T("Final out stream offset: %lu\n"),
2776 (unsigned long)memOutStream
.TellO());
2778 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
2781 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
2783 wxMemoryInputStream
memInpStream(buf
, len
);
2784 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2785 while ( !memInpStream
.Eof() )
2787 wxPutchar(memInpStream
.GetC());
2790 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
2793 #endif // TEST_STREAMS
2795 // ----------------------------------------------------------------------------
2797 // ----------------------------------------------------------------------------
2801 #include "wx/timer.h"
2802 #include "wx/utils.h"
2804 static void TestStopWatch()
2806 wxPuts(_T("*** Testing wxStopWatch ***\n"));
2810 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
2813 wxPrintf(_T("\t%ldms\n"), sw
.Time());
2815 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
2819 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2822 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
2825 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2828 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
2831 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2834 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
2835 for ( size_t n
= 0; n
< 70; n
++ )
2839 for ( size_t m
= 0; m
< 100000; m
++ )
2841 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2843 wxPuts(_T("\ntime is negative - ERROR!"));
2851 wxPuts(_T(", ok."));
2854 #endif // TEST_TIMER
2856 // ----------------------------------------------------------------------------
2858 // ----------------------------------------------------------------------------
2862 #include "wx/vcard.h"
2864 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2867 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2870 wxPrintf(_T("%s%s"),
2871 wxString(_T('\t'), level
).c_str(),
2872 vcObj
->GetName().c_str());
2875 switch ( vcObj
->GetType() )
2877 case wxVCardObject::String
:
2878 case wxVCardObject::UString
:
2881 vcObj
->GetValue(&val
);
2882 value
<< _T('"') << val
<< _T('"');
2886 case wxVCardObject::Int
:
2889 vcObj
->GetValue(&i
);
2890 value
.Printf(_T("%u"), i
);
2894 case wxVCardObject::Long
:
2897 vcObj
->GetValue(&l
);
2898 value
.Printf(_T("%lu"), l
);
2902 case wxVCardObject::None
:
2905 case wxVCardObject::Object
:
2906 value
= _T("<node>");
2910 value
= _T("<unknown value type>");
2914 wxPrintf(_T(" = %s"), value
.c_str());
2917 DumpVObject(level
+ 1, *vcObj
);
2920 vcObj
= vcard
.GetNextProp(&cookie
);
2924 static void DumpVCardAddresses(const wxVCard
& vcard
)
2926 wxPuts(_T("\nShowing all addresses from vCard:\n"));
2930 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2934 int flags
= addr
->GetFlags();
2935 if ( flags
& wxVCardAddress::Domestic
)
2937 flagsStr
<< _T("domestic ");
2939 if ( flags
& wxVCardAddress::Intl
)
2941 flagsStr
<< _T("international ");
2943 if ( flags
& wxVCardAddress::Postal
)
2945 flagsStr
<< _T("postal ");
2947 if ( flags
& wxVCardAddress::Parcel
)
2949 flagsStr
<< _T("parcel ");
2951 if ( flags
& wxVCardAddress::Home
)
2953 flagsStr
<< _T("home ");
2955 if ( flags
& wxVCardAddress::Work
)
2957 flagsStr
<< _T("work ");
2960 wxPrintf(_T("Address %u:\n")
2962 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2965 addr
->GetPostOffice().c_str(),
2966 addr
->GetExtAddress().c_str(),
2967 addr
->GetStreet().c_str(),
2968 addr
->GetLocality().c_str(),
2969 addr
->GetRegion().c_str(),
2970 addr
->GetPostalCode().c_str(),
2971 addr
->GetCountry().c_str()
2975 addr
= vcard
.GetNextAddress(&cookie
);
2979 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2981 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
2985 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2989 int flags
= phone
->GetFlags();
2990 if ( flags
& wxVCardPhoneNumber::Voice
)
2992 flagsStr
<< _T("voice ");
2994 if ( flags
& wxVCardPhoneNumber::Fax
)
2996 flagsStr
<< _T("fax ");
2998 if ( flags
& wxVCardPhoneNumber::Cellular
)
3000 flagsStr
<< _T("cellular ");
3002 if ( flags
& wxVCardPhoneNumber::Modem
)
3004 flagsStr
<< _T("modem ");
3006 if ( flags
& wxVCardPhoneNumber::Home
)
3008 flagsStr
<< _T("home ");
3010 if ( flags
& wxVCardPhoneNumber::Work
)
3012 flagsStr
<< _T("work ");
3015 wxPrintf(_T("Phone number %u:\n")
3020 phone
->GetNumber().c_str()
3024 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3028 static void TestVCardRead()
3030 wxPuts(_T("*** Testing wxVCard reading ***\n"));
3032 wxVCard
vcard(_T("vcard.vcf"));
3033 if ( !vcard
.IsOk() )
3035 wxPuts(_T("ERROR: couldn't load vCard."));
3039 // read individual vCard properties
3040 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3044 vcObj
->GetValue(&value
);
3049 value
= _T("<none>");
3052 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
3055 if ( !vcard
.GetFullName(&value
) )
3057 value
= _T("<none>");
3060 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
3062 // now show how to deal with multiply occuring properties
3063 DumpVCardAddresses(vcard
);
3064 DumpVCardPhoneNumbers(vcard
);
3066 // and finally show all
3067 wxPuts(_T("\nNow dumping the entire vCard:\n")
3068 "-----------------------------\n");
3070 DumpVObject(0, vcard
);
3074 static void TestVCardWrite()
3076 wxPuts(_T("*** Testing wxVCard writing ***\n"));
3079 if ( !vcard
.IsOk() )
3081 wxPuts(_T("ERROR: couldn't create vCard."));
3086 vcard
.SetName("Zeitlin", "Vadim");
3087 vcard
.SetFullName("Vadim Zeitlin");
3088 vcard
.SetOrganization("wxWidgets", "R&D");
3090 // just dump the vCard back
3091 wxPuts(_T("Entire vCard follows:\n"));
3092 wxPuts(vcard
.Write());
3096 #endif // TEST_VCARD
3098 // ----------------------------------------------------------------------------
3100 // ----------------------------------------------------------------------------
3102 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3108 #include "wx/volume.h"
3110 static const wxChar
*volumeKinds
[] =
3116 _T("network volume"),
3120 static void TestFSVolume()
3122 wxPuts(_T("*** Testing wxFSVolume class ***"));
3124 wxArrayString volumes
= wxFSVolume::GetVolumes();
3125 size_t count
= volumes
.GetCount();
3129 wxPuts(_T("ERROR: no mounted volumes?"));
3133 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3135 for ( size_t n
= 0; n
< count
; n
++ )
3137 wxFSVolume
vol(volumes
[n
]);
3140 wxPuts(_T("ERROR: couldn't create volume"));
3144 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3146 vol
.GetDisplayName().c_str(),
3147 vol
.GetName().c_str(),
3148 volumeKinds
[vol
.GetKind()],
3149 vol
.IsWritable() ? _T("rw") : _T("ro"),
3150 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3155 #endif // TEST_VOLUME
3157 // ----------------------------------------------------------------------------
3158 // wide char and Unicode support
3159 // ----------------------------------------------------------------------------
3163 #include "wx/strconv.h"
3164 #include "wx/fontenc.h"
3165 #include "wx/encconv.h"
3166 #include "wx/buffer.h"
3168 static const unsigned char utf8koi8r
[] =
3170 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3171 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3172 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3173 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3174 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3175 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3176 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3179 static const unsigned char utf8iso8859_1
[] =
3181 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3182 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3183 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3184 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3185 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3188 static const unsigned char utf8Invalid
[] =
3190 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3191 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3192 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3193 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3197 static const struct Utf8Data
3199 const unsigned char *text
;
3201 const wxChar
*charset
;
3202 wxFontEncoding encoding
;
3205 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3206 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3207 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3210 static void TestUtf8()
3212 wxPuts(_T("*** Testing UTF8 support ***\n"));
3217 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3219 const Utf8Data
& u8d
= utf8data
[n
];
3220 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3221 WXSIZEOF(wbuf
)) == (size_t)-1 )
3223 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3227 wxCSConv
conv(u8d
.charset
);
3228 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3230 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3234 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3238 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
));
3240 s
= _T("<< conversion failed >>");
3241 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3245 wxPuts(wxEmptyString
);
3248 static void TestEncodingConverter()
3250 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3252 // using wxEncodingConverter should give the same result as above
3255 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3256 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3258 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3262 wxEncodingConverter ec
;
3263 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3264 ec
.Convert(wbuf
, buf
);
3265 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
3268 wxPuts(wxEmptyString
);
3271 #endif // TEST_WCHAR
3273 // ----------------------------------------------------------------------------
3275 // ----------------------------------------------------------------------------
3279 #include "wx/filesys.h"
3280 #include "wx/fs_zip.h"
3281 #include "wx/zipstrm.h"
3283 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3285 static void TestZipStreamRead()
3287 wxPuts(_T("*** Testing ZIP reading ***\n"));
3289 static const wxString filename
= _T("foo");
3290 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3291 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3293 wxPrintf(_T("Dumping the file '%s':\n"), filename
.c_str());
3294 while ( !istr
.Eof() )
3296 wxPutchar(istr
.GetC());
3300 wxPuts(_T("\n----- done ------"));
3303 static void DumpZipDirectory(wxFileSystem
& fs
,
3304 const wxString
& dir
,
3305 const wxString
& indent
)
3307 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3308 TESTFILE_ZIP
, dir
.c_str());
3309 wxString wildcard
= prefix
+ _T("/*");
3311 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3312 while ( !dirname
.empty() )
3314 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3316 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3321 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3323 DumpZipDirectory(fs
, dirname
,
3324 indent
+ wxString(_T(' '), 4));
3326 dirname
= fs
.FindNext();
3329 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3330 while ( !filename
.empty() )
3332 if ( !filename
.StartsWith(prefix
, &filename
) )
3334 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3339 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3341 filename
= fs
.FindNext();
3345 static void TestZipFileSystem()
3347 wxPuts(_T("*** Testing ZIP file system ***\n"));
3349 wxFileSystem::AddHandler(new wxZipFSHandler
);
3351 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3353 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3358 // ----------------------------------------------------------------------------
3360 // ----------------------------------------------------------------------------
3362 #ifdef TEST_DATETIME
3364 #include "wx/math.h"
3365 #include "wx/datetime.h"
3367 // this test miscellaneous static wxDateTime functions
3371 static void TestTimeStatic()
3373 wxPuts(_T("\n*** wxDateTime static methods test ***"));
3375 // some info about the current date
3376 int year
= wxDateTime::GetCurrentYear();
3377 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
3379 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3380 wxDateTime::GetNumberOfDays(year
));
3382 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3383 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
3384 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3385 wxDateTime::GetMonthName(month
).c_str(),
3386 wxDateTime::GetNumberOfDays(month
));
3389 // test time zones stuff
3390 static void TestTimeZones()
3392 wxPuts(_T("\n*** wxDateTime timezone test ***"));
3394 wxDateTime now
= wxDateTime::Now();
3396 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
3397 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
3398 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
3399 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
3400 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
3401 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
3403 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
3405 wxDateTime::Tm tm
= now
.GetTm();
3406 if ( wxDateTime(tm
) != now
)
3408 wxPrintf(_T("ERROR: got %s instead of %s\n"),
3409 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3413 // test some minimal support for the dates outside the standard range
3414 static void TestTimeRange()
3416 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
3418 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
3420 wxPrintf(_T("Unix epoch:\t%s\n"),
3421 wxDateTime(2440587.5).Format(fmt
).c_str());
3422 wxPrintf(_T("Feb 29, 0: \t%s\n"),
3423 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3424 wxPrintf(_T("JDN 0: \t%s\n"),
3425 wxDateTime(0.0).Format(fmt
).c_str());
3426 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
3427 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3428 wxPrintf(_T("May 29, 2099:\t%s\n"),
3429 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3432 // test DST calculations
3433 static void TestTimeDST()
3435 wxPuts(_T("\n*** wxDateTime DST test ***"));
3437 wxPrintf(_T("DST is%s in effect now.\n\n"),
3438 wxDateTime::Now().IsDST() ? wxEmptyString
: _T(" not"));
3440 for ( int year
= 1990; year
< 2005; year
++ )
3442 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
3444 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3445 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3451 #if TEST_INTERACTIVE
3453 static void TestDateTimeInteractive()
3455 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
3461 wxPrintf(_T("Enter a date: "));
3462 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3465 // kill the last '\n'
3466 buf
[wxStrlen(buf
) - 1] = 0;
3469 const wxChar
*p
= dt
.ParseDate(buf
);
3472 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
3478 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
3481 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
3482 dt
.Format(_T("%b %d, %Y")).c_str(),
3484 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3485 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3486 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3489 wxPuts(_T("\n*** done ***"));
3492 #endif // TEST_INTERACTIVE
3496 static void TestTimeMS()
3498 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
3500 wxDateTime dt1
= wxDateTime::Now(),
3501 dt2
= wxDateTime::UNow();
3503 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
3504 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3505 wxPrintf(_T("Dummy loop: "));
3506 for ( int i
= 0; i
< 6000; i
++ )
3508 //for ( int j = 0; j < 10; j++ )
3511 s
.Printf(_T("%g"), sqrt((float)i
));
3517 wxPuts(_T(", done"));
3520 dt2
= wxDateTime::UNow();
3521 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3523 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
3525 wxPuts(_T("\n*** done ***"));
3528 static void TestTimeHolidays()
3530 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
3532 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3533 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3534 dtEnd
= dtStart
.GetLastMonthDay();
3536 wxDateTimeArray hol
;
3537 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3539 const wxChar
*format
= _T("%d-%b-%Y (%a)");
3541 wxPrintf(_T("All holidays between %s and %s:\n"),
3542 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3544 size_t count
= hol
.GetCount();
3545 for ( size_t n
= 0; n
< count
; n
++ )
3547 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
3550 wxPuts(wxEmptyString
);
3553 static void TestTimeZoneBug()
3555 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
3557 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3558 for ( int i
= 0; i
< 31; i
++ )
3560 wxPrintf(_T("Date %s: week day %s.\n"),
3561 date
.Format(_T("%d-%m-%Y")).c_str(),
3562 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3564 date
+= wxDateSpan::Day();
3567 wxPuts(wxEmptyString
);
3570 static void TestTimeSpanFormat()
3572 wxPuts(_T("\n*** wxTimeSpan tests ***"));
3574 static const wxChar
*formats
[] =
3576 _T("(default) %H:%M:%S"),
3577 _T("%E weeks and %D days"),
3578 _T("%l milliseconds"),
3579 _T("(with ms) %H:%M:%S:%l"),
3580 _T("100%% of minutes is %M"), // test "%%"
3581 _T("%D days and %H hours"),
3582 _T("or also %S seconds"),
3585 wxTimeSpan
ts1(1, 2, 3, 4),
3587 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3589 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
3590 ts1
.Format(formats
[n
]).c_str(),
3591 ts2
.Format(formats
[n
]).c_str());
3594 wxPuts(wxEmptyString
);
3599 #endif // TEST_DATETIME
3601 // ----------------------------------------------------------------------------
3602 // wxTextInput/OutputStream
3603 // ----------------------------------------------------------------------------
3605 #ifdef TEST_TEXTSTREAM
3607 #include "wx/txtstrm.h"
3608 #include "wx/wfstream.h"
3610 static void TestTextInputStream()
3612 wxPuts(_T("\n*** wxTextInputStream test ***"));
3614 wxString filename
= _T("testdata.fc");
3615 wxFileInputStream
fsIn(filename
);
3618 wxPuts(_T("ERROR: couldn't open file."));
3622 wxTextInputStream
tis(fsIn
);
3627 const wxString s
= tis
.ReadLine();
3629 // line could be non empty if the last line of the file isn't
3630 // terminated with EOL
3631 if ( fsIn
.Eof() && s
.empty() )
3634 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
3639 #endif // TEST_TEXTSTREAM
3641 // ----------------------------------------------------------------------------
3643 // ----------------------------------------------------------------------------
3647 #include "wx/thread.h"
3649 static size_t gs_counter
= (size_t)-1;
3650 static wxCriticalSection gs_critsect
;
3651 static wxSemaphore gs_cond
;
3653 class MyJoinableThread
: public wxThread
3656 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3657 { m_n
= n
; Create(); }
3659 // thread execution starts here
3660 virtual ExitCode
Entry();
3666 wxThread::ExitCode
MyJoinableThread::Entry()
3668 unsigned long res
= 1;
3669 for ( size_t n
= 1; n
< m_n
; n
++ )
3673 // it's a loooong calculation :-)
3677 return (ExitCode
)res
;
3680 class MyDetachedThread
: public wxThread
3683 MyDetachedThread(size_t n
, wxChar ch
)
3687 m_cancelled
= false;
3692 // thread execution starts here
3693 virtual ExitCode
Entry();
3696 virtual void OnExit();
3699 size_t m_n
; // number of characters to write
3700 wxChar m_ch
; // character to write
3702 bool m_cancelled
; // false if we exit normally
3705 wxThread::ExitCode
MyDetachedThread::Entry()
3708 wxCriticalSectionLocker
lock(gs_critsect
);
3709 if ( gs_counter
== (size_t)-1 )
3715 for ( size_t n
= 0; n
< m_n
; n
++ )
3717 if ( TestDestroy() )
3727 wxThread::Sleep(100);
3733 void MyDetachedThread::OnExit()
3735 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
3737 wxCriticalSectionLocker
lock(gs_critsect
);
3738 if ( !--gs_counter
&& !m_cancelled
)
3742 static void TestDetachedThreads()
3744 wxPuts(_T("\n*** Testing detached threads ***"));
3746 static const size_t nThreads
= 3;
3747 MyDetachedThread
*threads
[nThreads
];
3749 for ( n
= 0; n
< nThreads
; n
++ )
3751 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3754 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3755 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3757 for ( n
= 0; n
< nThreads
; n
++ )
3762 // wait until all threads terminate
3765 wxPuts(wxEmptyString
);
3768 static void TestJoinableThreads()
3770 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
3772 // calc 10! in the background
3773 MyJoinableThread
thread(10);
3776 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
3777 (unsigned long)thread
.Wait());
3780 static void TestThreadSuspend()
3782 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
3784 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3788 // this is for this demo only, in a real life program we'd use another
3789 // condition variable which would be signaled from wxThread::Entry() to
3790 // tell us that the thread really started running - but here just wait a
3791 // bit and hope that it will be enough (the problem is, of course, that
3792 // the thread might still not run when we call Pause() which will result
3794 wxThread::Sleep(300);
3796 for ( size_t n
= 0; n
< 3; n
++ )
3800 wxPuts(_T("\nThread suspended"));
3803 // don't sleep but resume immediately the first time
3804 wxThread::Sleep(300);
3806 wxPuts(_T("Going to resume the thread"));
3811 wxPuts(_T("Waiting until it terminates now"));
3813 // wait until the thread terminates
3816 wxPuts(wxEmptyString
);
3819 static void TestThreadDelete()
3821 // As above, using Sleep() is only for testing here - we must use some
3822 // synchronisation object instead to ensure that the thread is still
3823 // running when we delete it - deleting a detached thread which already
3824 // terminated will lead to a crash!
3826 wxPuts(_T("\n*** Testing thread delete function ***"));
3828 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3832 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
3834 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3838 wxThread::Sleep(300);
3842 wxPuts(_T("\nDeleted a running thread."));
3844 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3848 wxThread::Sleep(300);
3854 wxPuts(_T("\nDeleted a sleeping thread."));
3856 MyJoinableThread
thread3(20);
3861 wxPuts(_T("\nDeleted a joinable thread."));
3863 MyJoinableThread
thread4(2);
3866 wxThread::Sleep(300);
3870 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
3872 wxPuts(wxEmptyString
);
3875 class MyWaitingThread
: public wxThread
3878 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
3881 m_condition
= condition
;
3886 virtual ExitCode
Entry()
3888 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
3893 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
3897 m_condition
->Wait();
3900 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
3908 wxCondition
*m_condition
;
3911 static void TestThreadConditions()
3914 wxCondition
condition(mutex
);
3916 // otherwise its difficult to understand which log messages pertain to
3918 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
3919 // condition.GetId(), gs_cond.GetId());
3921 // create and launch threads
3922 MyWaitingThread
*threads
[10];
3925 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3927 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
3930 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3935 // wait until all threads run
3936 wxPuts(_T("Main thread is waiting for the other threads to start"));
3939 size_t nRunning
= 0;
3940 while ( nRunning
< WXSIZEOF(threads
) )
3946 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
3950 wxPuts(_T("Main thread: all threads started up."));
3953 wxThread::Sleep(500);
3956 // now wake one of them up
3957 wxPrintf(_T("Main thread: about to signal the condition.\n"));
3962 wxThread::Sleep(200);
3964 // wake all the (remaining) threads up, so that they can exit
3965 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
3967 condition
.Broadcast();
3969 // give them time to terminate (dirty!)
3970 wxThread::Sleep(500);
3973 #include "wx/utils.h"
3975 class MyExecThread
: public wxThread
3978 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
3984 virtual ExitCode
Entry()
3986 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
3993 static void TestThreadExec()
3995 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
3997 MyExecThread
thread(_T("true"));
4000 wxPrintf(_T("Main program exit code: %ld.\n"),
4001 wxExecute(_T("false"), wxEXEC_SYNC
));
4003 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
4007 #include "wx/datetime.h"
4009 class MySemaphoreThread
: public wxThread
4012 MySemaphoreThread(int i
, wxSemaphore
*sem
)
4013 : wxThread(wxTHREAD_JOINABLE
),
4020 virtual ExitCode
Entry()
4022 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
4023 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
4027 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
4028 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
4032 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
4033 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
4045 WX_DEFINE_ARRAY_PTR(wxThread
*, ArrayThreads
);
4047 static void TestSemaphore()
4049 wxPuts(_T("*** Testing wxSemaphore class. ***"));
4051 static const int SEM_LIMIT
= 3;
4053 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
4054 ArrayThreads threads
;
4056 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
4058 threads
.Add(new MySemaphoreThread(i
, &sem
));
4059 threads
.Last()->Run();
4062 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
4069 #endif // TEST_THREADS
4071 // ----------------------------------------------------------------------------
4073 // ----------------------------------------------------------------------------
4075 #ifdef TEST_SNGLINST
4076 #include "wx/snglinst.h"
4077 #endif // TEST_SNGLINST
4079 int main(int argc
, char **argv
)
4081 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
4083 wxInitializer initializer
;
4086 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
4091 #ifdef TEST_SNGLINST
4092 wxSingleInstanceChecker checker
;
4093 if ( checker
.Create(_T(".wxconsole.lock")) )
4095 if ( checker
.IsAnotherRunning() )
4097 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4102 // wait some time to give time to launch another instance
4103 wxPrintf(_T("Press \"Enter\" to continue..."));
4106 else // failed to create
4108 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4110 #endif // TEST_SNGLINST
4113 TestCmdLineConvert();
4115 #if wxUSE_CMDLINE_PARSER
4116 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4118 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
4119 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4120 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
4121 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
4123 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
4124 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
4125 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
4126 wxCMD_LINE_VAL_NUMBER
},
4127 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
4128 wxCMD_LINE_VAL_DATE
},
4130 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
4131 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4137 wxChar
**wargv
= new wxChar
*[argc
+ 1];
4142 for (n
= 0; n
< argc
; n
++ )
4144 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
4145 wargv
[n
] = wxStrdup(warg
);
4152 #endif // wxUSE_UNICODE
4154 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4158 for ( int n
= 0; n
< argc
; n
++ )
4163 #endif // wxUSE_UNICODE
4165 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
4166 wxCMD_LINE_VAL_STRING
,
4167 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4169 switch ( parser
.Parse() )
4172 wxLogMessage(_T("Help was given, terminating."));
4176 ShowCmdLine(parser
);
4180 wxLogMessage(_T("Syntax error detected, aborting."));
4183 #endif // wxUSE_CMDLINE_PARSER
4185 #endif // TEST_CMDLINE
4195 #ifdef TEST_DLLLOADER
4197 TestDllListLoaded();
4198 #endif // TEST_DLLLOADER
4202 #endif // TEST_ENVIRON
4206 #endif // TEST_EXECUTE
4208 #ifdef TEST_FILECONF
4210 #endif // TEST_FILECONF
4214 #endif // TEST_LOCALE
4217 wxPuts(_T("*** Testing wxLog ***"));
4220 for ( size_t n
= 0; n
< 8000; n
++ )
4222 s
<< (wxChar
)(_T('A') + (n
% 26));
4225 wxLogWarning(_T("The length of the string is %lu"),
4226 (unsigned long)s
.length());
4229 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
4231 // this one shouldn't be truncated
4234 // but this one will because log functions use fixed size buffer
4235 // (note that it doesn't need '\n' at the end neither - will be added
4237 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
4246 #ifdef TEST_FILENAME
4247 TestFileNameConstruction();
4248 TestFileNameMakeRelative();
4249 TestFileNameMakeAbsolute();
4250 TestFileNameSplit();
4253 TestFileNameDirManip();
4254 TestFileNameComparison();
4255 TestFileNameOperations();
4256 #endif // TEST_FILENAME
4258 #ifdef TEST_FILETIME
4263 #endif // TEST_FILETIME
4266 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4267 if ( TestFtpConnect() )
4277 #if TEST_INTERACTIVE
4278 TestFtpInteractive();
4281 //else: connecting to the FTP server failed
4289 wxLog::AddTraceMask(_T("mime"));
4293 TestMimeAssociate();
4298 #ifdef TEST_INFO_FUNCTIONS
4303 #if TEST_INTERACTIVE
4307 #endif // TEST_INFO_FUNCTIONS
4309 #ifdef TEST_PATHLIST
4311 #endif // TEST_PATHLIST
4319 #endif // TEST_PRINTF
4326 #endif // TEST_REGCONF
4328 #if defined TEST_REGEX && TEST_INTERACTIVE
4329 TestRegExInteractive();
4330 #endif // defined TEST_REGEX && TEST_INTERACTIVE
4332 #ifdef TEST_REGISTRY
4334 TestRegistryAssociation();
4335 #endif // TEST_REGISTRY
4340 #endif // TEST_SOCKETS
4347 #endif // TEST_STREAMS
4349 #ifdef TEST_TEXTSTREAM
4350 TestTextInputStream();
4351 #endif // TEST_TEXTSTREAM
4354 int nCPUs
= wxThread::GetCPUCount();
4355 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
4357 wxThread::SetConcurrency(nCPUs
);
4359 TestJoinableThreads();
4362 TestJoinableThreads();
4363 TestDetachedThreads();
4364 TestThreadSuspend();
4366 TestThreadConditions();
4370 #endif // TEST_THREADS
4374 #endif // TEST_TIMER
4376 #ifdef TEST_DATETIME
4388 TestTimeArithmetics();
4390 TestTimeSpanFormat();
4396 #if TEST_INTERACTIVE
4397 TestDateTimeInteractive();
4399 #endif // TEST_DATETIME
4401 #ifdef TEST_SCOPEGUARD
4405 #ifdef TEST_STACKWALKER
4406 #if wxUSE_STACKWALKER
4407 TestStackWalk(argv
[0]);
4409 #endif // TEST_STACKWALKER
4411 #ifdef TEST_STDPATHS
4412 TestStandardPaths();
4416 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
4418 #endif // TEST_USLEEP
4423 #endif // TEST_VCARD
4427 #endif // TEST_VOLUME
4431 TestEncodingConverter();
4432 #endif // TEST_WCHAR
4435 TestZipStreamRead();
4436 TestZipFileSystem();