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)
79 #define TEST_TEXTSTREAM
82 // #define TEST_VCARD -- don't enable this (VZ)
83 // #define TEST_VOLUME --FIXME! (RN)
87 #define TEST_DLLLOADER
90 // some tests are interactive, define this to run them
91 #ifdef TEST_INTERACTIVE
92 #undef TEST_INTERACTIVE
94 #define TEST_INTERACTIVE 1
96 #define TEST_INTERACTIVE 0
99 // ============================================================================
101 // ============================================================================
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 #if defined(TEST_SOCKETS)
109 // replace TABs with \t and CRs with \n
110 static wxString
MakePrintable(const wxChar
*s
)
113 (void)str
.Replace(_T("\t"), _T("\\t"));
114 (void)str
.Replace(_T("\n"), _T("\\n"));
115 (void)str
.Replace(_T("\r"), _T("\\r"));
120 #endif // MakePrintable() is used
122 // ----------------------------------------------------------------------------
124 // ----------------------------------------------------------------------------
128 #include "wx/cmdline.h"
129 #include "wx/datetime.h"
131 #if wxUSE_CMDLINE_PARSER
133 static void ShowCmdLine(const wxCmdLineParser
& parser
)
135 wxString s
= _T("Input files: ");
137 size_t count
= parser
.GetParamCount();
138 for ( size_t param
= 0; param
< count
; param
++ )
140 s
<< parser
.GetParam(param
) << ' ';
144 << _T("Verbose:\t") << (parser
.Found(_T("v")) ? _T("yes") : _T("no")) << '\n'
145 << _T("Quiet:\t") << (parser
.Found(_T("q")) ? _T("yes") : _T("no")) << '\n';
150 if ( parser
.Found(_T("o"), &strVal
) )
151 s
<< _T("Output file:\t") << strVal
<< '\n';
152 if ( parser
.Found(_T("i"), &strVal
) )
153 s
<< _T("Input dir:\t") << strVal
<< '\n';
154 if ( parser
.Found(_T("s"), &lVal
) )
155 s
<< _T("Size:\t") << lVal
<< '\n';
156 if ( parser
.Found(_T("d"), &dt
) )
157 s
<< _T("Date:\t") << dt
.FormatISODate() << '\n';
158 if ( parser
.Found(_T("project_name"), &strVal
) )
159 s
<< _T("Project:\t") << strVal
<< '\n';
164 #endif // wxUSE_CMDLINE_PARSER
166 static void TestCmdLineConvert()
168 static const wxChar
*cmdlines
[] =
171 _T("-a \"-bstring 1\" -c\"string 2\" \"string 3\""),
172 _T("literal \\\" and \"\""),
175 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
177 const wxChar
*cmdline
= cmdlines
[n
];
178 wxPrintf(_T("Parsing: %s\n"), cmdline
);
179 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
181 size_t count
= args
.GetCount();
182 wxPrintf(_T("\targc = %u\n"), count
);
183 for ( size_t arg
= 0; arg
< count
; arg
++ )
185 wxPrintf(_T("\targv[%u] = %s\n"), arg
, args
[arg
].c_str());
190 #endif // TEST_CMDLINE
192 // ----------------------------------------------------------------------------
194 // ----------------------------------------------------------------------------
201 static const wxChar
*ROOTDIR
= _T("/");
202 static const wxChar
*TESTDIR
= _T("/usr/local/share");
203 #elif defined(__WXMSW__)
204 static const wxChar
*ROOTDIR
= _T("c:\\");
205 static const wxChar
*TESTDIR
= _T("d:\\");
207 #error "don't know where the root directory is"
210 static void TestDirEnumHelper(wxDir
& dir
,
211 int flags
= wxDIR_DEFAULT
,
212 const wxString
& filespec
= wxEmptyString
)
216 if ( !dir
.IsOpened() )
219 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
222 wxPrintf(_T("\t%s\n"), filename
.c_str());
224 cont
= dir
.GetNext(&filename
);
227 wxPuts(wxEmptyString
);
230 static void TestDirEnum()
232 wxPuts(_T("*** Testing wxDir::GetFirst/GetNext ***"));
234 wxString cwd
= wxGetCwd();
235 if ( !wxDir::Exists(cwd
) )
237 wxPrintf(_T("ERROR: current directory '%s' doesn't exist?\n"), cwd
.c_str());
242 if ( !dir
.IsOpened() )
244 wxPrintf(_T("ERROR: failed to open current directory '%s'.\n"), cwd
.c_str());
248 wxPuts(_T("Enumerating everything in current directory:"));
249 TestDirEnumHelper(dir
);
251 wxPuts(_T("Enumerating really everything in current directory:"));
252 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
254 wxPuts(_T("Enumerating object files in current directory:"));
255 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, _T("*.o*"));
257 wxPuts(_T("Enumerating directories in current directory:"));
258 TestDirEnumHelper(dir
, wxDIR_DIRS
);
260 wxPuts(_T("Enumerating files in current directory:"));
261 TestDirEnumHelper(dir
, wxDIR_FILES
);
263 wxPuts(_T("Enumerating files including hidden in current directory:"));
264 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
268 wxPuts(_T("Enumerating everything in root directory:"));
269 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
271 wxPuts(_T("Enumerating directories in root directory:"));
272 TestDirEnumHelper(dir
, wxDIR_DIRS
);
274 wxPuts(_T("Enumerating files in root directory:"));
275 TestDirEnumHelper(dir
, wxDIR_FILES
);
277 wxPuts(_T("Enumerating files including hidden in root directory:"));
278 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
280 wxPuts(_T("Enumerating files in non existing directory:"));
281 wxDir
dirNo(_T("nosuchdir"));
282 TestDirEnumHelper(dirNo
);
285 class DirPrintTraverser
: public wxDirTraverser
288 virtual wxDirTraverseResult
OnFile(const wxString
& WXUNUSED(filename
))
290 return wxDIR_CONTINUE
;
293 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
295 wxString path
, name
, ext
;
296 wxSplitPath(dirname
, &path
, &name
, &ext
);
299 name
<< _T('.') << ext
;
302 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
304 if ( wxIsPathSeparator(*p
) )
308 wxPrintf(_T("%s%s\n"), indent
.c_str(), name
.c_str());
310 return wxDIR_CONTINUE
;
314 static void TestDirTraverse()
316 wxPuts(_T("*** Testing wxDir::Traverse() ***"));
320 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
321 wxPrintf(_T("There are %u files under '%s'\n"), n
, TESTDIR
);
324 wxPrintf(_T("First one is '%s'\n"), files
[0u].c_str());
325 wxPrintf(_T(" last one is '%s'\n"), files
[n
- 1].c_str());
328 // enum again with custom traverser
329 wxPuts(_T("Now enumerating directories:"));
331 DirPrintTraverser traverser
;
332 dir
.Traverse(traverser
, wxEmptyString
, wxDIR_DIRS
| wxDIR_HIDDEN
);
335 static void TestDirExists()
337 wxPuts(_T("*** Testing wxDir::Exists() ***"));
339 static const wxChar
*dirnames
[] =
342 #if defined(__WXMSW__)
345 _T("\\\\share\\file"),
349 _T("c:\\autoexec.bat"),
350 #elif defined(__UNIX__)
359 for ( size_t n
= 0; n
< WXSIZEOF(dirnames
); n
++ )
361 wxPrintf(_T("%-40s: %s\n"),
363 wxDir::Exists(dirnames
[n
]) ? _T("exists")
364 : _T("doesn't exist"));
370 // ----------------------------------------------------------------------------
372 // ----------------------------------------------------------------------------
374 #ifdef TEST_DLLLOADER
376 #include "wx/dynlib.h"
378 static void TestDllLoad()
380 #if defined(__WXMSW__)
381 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
382 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
383 #elif defined(__UNIX__)
384 // weird: using just libc.so does *not* work!
385 static const wxChar
*LIB_NAME
= _T("/lib/libc.so.6");
386 static const wxChar
*FUNC_NAME
= _T("strlen");
388 #error "don't know how to test wxDllLoader on this platform"
391 wxPuts(_T("*** testing basic wxDynamicLibrary functions ***\n"));
393 wxDynamicLibrary
lib(LIB_NAME
);
394 if ( !lib
.IsLoaded() )
396 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
400 typedef int (*wxStrlenType
)(const char *);
401 wxStrlenType pfnStrlen
= (wxStrlenType
)lib
.GetSymbol(FUNC_NAME
);
404 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
405 FUNC_NAME
, LIB_NAME
);
409 wxPrintf(_T("Calling %s dynamically loaded from %s "),
410 FUNC_NAME
, LIB_NAME
);
412 if ( pfnStrlen("foo") != 3 )
414 wxPrintf(_T("ERROR: loaded function is not wxStrlen()!\n"));
418 wxPuts(_T("... ok"));
424 #if defined(__WXMSW__) || defined(__UNIX__)
426 static void TestDllListLoaded()
428 wxPuts(_T("*** testing wxDynamicLibrary::ListLoaded() ***\n"));
430 puts("\nLoaded modules:");
431 wxDynamicLibraryDetailsArray dlls
= wxDynamicLibrary::ListLoaded();
432 const size_t count
= dlls
.GetCount();
433 for ( size_t n
= 0; n
< count
; ++n
)
435 const wxDynamicLibraryDetails
& details
= dlls
[n
];
436 printf("%-45s", details
.GetPath().c_str());
440 if ( details
.GetAddress(&addr
, &len
) )
442 printf(" %08lx:%08lx",
443 (unsigned long)addr
, (unsigned long)((char *)addr
+ len
));
446 printf(" %s\n", details
.GetVersion().c_str());
452 #endif // TEST_DLLLOADER
454 // ----------------------------------------------------------------------------
456 // ----------------------------------------------------------------------------
460 #include "wx/utils.h"
462 static wxString
MyGetEnv(const wxString
& var
)
465 if ( !wxGetEnv(var
, &val
) )
468 val
= wxString(_T('\'')) + val
+ _T('\'');
473 static void TestEnvironment()
475 const wxChar
*var
= _T("wxTestVar");
477 wxPuts(_T("*** testing environment access functions ***"));
479 wxPrintf(_T("Initially getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
480 wxSetEnv(var
, _T("value for wxTestVar"));
481 wxPrintf(_T("After wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
482 wxSetEnv(var
, _T("another value"));
483 wxPrintf(_T("After 2nd wxSetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
485 wxPrintf(_T("After wxUnsetEnv: getenv(%s) = %s\n"), var
, MyGetEnv(var
).c_str());
486 wxPrintf(_T("PATH = %s\n"), MyGetEnv(_T("PATH")).c_str());
489 #endif // TEST_ENVIRON
491 // ----------------------------------------------------------------------------
493 // ----------------------------------------------------------------------------
497 #include "wx/utils.h"
499 static void TestExecute()
501 wxPuts(_T("*** testing wxExecute ***"));
504 #define COMMAND "cat -n ../../Makefile" // "echo hi"
505 #define SHELL_COMMAND "echo hi from shell"
506 #define REDIRECT_COMMAND COMMAND // "date"
507 #elif defined(__WXMSW__)
508 #define COMMAND "command.com /c echo hi"
509 #define SHELL_COMMAND "echo hi"
510 #define REDIRECT_COMMAND COMMAND
512 #error "no command to exec"
515 wxPrintf(_T("Testing wxShell: "));
517 if ( wxShell(_T(SHELL_COMMAND
)) )
520 wxPuts(_T("ERROR."));
522 wxPrintf(_T("Testing wxExecute: "));
524 if ( wxExecute(_T(COMMAND
), true /* sync */) == 0 )
527 wxPuts(_T("ERROR."));
529 #if 0 // no, it doesn't work (yet?)
530 wxPrintf(_T("Testing async wxExecute: "));
532 if ( wxExecute(COMMAND
) != 0 )
533 wxPuts(_T("Ok (command launched)."));
535 wxPuts(_T("ERROR."));
538 wxPrintf(_T("Testing wxExecute with redirection:\n"));
539 wxArrayString output
;
540 if ( wxExecute(_T(REDIRECT_COMMAND
), output
) != 0 )
542 wxPuts(_T("ERROR."));
546 size_t count
= output
.GetCount();
547 for ( size_t n
= 0; n
< count
; n
++ )
549 wxPrintf(_T("\t%s\n"), output
[n
].c_str());
556 #endif // TEST_EXECUTE
558 // ----------------------------------------------------------------------------
560 // ----------------------------------------------------------------------------
565 #include "wx/ffile.h"
566 #include "wx/textfile.h"
568 static void TestFileRead()
570 wxPuts(_T("*** wxFile read test ***"));
572 wxFile
file(_T("testdata.fc"));
573 if ( file
.IsOpened() )
575 wxPrintf(_T("File length: %lu\n"), file
.Length());
577 wxPuts(_T("File dump:\n----------"));
579 static const size_t len
= 1024;
583 size_t nRead
= file
.Read(buf
, len
);
584 if ( nRead
== (size_t)wxInvalidOffset
)
586 wxPrintf(_T("Failed to read the file."));
590 fwrite(buf
, nRead
, 1, stdout
);
596 wxPuts(_T("----------"));
600 wxPrintf(_T("ERROR: can't open test file.\n"));
603 wxPuts(wxEmptyString
);
606 static void TestTextFileRead()
608 wxPuts(_T("*** wxTextFile read test ***"));
610 wxTextFile
file(_T("testdata.fc"));
613 wxPrintf(_T("Number of lines: %u\n"), file
.GetLineCount());
614 wxPrintf(_T("Last line: '%s'\n"), file
.GetLastLine().c_str());
618 wxPuts(_T("\nDumping the entire file:"));
619 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
621 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
623 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
625 wxPuts(_T("\nAnd now backwards:"));
626 for ( s
= file
.GetLastLine();
627 file
.GetCurrentLine() != 0;
628 s
= file
.GetPrevLine() )
630 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
632 wxPrintf(_T("%6u: %s\n"), file
.GetCurrentLine() + 1, s
.c_str());
636 wxPrintf(_T("ERROR: can't open '%s'\n"), file
.GetName());
639 wxPuts(wxEmptyString
);
642 static void TestFileCopy()
644 wxPuts(_T("*** Testing wxCopyFile ***"));
646 static const wxChar
*filename1
= _T("testdata.fc");
647 static const wxChar
*filename2
= _T("test2");
648 if ( !wxCopyFile(filename1
, filename2
) )
650 wxPuts(_T("ERROR: failed to copy file"));
654 wxFFile
f1(filename1
, _T("rb")),
655 f2(filename2
, _T("rb"));
657 if ( !f1
.IsOpened() || !f2
.IsOpened() )
659 wxPuts(_T("ERROR: failed to open file(s)"));
664 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
666 wxPuts(_T("ERROR: failed to read file(s)"));
670 if ( (s1
.length() != s2
.length()) ||
671 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
673 wxPuts(_T("ERROR: copy error!"));
677 wxPuts(_T("File was copied ok."));
683 if ( !wxRemoveFile(filename2
) )
685 wxPuts(_T("ERROR: failed to remove the file"));
688 wxPuts(wxEmptyString
);
693 // ----------------------------------------------------------------------------
695 // ----------------------------------------------------------------------------
699 #include "wx/confbase.h"
700 #include "wx/fileconf.h"
702 static const struct FileConfTestData
704 const wxChar
*name
; // value name
705 const wxChar
*value
; // the value from the file
708 { _T("value1"), _T("one") },
709 { _T("value2"), _T("two") },
710 { _T("novalue"), _T("default") },
713 static void TestFileConfRead()
715 wxPuts(_T("*** testing wxFileConfig loading/reading ***"));
717 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
718 _T("testdata.fc"), wxEmptyString
,
719 wxCONFIG_USE_RELATIVE_PATH
);
721 // test simple reading
722 wxPuts(_T("\nReading config file:"));
723 wxString
defValue(_T("default")), value
;
724 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
726 const FileConfTestData
& data
= fcTestData
[n
];
727 value
= fileconf
.Read(data
.name
, defValue
);
728 wxPrintf(_T("\t%s = %s "), data
.name
, value
.c_str());
729 if ( value
== data
.value
)
735 wxPrintf(_T("(ERROR: should be %s)\n"), data
.value
);
739 // test enumerating the entries
740 wxPuts(_T("\nEnumerating all root entries:"));
743 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
746 wxPrintf(_T("\t%s = %s\n"),
748 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
750 cont
= fileconf
.GetNextEntry(name
, dummy
);
753 static const wxChar
*testEntry
= _T("TestEntry");
754 wxPrintf(_T("\nTesting deletion of newly created \"Test\" entry: "));
755 fileconf
.Write(testEntry
, _T("A value"));
756 fileconf
.DeleteEntry(testEntry
);
757 wxPrintf(fileconf
.HasEntry(testEntry
) ? _T("ERROR\n") : _T("ok\n"));
760 #endif // TEST_FILECONF
762 // ----------------------------------------------------------------------------
764 // ----------------------------------------------------------------------------
768 #include "wx/filename.h"
771 static void DumpFileName(const wxChar
*desc
, const wxFileName
& fn
)
775 wxString full
= fn
.GetFullPath();
777 wxString vol
, path
, name
, ext
;
778 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
780 wxPrintf(_T("'%s'-> vol '%s', path '%s', name '%s', ext '%s'\n"),
781 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
783 wxFileName::SplitPath(full
, &path
, &name
, &ext
);
784 wxPrintf(_T("or\t\t-> path '%s', name '%s', ext '%s'\n"),
785 path
.c_str(), name
.c_str(), ext
.c_str());
787 wxPrintf(_T("path is also:\t'%s'\n"), fn
.GetPath().c_str());
788 wxPrintf(_T("with volume: \t'%s'\n"),
789 fn
.GetPath(wxPATH_GET_VOLUME
).c_str());
790 wxPrintf(_T("with separator:\t'%s'\n"),
791 fn
.GetPath(wxPATH_GET_SEPARATOR
).c_str());
792 wxPrintf(_T("with both: \t'%s'\n"),
793 fn
.GetPath(wxPATH_GET_SEPARATOR
| wxPATH_GET_VOLUME
).c_str());
795 wxPuts(_T("The directories in the path are:"));
796 wxArrayString dirs
= fn
.GetDirs();
797 size_t count
= dirs
.GetCount();
798 for ( size_t n
= 0; n
< count
; n
++ )
800 wxPrintf(_T("\t%u: %s\n"), n
, dirs
[n
].c_str());
805 static void TestFileNameTemp()
807 wxPuts(_T("*** testing wxFileName temp file creation ***"));
809 static const wxChar
*tmpprefixes
[] =
817 _T("/tmp/foo/bar"), // this one must be an error
821 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
823 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
826 // "error" is not in upper case because it may be ok
827 wxPrintf(_T("Prefix '%s'\t-> error\n"), tmpprefixes
[n
]);
831 wxPrintf(_T("Prefix '%s'\t-> temp file '%s'\n"),
832 tmpprefixes
[n
], path
.c_str());
834 if ( !wxRemoveFile(path
) )
836 wxLogWarning(_T("Failed to remove temp file '%s'"),
843 static void TestFileNameMakeRelative()
845 wxPuts(_T("*** testing wxFileName::MakeRelativeTo() ***"));
847 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
849 const FileNameInfo
& fni
= filenames
[n
];
851 wxFileName
fn(fni
.fullname
, fni
.format
);
853 // choose the base dir of the same format
855 switch ( fni
.format
)
858 base
= _T("/usr/bin/");
867 // TODO: I don't know how this is supposed to work there
870 case wxPATH_NATIVE
: // make gcc happy
872 wxFAIL_MSG( _T("unexpected path format") );
875 wxPrintf(_T("'%s' relative to '%s': "),
876 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
878 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
880 wxPuts(_T("unchanged"));
884 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
889 static void TestFileNameMakeAbsolute()
891 wxPuts(_T("*** testing wxFileName::MakeAbsolute() ***"));
893 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
895 const FileNameInfo
& fni
= filenames
[n
];
896 wxFileName
fn(fni
.fullname
, fni
.format
);
898 wxPrintf(_T("'%s' absolutized: "),
899 fn
.GetFullPath(fni
.format
).c_str());
901 wxPrintf(_T("'%s'\n"), fn
.GetFullPath(fni
.format
).c_str());
904 wxPuts(wxEmptyString
);
907 static void TestFileNameDirManip()
909 // TODO: test AppendDir(), RemoveDir(), ...
912 static void TestFileNameComparison()
917 static void TestFileNameOperations()
922 static void TestFileNameCwd()
927 #endif // TEST_FILENAME
929 // ----------------------------------------------------------------------------
930 // wxFileName time functions
931 // ----------------------------------------------------------------------------
935 #include <wx/filename.h>
936 #include <wx/datetime.h>
938 static void TestFileGetTimes()
940 wxFileName
fn(_T("testdata.fc"));
942 wxDateTime dtAccess
, dtMod
, dtCreate
;
943 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtCreate
) )
945 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
949 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
951 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
952 wxPrintf(_T("Creation: \t%s\n"), dtCreate
.Format(fmt
).c_str());
953 wxPrintf(_T("Last read: \t%s\n"), dtAccess
.Format(fmt
).c_str());
954 wxPrintf(_T("Last write: \t%s\n"), dtMod
.Format(fmt
).c_str());
959 static void TestFileSetTimes()
961 wxFileName
fn(_T("testdata.fc"));
965 wxPrintf(_T("ERROR: Touch() failed.\n"));
970 #endif // TEST_FILETIME
972 // ----------------------------------------------------------------------------
974 // ----------------------------------------------------------------------------
979 #include "wx/utils.h" // for wxSetEnv
981 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
983 // find the name of the language from its value
984 static const wxChar
*GetLangName(int lang
)
986 static const wxChar
*languageNames
[] =
996 _T("ARABIC_ALGERIA"),
997 _T("ARABIC_BAHRAIN"),
1000 _T("ARABIC_JORDAN"),
1001 _T("ARABIC_KUWAIT"),
1002 _T("ARABIC_LEBANON"),
1004 _T("ARABIC_MOROCCO"),
1007 _T("ARABIC_SAUDI_ARABIA"),
1010 _T("ARABIC_TUNISIA"),
1017 _T("AZERI_CYRILLIC"),
1032 _T("CHINESE_SIMPLIFIED"),
1033 _T("CHINESE_TRADITIONAL"),
1034 _T("CHINESE_HONGKONG"),
1035 _T("CHINESE_MACAU"),
1036 _T("CHINESE_SINGAPORE"),
1037 _T("CHINESE_TAIWAN"),
1043 _T("DUTCH_BELGIAN"),
1047 _T("ENGLISH_AUSTRALIA"),
1048 _T("ENGLISH_BELIZE"),
1049 _T("ENGLISH_BOTSWANA"),
1050 _T("ENGLISH_CANADA"),
1051 _T("ENGLISH_CARIBBEAN"),
1052 _T("ENGLISH_DENMARK"),
1054 _T("ENGLISH_JAMAICA"),
1055 _T("ENGLISH_NEW_ZEALAND"),
1056 _T("ENGLISH_PHILIPPINES"),
1057 _T("ENGLISH_SOUTH_AFRICA"),
1058 _T("ENGLISH_TRINIDAD"),
1059 _T("ENGLISH_ZIMBABWE"),
1067 _T("FRENCH_BELGIAN"),
1068 _T("FRENCH_CANADIAN"),
1069 _T("FRENCH_LUXEMBOURG"),
1070 _T("FRENCH_MONACO"),
1076 _T("GERMAN_AUSTRIAN"),
1077 _T("GERMAN_BELGIUM"),
1078 _T("GERMAN_LIECHTENSTEIN"),
1079 _T("GERMAN_LUXEMBOURG"),
1097 _T("ITALIAN_SWISS"),
1102 _T("KASHMIRI_INDIA"),
1120 _T("MALAY_BRUNEI_DARUSSALAM"),
1121 _T("MALAY_MALAYSIA"),
1131 _T("NORWEGIAN_BOKMAL"),
1132 _T("NORWEGIAN_NYNORSK"),
1139 _T("PORTUGUESE_BRAZILIAN"),
1142 _T("RHAETO_ROMANCE"),
1145 _T("RUSSIAN_UKRAINE"),
1151 _T("SERBIAN_CYRILLIC"),
1152 _T("SERBIAN_LATIN"),
1153 _T("SERBO_CROATIAN"),
1164 _T("SPANISH_ARGENTINA"),
1165 _T("SPANISH_BOLIVIA"),
1166 _T("SPANISH_CHILE"),
1167 _T("SPANISH_COLOMBIA"),
1168 _T("SPANISH_COSTA_RICA"),
1169 _T("SPANISH_DOMINICAN_REPUBLIC"),
1170 _T("SPANISH_ECUADOR"),
1171 _T("SPANISH_EL_SALVADOR"),
1172 _T("SPANISH_GUATEMALA"),
1173 _T("SPANISH_HONDURAS"),
1174 _T("SPANISH_MEXICAN"),
1175 _T("SPANISH_MODERN"),
1176 _T("SPANISH_NICARAGUA"),
1177 _T("SPANISH_PANAMA"),
1178 _T("SPANISH_PARAGUAY"),
1180 _T("SPANISH_PUERTO_RICO"),
1181 _T("SPANISH_URUGUAY"),
1183 _T("SPANISH_VENEZUELA"),
1187 _T("SWEDISH_FINLAND"),
1205 _T("URDU_PAKISTAN"),
1207 _T("UZBEK_CYRILLIC"),
1220 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1221 return languageNames
[lang
];
1223 return _T("INVALID");
1226 static void TestDefaultLang()
1228 wxPuts(_T("*** Testing wxLocale::GetSystemLanguage ***"));
1230 static const wxChar
*langStrings
[] =
1232 NULL
, // system default
1239 _T("de_DE.iso88591"),
1241 _T("?"), // invalid lang spec
1242 _T("klingonese"), // I bet on some systems it does exist...
1245 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1246 wxLocale::GetSystemEncodingName().c_str(),
1247 wxLocale::GetSystemEncoding());
1249 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1251 const wxChar
*langStr
= langStrings
[n
];
1254 // FIXME: this doesn't do anything at all under Windows, we need
1255 // to create a new wxLocale!
1256 wxSetEnv(_T("LC_ALL"), langStr
);
1259 int lang
= gs_localeDefault
.GetSystemLanguage();
1260 wxPrintf(_T("Locale for '%s' is %s.\n"),
1261 langStr
? langStr
: _T("system default"), GetLangName(lang
));
1265 #endif // TEST_LOCALE
1267 // ----------------------------------------------------------------------------
1269 // ----------------------------------------------------------------------------
1273 #include "wx/mimetype.h"
1275 static void TestMimeEnum()
1277 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1279 wxArrayString mimetypes
;
1281 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1283 wxPrintf(_T("*** All %u known filetypes: ***\n"), count
);
1288 for ( size_t n
= 0; n
< count
; n
++ )
1290 wxFileType
*filetype
=
1291 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1294 wxPrintf(_T("nothing known about the filetype '%s'!\n"),
1295 mimetypes
[n
].c_str());
1299 filetype
->GetDescription(&desc
);
1300 filetype
->GetExtensions(exts
);
1302 filetype
->GetIcon(NULL
);
1305 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1308 extsAll
<< _T(", ");
1312 wxPrintf(_T("\t%s: %s (%s)\n"),
1313 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1316 wxPuts(wxEmptyString
);
1319 static void TestMimeOverride()
1321 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1323 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1324 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1326 if ( wxFile::Exists(mailcap
) )
1327 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1329 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1331 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1334 if ( wxFile::Exists(mimetypes
) )
1335 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1337 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1339 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1342 wxPuts(wxEmptyString
);
1345 static void TestMimeFilename()
1347 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1349 static const wxChar
*filenames
[] =
1357 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1359 const wxString fname
= filenames
[n
];
1360 wxString ext
= fname
.AfterLast(_T('.'));
1361 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1364 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1369 if ( !ft
->GetDescription(&desc
) )
1370 desc
= _T("<no description>");
1373 if ( !ft
->GetOpenCommand(&cmd
,
1374 wxFileType::MessageParameters(fname
, wxEmptyString
)) )
1375 cmd
= _T("<no command available>");
1377 cmd
= wxString(_T('"')) + cmd
+ _T('"');
1379 wxPrintf(_T("To open %s (%s) do %s.\n"),
1380 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1386 wxPuts(wxEmptyString
);
1389 static void TestMimeAssociate()
1391 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1393 wxFileTypeInfo
ftInfo(
1394 _T("application/x-xyz"),
1395 _T("xyzview '%s'"), // open cmd
1396 _T(""), // print cmd
1397 _T("XYZ File"), // description
1398 _T(".xyz"), // extensions
1399 NULL
// end of extensions
1401 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1403 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1406 wxPuts(_T("ERROR: failed to create association!"));
1410 // TODO: read it back
1414 wxPuts(wxEmptyString
);
1419 // ----------------------------------------------------------------------------
1420 // misc information functions
1421 // ----------------------------------------------------------------------------
1423 #ifdef TEST_INFO_FUNCTIONS
1425 #include "wx/utils.h"
1427 static void TestDiskInfo()
1429 wxPuts(_T("*** Testing wxGetDiskSpace() ***"));
1433 wxChar pathname
[128];
1434 wxPrintf(_T("\nEnter a directory name: "));
1435 if ( !wxFgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1438 // kill the last '\n'
1439 pathname
[wxStrlen(pathname
) - 1] = 0;
1441 wxLongLong total
, free
;
1442 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1444 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1448 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1449 (total
/ 1024).ToString().c_str(),
1450 (free
/ 1024).ToString().c_str(),
1456 static void TestOsInfo()
1458 wxPuts(_T("*** Testing OS info functions ***\n"));
1461 wxGetOsVersion(&major
, &minor
);
1462 wxPrintf(_T("Running under: %s, version %d.%d\n"),
1463 wxGetOsDescription().c_str(), major
, minor
);
1465 wxPrintf(_T("%ld free bytes of memory left.\n"), wxGetFreeMemory());
1467 wxPrintf(_T("Host name is %s (%s).\n"),
1468 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1470 wxPuts(wxEmptyString
);
1473 static void TestUserInfo()
1475 wxPuts(_T("*** Testing user info functions ***\n"));
1477 wxPrintf(_T("User id is:\t%s\n"), wxGetUserId().c_str());
1478 wxPrintf(_T("User name is:\t%s\n"), wxGetUserName().c_str());
1479 wxPrintf(_T("Home dir is:\t%s\n"), wxGetHomeDir().c_str());
1480 wxPrintf(_T("Email address:\t%s\n"), wxGetEmailAddress().c_str());
1482 wxPuts(wxEmptyString
);
1485 #endif // TEST_INFO_FUNCTIONS
1487 // ----------------------------------------------------------------------------
1489 // ----------------------------------------------------------------------------
1491 #ifdef TEST_PATHLIST
1494 #define CMD_IN_PATH _T("ls")
1496 #define CMD_IN_PATH _T("command.com")
1499 static void TestPathList()
1501 wxPuts(_T("*** Testing wxPathList ***\n"));
1503 wxPathList pathlist
;
1504 pathlist
.AddEnvList(_T("PATH"));
1505 wxString path
= pathlist
.FindValidPath(CMD_IN_PATH
);
1508 wxPrintf(_T("ERROR: command not found in the path.\n"));
1512 wxPrintf(_T("Command found in the path as '%s'.\n"), path
.c_str());
1516 #endif // TEST_PATHLIST
1518 // ----------------------------------------------------------------------------
1519 // regular expressions
1520 // ----------------------------------------------------------------------------
1524 #include "wx/regex.h"
1526 static void TestRegExInteractive()
1528 wxPuts(_T("*** Testing RE interactively ***"));
1532 wxChar pattern
[128];
1533 wxPrintf(_T("\nEnter a pattern: "));
1534 if ( !wxFgets(pattern
, WXSIZEOF(pattern
), stdin
) )
1537 // kill the last '\n'
1538 pattern
[wxStrlen(pattern
) - 1] = 0;
1541 if ( !re
.Compile(pattern
) )
1549 wxPrintf(_T("Enter text to match: "));
1550 if ( !wxFgets(text
, WXSIZEOF(text
), stdin
) )
1553 // kill the last '\n'
1554 text
[wxStrlen(text
) - 1] = 0;
1556 if ( !re
.Matches(text
) )
1558 wxPrintf(_T("No match.\n"));
1562 wxPrintf(_T("Pattern matches at '%s'\n"), re
.GetMatch(text
).c_str());
1565 for ( size_t n
= 1; ; n
++ )
1567 if ( !re
.GetMatch(&start
, &len
, n
) )
1572 wxPrintf(_T("Subexpr %u matched '%s'\n"),
1573 n
, wxString(text
+ start
, len
).c_str());
1580 #endif // TEST_REGEX
1582 // ----------------------------------------------------------------------------
1584 // ----------------------------------------------------------------------------
1594 static void TestDbOpen()
1602 // ----------------------------------------------------------------------------
1604 // ----------------------------------------------------------------------------
1607 NB: this stuff was taken from the glibc test suite and modified to build
1608 in wxWidgets: if I read the copyright below properly, this shouldn't
1614 #ifdef wxTEST_PRINTF
1615 // use our functions from wxchar.cpp
1619 // NB: do _not_ use ATTRIBUTE_PRINTF here, we have some invalid formats
1620 // in the tests below
1621 int wxPrintf( const wxChar
*format
, ... );
1622 int wxSprintf( wxChar
*str
, const wxChar
*format
, ... );
1625 #include "wx/longlong.h"
1629 static void rfg1 (void);
1630 static void rfg2 (void);
1634 fmtchk (const wxChar
*fmt
)
1636 (void) wxPrintf(_T("%s:\t`"), fmt
);
1637 (void) wxPrintf(fmt
, 0x12);
1638 (void) wxPrintf(_T("'\n"));
1642 fmtst1chk (const wxChar
*fmt
)
1644 (void) wxPrintf(_T("%s:\t`"), fmt
);
1645 (void) wxPrintf(fmt
, 4, 0x12);
1646 (void) wxPrintf(_T("'\n"));
1650 fmtst2chk (const wxChar
*fmt
)
1652 (void) wxPrintf(_T("%s:\t`"), fmt
);
1653 (void) wxPrintf(fmt
, 4, 4, 0x12);
1654 (void) wxPrintf(_T("'\n"));
1657 /* This page is covered by the following copyright: */
1659 /* (C) Copyright C E Chew
1661 * Feel free to copy, use and distribute this software provided:
1663 * 1. you do not pretend that you wrote it
1664 * 2. you leave this copyright notice intact.
1668 * Extracted from exercise.c for glibc-1.05 bug report by Bruce Evans.
1675 /* Formatted Output Test
1677 * This exercises the output formatting code.
1680 wxChar
*PointerNull
= NULL
;
1687 wxChar
*prefix
= buf
;
1690 wxPuts(_T("\nFormatted output test"));
1691 wxPrintf(_T("prefix 6d 6o 6x 6X 6u\n"));
1692 wxStrcpy(prefix
, _T("%"));
1693 for (i
= 0; i
< 2; i
++) {
1694 for (j
= 0; j
< 2; j
++) {
1695 for (k
= 0; k
< 2; k
++) {
1696 for (l
= 0; l
< 2; l
++) {
1697 wxStrcpy(prefix
, _T("%"));
1698 if (i
== 0) wxStrcat(prefix
, _T("-"));
1699 if (j
== 0) wxStrcat(prefix
, _T("+"));
1700 if (k
== 0) wxStrcat(prefix
, _T("#"));
1701 if (l
== 0) wxStrcat(prefix
, _T("0"));
1702 wxPrintf(_T("%5s |"), prefix
);
1703 wxStrcpy(tp
, prefix
);
1704 wxStrcat(tp
, _T("6d |"));
1706 wxStrcpy(tp
, prefix
);
1707 wxStrcat(tp
, _T("6o |"));
1709 wxStrcpy(tp
, prefix
);
1710 wxStrcat(tp
, _T("6x |"));
1712 wxStrcpy(tp
, prefix
);
1713 wxStrcat(tp
, _T("6X |"));
1715 wxStrcpy(tp
, prefix
);
1716 wxStrcat(tp
, _T("6u |"));
1723 wxPrintf(_T("%10s\n"), PointerNull
);
1724 wxPrintf(_T("%-10s\n"), PointerNull
);
1727 static void TestPrintf()
1729 static wxChar shortstr
[] = _T("Hi, Z.");
1730 static wxChar longstr
[] = _T("Good morning, Doctor Chandra. This is Hal. \
1731 I am ready for my first lesson today.");
1733 wxString test_format
;
1737 fmtchk(_T("%4.4x"));
1738 fmtchk(_T("%04.4x"));
1739 fmtchk(_T("%4.3x"));
1740 fmtchk(_T("%04.3x"));
1742 fmtst1chk(_T("%.*x"));
1743 fmtst1chk(_T("%0*x"));
1744 fmtst2chk(_T("%*.*x"));
1745 fmtst2chk(_T("%0*.*x"));
1747 wxString bad_format
= _T("bad format:\t\"%b\"\n");
1748 wxPrintf(bad_format
.c_str());
1749 wxPrintf(_T("nil pointer (padded):\t\"%10p\"\n"), (void *) NULL
);
1751 wxPrintf(_T("decimal negative:\t\"%d\"\n"), -2345);
1752 wxPrintf(_T("octal negative:\t\"%o\"\n"), -2345);
1753 wxPrintf(_T("hex negative:\t\"%x\"\n"), -2345);
1754 wxPrintf(_T("long decimal number:\t\"%ld\"\n"), -123456L);
1755 wxPrintf(_T("long octal negative:\t\"%lo\"\n"), -2345L);
1756 wxPrintf(_T("long unsigned decimal number:\t\"%lu\"\n"), -123456L);
1757 wxPrintf(_T("zero-padded LDN:\t\"%010ld\"\n"), -123456L);
1758 test_format
= _T("left-adjusted ZLDN:\t\"%-010ld\"\n");
1759 wxPrintf(test_format
.c_str(), -123456);
1760 wxPrintf(_T("space-padded LDN:\t\"%10ld\"\n"), -123456L);
1761 wxPrintf(_T("left-adjusted SLDN:\t\"%-10ld\"\n"), -123456L);
1763 test_format
= _T("zero-padded string:\t\"%010s\"\n");
1764 wxPrintf(test_format
.c_str(), shortstr
);
1765 test_format
= _T("left-adjusted Z string:\t\"%-010s\"\n");
1766 wxPrintf(test_format
.c_str(), shortstr
);
1767 wxPrintf(_T("space-padded string:\t\"%10s\"\n"), shortstr
);
1768 wxPrintf(_T("left-adjusted S string:\t\"%-10s\"\n"), shortstr
);
1769 wxPrintf(_T("null string:\t\"%s\"\n"), PointerNull
);
1770 wxPrintf(_T("limited string:\t\"%.22s\"\n"), longstr
);
1772 wxPrintf(_T("e-style >= 1:\t\"%e\"\n"), 12.34);
1773 wxPrintf(_T("e-style >= .1:\t\"%e\"\n"), 0.1234);
1774 wxPrintf(_T("e-style < .1:\t\"%e\"\n"), 0.001234);
1775 wxPrintf(_T("e-style big:\t\"%.60e\"\n"), 1e20
);
1776 wxPrintf(_T("e-style == .1:\t\"%e\"\n"), 0.1);
1777 wxPrintf(_T("f-style >= 1:\t\"%f\"\n"), 12.34);
1778 wxPrintf(_T("f-style >= .1:\t\"%f\"\n"), 0.1234);
1779 wxPrintf(_T("f-style < .1:\t\"%f\"\n"), 0.001234);
1780 wxPrintf(_T("g-style >= 1:\t\"%g\"\n"), 12.34);
1781 wxPrintf(_T("g-style >= .1:\t\"%g\"\n"), 0.1234);
1782 wxPrintf(_T("g-style < .1:\t\"%g\"\n"), 0.001234);
1783 wxPrintf(_T("g-style big:\t\"%.60g\"\n"), 1e20
);
1785 wxPrintf (_T(" %6.5f\n"), .099999999860301614);
1786 wxPrintf (_T(" %6.5f\n"), .1);
1787 wxPrintf (_T("x%5.4fx\n"), .5);
1789 wxPrintf (_T("%#03x\n"), 1);
1791 //wxPrintf (_T("something really insane: %.10000f\n"), 1.0);
1797 while (niter
-- != 0)
1798 wxPrintf (_T("%.17e\n"), d
/ 2);
1803 // Open Watcom cause compiler error here
1804 // Error! E173: col(24) floating-point constant too small to represent
1805 wxPrintf (_T("%15.5e\n"), 4.9406564584124654e-324);
1808 #define FORMAT _T("|%12.4f|%12.4e|%12.4g|\n")
1809 wxPrintf (FORMAT
, 0.0, 0.0, 0.0);
1810 wxPrintf (FORMAT
, 1.0, 1.0, 1.0);
1811 wxPrintf (FORMAT
, -1.0, -1.0, -1.0);
1812 wxPrintf (FORMAT
, 100.0, 100.0, 100.0);
1813 wxPrintf (FORMAT
, 1000.0, 1000.0, 1000.0);
1814 wxPrintf (FORMAT
, 10000.0, 10000.0, 10000.0);
1815 wxPrintf (FORMAT
, 12345.0, 12345.0, 12345.0);
1816 wxPrintf (FORMAT
, 100000.0, 100000.0, 100000.0);
1817 wxPrintf (FORMAT
, 123456.0, 123456.0, 123456.0);
1822 int rc
= wxSnprintf (buf
, WXSIZEOF(buf
), _T("%30s"), _T("foo"));
1824 wxPrintf(_T("snprintf (\"%%30s\", \"foo\") == %d, \"%.*s\"\n"),
1825 rc
, WXSIZEOF(buf
), buf
);
1828 wxPrintf ("snprintf (\"%%.999999u\", 10)\n",
1829 wxSnprintf(buf2
, WXSIZEOFbuf2
), "%.999999u", 10));
1835 wxPrintf (_T("%e should be 1.234568e+06\n"), 1234567.8);
1836 wxPrintf (_T("%f should be 1234567.800000\n"), 1234567.8);
1837 wxPrintf (_T("%g should be 1.23457e+06\n"), 1234567.8);
1838 wxPrintf (_T("%g should be 123.456\n"), 123.456);
1839 wxPrintf (_T("%g should be 1e+06\n"), 1000000.0);
1840 wxPrintf (_T("%g should be 10\n"), 10.0);
1841 wxPrintf (_T("%g should be 0.02\n"), 0.02);
1845 wxPrintf(_T("%.17f\n"),(1.0/x
/10.0+1.0)*x
-x
);
1851 wxSprintf(buf
,_T("%*s%*s%*s"),-1,_T("one"),-20,_T("two"),-30,_T("three"));
1853 result
|= wxStrcmp (buf
,
1854 _T("onetwo three "));
1856 wxPuts (result
!= 0 ? _T("Test failed!") : _T("Test ok."));
1863 wxSprintf(buf
, _T("%07") wxLongLongFmtSpec
_T("o"), wxLL(040000000000));
1865 // for some reason below line fails under Borland
1866 wxPrintf (_T("sprintf (buf, \"%%07Lo\", 040000000000ll) = %s"), buf
);
1869 if (wxStrcmp (buf
, _T("40000000000")) != 0)
1872 wxPuts (_T("\tFAILED"));
1874 wxUnusedVar(result
);
1875 wxPuts (wxEmptyString
);
1877 #endif // wxLongLong_t
1879 wxPrintf (_T("printf (\"%%hhu\", %u) = %hhu\n"), UCHAR_MAX
+ 2, UCHAR_MAX
+ 2);
1880 wxPrintf (_T("printf (\"%%hu\", %u) = %hu\n"), USHRT_MAX
+ 2, USHRT_MAX
+ 2);
1882 wxPuts (_T("--- Should be no further output. ---"));
1891 memset (bytes
, '\xff', sizeof bytes
);
1892 wxSprintf (buf
, _T("foo%hhn\n"), &bytes
[3]);
1893 if (bytes
[0] != '\xff' || bytes
[1] != '\xff' || bytes
[2] != '\xff'
1894 || bytes
[4] != '\xff' || bytes
[5] != '\xff' || bytes
[6] != '\xff')
1896 wxPuts (_T("%hhn overwrite more bytes"));
1901 wxPuts (_T("%hhn wrote incorrect value"));
1913 wxSprintf (buf
, _T("%5.s"), _T("xyz"));
1914 if (wxStrcmp (buf
, _T(" ")) != 0)
1915 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" "));
1916 wxSprintf (buf
, _T("%5.f"), 33.3);
1917 if (wxStrcmp (buf
, _T(" 33")) != 0)
1918 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 33"));
1919 wxSprintf (buf
, _T("%8.e"), 33.3e7
);
1920 if (wxStrcmp (buf
, _T(" 3e+08")) != 0)
1921 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3e+08"));
1922 wxSprintf (buf
, _T("%8.E"), 33.3e7
);
1923 if (wxStrcmp (buf
, _T(" 3E+08")) != 0)
1924 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3E+08"));
1925 wxSprintf (buf
, _T("%.g"), 33.3);
1926 if (wxStrcmp (buf
, _T("3e+01")) != 0)
1927 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3e+01"));
1928 wxSprintf (buf
, _T("%.G"), 33.3);
1929 if (wxStrcmp (buf
, _T("3E+01")) != 0)
1930 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3E+01"));
1938 wxString test_format
;
1941 wxSprintf (buf
, _T("%.*g"), prec
, 3.3);
1942 if (wxStrcmp (buf
, _T("3")) != 0)
1943 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1945 wxSprintf (buf
, _T("%.*G"), prec
, 3.3);
1946 if (wxStrcmp (buf
, _T("3")) != 0)
1947 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T("3"));
1949 wxSprintf (buf
, _T("%7.*G"), prec
, 3.33);
1950 if (wxStrcmp (buf
, _T(" 3")) != 0)
1951 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 3"));
1953 test_format
= _T("%04.*o");
1954 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1955 if (wxStrcmp (buf
, _T(" 041")) != 0)
1956 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 041"));
1958 test_format
= _T("%09.*u");
1959 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1960 if (wxStrcmp (buf
, _T(" 0000033")) != 0)
1961 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 0000033"));
1963 test_format
= _T("%04.*x");
1964 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1965 if (wxStrcmp (buf
, _T(" 021")) != 0)
1966 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1968 test_format
= _T("%04.*X");
1969 wxSprintf (buf
, test_format
.c_str(), prec
, 33);
1970 if (wxStrcmp (buf
, _T(" 021")) != 0)
1971 wxPrintf (_T("got: '%s', expected: '%s'\n"), buf
, _T(" 021"));
1974 #endif // TEST_PRINTF
1976 // ----------------------------------------------------------------------------
1977 // registry and related stuff
1978 // ----------------------------------------------------------------------------
1980 // this is for MSW only
1983 #undef TEST_REGISTRY
1988 #include "wx/confbase.h"
1989 #include "wx/msw/regconf.h"
1992 static void TestRegConfWrite()
1994 wxConfig
*config
= new wxConfig(_T("myapp"));
1995 config
->SetPath(_T("/group1"));
1996 config
->Write(_T("entry1"), _T("foo"));
1997 config
->SetPath(_T("/group2"));
1998 config
->Write(_T("entry1"), _T("bar"));
2002 static void TestRegConfRead()
2004 wxConfig
*config
= new wxConfig(_T("myapp"));
2008 config
->SetPath(_T("/"));
2009 wxPuts(_T("Enumerating / subgroups:"));
2010 bool bCont
= config
->GetFirstGroup(str
, dummy
);
2014 bCont
= config
->GetNextGroup(str
, dummy
);
2018 #endif // TEST_REGCONF
2020 #ifdef TEST_REGISTRY
2022 #include "wx/msw/registry.h"
2024 // I chose this one because I liked its name, but it probably only exists under
2026 static const wxChar
*TESTKEY
=
2027 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2029 static void TestRegistryRead()
2031 wxPuts(_T("*** testing registry reading ***"));
2033 wxRegKey
key(TESTKEY
);
2034 wxPrintf(_T("The test key name is '%s'.\n"), key
.GetName().c_str());
2037 wxPuts(_T("ERROR: test key can't be opened, aborting test."));
2042 size_t nSubKeys
, nValues
;
2043 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2045 wxPrintf(_T("It has %u subkeys and %u values.\n"), nSubKeys
, nValues
);
2048 wxPrintf(_T("Enumerating values:\n"));
2052 bool cont
= key
.GetFirstValue(value
, dummy
);
2055 wxPrintf(_T("Value '%s': type "), value
.c_str());
2056 switch ( key
.GetValueType(value
) )
2058 case wxRegKey::Type_None
: wxPrintf(_T("ERROR (none)")); break;
2059 case wxRegKey::Type_String
: wxPrintf(_T("SZ")); break;
2060 case wxRegKey::Type_Expand_String
: wxPrintf(_T("EXPAND_SZ")); break;
2061 case wxRegKey::Type_Binary
: wxPrintf(_T("BINARY")); break;
2062 case wxRegKey::Type_Dword
: wxPrintf(_T("DWORD")); break;
2063 case wxRegKey::Type_Multi_String
: wxPrintf(_T("MULTI_SZ")); break;
2064 default: wxPrintf(_T("other (unknown)")); break;
2067 wxPrintf(_T(", value = "));
2068 if ( key
.IsNumericValue(value
) )
2071 key
.QueryValue(value
, &val
);
2072 wxPrintf(_T("%ld"), val
);
2077 key
.QueryValue(value
, val
);
2078 wxPrintf(_T("'%s'"), val
.c_str());
2080 key
.QueryRawValue(value
, val
);
2081 wxPrintf(_T(" (raw value '%s')"), val
.c_str());
2086 cont
= key
.GetNextValue(value
, dummy
);
2090 static void TestRegistryAssociation()
2093 The second call to deleteself genertaes an error message, with a
2094 messagebox saying .flo is crucial to system operation, while the .ddf
2095 call also fails, but with no error message
2100 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2102 key
= _T("ddxf_auto_file") ;
2103 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2105 key
= _T("ddxf_auto_file") ;
2106 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2108 key
= _T("program,0") ;
2109 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2111 key
= _T("program \"%1\"") ;
2113 key
.SetName(_T("HKEY_CLASSES_ROOT\\.ddf") );
2115 key
.SetName(_T("HKEY_CLASSES_ROOT\\.flo") );
2117 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon"));
2119 key
.SetName(_T("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command"));
2123 #endif // TEST_REGISTRY
2125 // ----------------------------------------------------------------------------
2127 // ----------------------------------------------------------------------------
2129 #ifdef TEST_SCOPEGUARD
2131 #include "wx/scopeguard.h"
2133 static void function0() { puts("function0()"); }
2134 static void function1(int n
) { printf("function1(%d)\n", n
); }
2135 static void function2(double x
, char c
) { printf("function2(%g, %c)\n", x
, c
); }
2139 void method0() { printf("method0()\n"); }
2140 void method1(int n
) { printf("method1(%d)\n", n
); }
2141 void method2(double x
, char c
) { printf("method2(%g, %c)\n", x
, c
); }
2144 static void TestScopeGuard()
2146 wxON_BLOCK_EXIT0(function0
);
2147 wxON_BLOCK_EXIT1(function1
, 17);
2148 wxON_BLOCK_EXIT2(function2
, 3.14, 'p');
2151 wxON_BLOCK_EXIT_OBJ0(obj
, &Object::method0
);
2152 wxON_BLOCK_EXIT_OBJ1(obj
, &Object::method1
, 7);
2153 wxON_BLOCK_EXIT_OBJ2(obj
, &Object::method2
, 2.71, 'e');
2155 wxScopeGuard dismissed
= wxMakeGuard(function0
);
2156 dismissed
.Dismiss();
2161 // ----------------------------------------------------------------------------
2163 // ----------------------------------------------------------------------------
2167 #include "wx/socket.h"
2168 #include "wx/protocol/protocol.h"
2169 #include "wx/protocol/http.h"
2171 static void TestSocketServer()
2173 wxPuts(_T("*** Testing wxSocketServer ***\n"));
2175 static const int PORT
= 3000;
2180 wxSocketServer
*server
= new wxSocketServer(addr
);
2181 if ( !server
->Ok() )
2183 wxPuts(_T("ERROR: failed to bind"));
2191 wxPrintf(_T("Server: waiting for connection on port %d...\n"), PORT
);
2193 wxSocketBase
*socket
= server
->Accept();
2196 wxPuts(_T("ERROR: wxSocketServer::Accept() failed."));
2200 wxPuts(_T("Server: got a client."));
2202 server
->SetTimeout(60); // 1 min
2205 while ( !close
&& socket
->IsConnected() )
2208 wxChar ch
= _T('\0');
2211 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2213 // don't log error if the client just close the connection
2214 if ( socket
->IsConnected() )
2216 wxPuts(_T("ERROR: in wxSocket::Read."));
2236 wxPrintf(_T("Server: got '%s'.\n"), s
.c_str());
2237 if ( s
== _T("close") )
2239 wxPuts(_T("Closing connection"));
2243 else if ( s
== _T("quit") )
2248 wxPuts(_T("Shutting down the server"));
2250 else // not a special command
2252 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2253 socket
->Write("\r\n", 2);
2254 wxPrintf(_T("Server: wrote '%s'.\n"), s
.c_str());
2260 wxPuts(_T("Server: lost a client unexpectedly."));
2266 // same as "delete server" but is consistent with GUI programs
2270 static void TestSocketClient()
2272 wxPuts(_T("*** Testing wxSocketClient ***\n"));
2274 static const wxChar
*hostname
= _T("www.wxwidgets.org");
2277 addr
.Hostname(hostname
);
2280 wxPrintf(_T("--- Attempting to connect to %s:80...\n"), hostname
);
2282 wxSocketClient client
;
2283 if ( !client
.Connect(addr
) )
2285 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2289 wxPrintf(_T("--- Connected to %s:%u...\n"),
2290 addr
.Hostname().c_str(), addr
.Service());
2294 // could use simply "GET" here I suppose
2296 wxString::Format(_T("GET http://%s/\r\n"), hostname
);
2297 client
.Write(cmdGet
, cmdGet
.length());
2298 wxPrintf(_T("--- Sent command '%s' to the server\n"),
2299 MakePrintable(cmdGet
).c_str());
2300 client
.Read(buf
, WXSIZEOF(buf
));
2301 wxPrintf(_T("--- Server replied:\n%s"), buf
);
2305 #endif // TEST_SOCKETS
2307 // ----------------------------------------------------------------------------
2309 // ----------------------------------------------------------------------------
2313 #include "wx/protocol/ftp.h"
2317 #define FTP_ANONYMOUS
2319 #ifdef FTP_ANONYMOUS
2320 static const wxChar
*directory
= _T("/pub");
2321 static const wxChar
*filename
= _T("welcome.msg");
2323 static const wxChar
*directory
= _T("/etc");
2324 static const wxChar
*filename
= _T("issue");
2327 static bool TestFtpConnect()
2329 wxPuts(_T("*** Testing FTP connect ***"));
2331 #ifdef FTP_ANONYMOUS
2332 static const wxChar
*hostname
= _T("ftp.wxwidgets.org");
2334 wxPrintf(_T("--- Attempting to connect to %s:21 anonymously...\n"), hostname
);
2335 #else // !FTP_ANONYMOUS
2336 static const wxChar
*hostname
= "localhost";
2339 wxFgets(user
, WXSIZEOF(user
), stdin
);
2340 user
[wxStrlen(user
) - 1] = '\0'; // chop off '\n'
2343 wxChar password
[256];
2344 wxPrintf(_T("Password for %s: "), password
);
2345 wxFgets(password
, WXSIZEOF(password
), stdin
);
2346 password
[wxStrlen(password
) - 1] = '\0'; // chop off '\n'
2347 ftp
.SetPassword(password
);
2349 wxPrintf(_T("--- Attempting to connect to %s:21 as %s...\n"), hostname
, user
);
2350 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2352 if ( !ftp
.Connect(hostname
) )
2354 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2360 wxPrintf(_T("--- Connected to %s, current directory is '%s'\n"),
2361 hostname
, ftp
.Pwd().c_str());
2368 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2369 static void TestFtpWuFtpd()
2372 static const wxChar
*hostname
= _T("ftp.eudora.com");
2373 if ( !ftp
.Connect(hostname
) )
2375 wxPrintf(_T("ERROR: failed to connect to %s\n"), hostname
);
2379 static const wxChar
*filename
= _T("eudora/pubs/draft-gellens-submit-09.txt");
2380 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2383 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2387 size_t size
= in
->GetSize();
2388 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2390 wxChar
*data
= new wxChar
[size
];
2391 if ( !in
->Read(data
, size
) )
2393 wxPuts(_T("ERROR: read error"));
2397 wxPrintf(_T("Successfully retrieved the file.\n"));
2406 static void TestFtpList()
2408 wxPuts(_T("*** Testing wxFTP file listing ***\n"));
2411 if ( !ftp
.ChDir(directory
) )
2413 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2416 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2418 // test NLIST and LIST
2419 wxArrayString files
;
2420 if ( !ftp
.GetFilesList(files
) )
2422 wxPuts(_T("ERROR: failed to get NLIST of files"));
2426 wxPrintf(_T("Brief list of files under '%s':\n"), ftp
.Pwd().c_str());
2427 size_t count
= files
.GetCount();
2428 for ( size_t n
= 0; n
< count
; n
++ )
2430 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2432 wxPuts(_T("End of the file list"));
2435 if ( !ftp
.GetDirList(files
) )
2437 wxPuts(_T("ERROR: failed to get LIST of files"));
2441 wxPrintf(_T("Detailed list of files under '%s':\n"), ftp
.Pwd().c_str());
2442 size_t count
= files
.GetCount();
2443 for ( size_t n
= 0; n
< count
; n
++ )
2445 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2447 wxPuts(_T("End of the file list"));
2450 if ( !ftp
.ChDir(_T("..")) )
2452 wxPuts(_T("ERROR: failed to cd to .."));
2455 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2458 static void TestFtpDownload()
2460 wxPuts(_T("*** Testing wxFTP download ***\n"));
2463 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2466 wxPrintf(_T("ERROR: couldn't get input stream for %s\n"), filename
);
2470 size_t size
= in
->GetSize();
2471 wxPrintf(_T("Reading file %s (%u bytes)..."), filename
, size
);
2474 wxChar
*data
= new wxChar
[size
];
2475 if ( !in
->Read(data
, size
) )
2477 wxPuts(_T("ERROR: read error"));
2481 wxPrintf(_T("\nContents of %s:\n%s\n"), filename
, data
);
2489 static void TestFtpFileSize()
2491 wxPuts(_T("*** Testing FTP SIZE command ***"));
2493 if ( !ftp
.ChDir(directory
) )
2495 wxPrintf(_T("ERROR: failed to cd to %s\n"), directory
);
2498 wxPrintf(_T("Current directory is '%s'\n"), ftp
.Pwd().c_str());
2500 if ( ftp
.FileExists(filename
) )
2502 int size
= ftp
.GetFileSize(filename
);
2504 wxPrintf(_T("ERROR: couldn't get size of '%s'\n"), filename
);
2506 wxPrintf(_T("Size of '%s' is %d bytes.\n"), filename
, size
);
2510 wxPrintf(_T("ERROR: '%s' doesn't exist\n"), filename
);
2514 static void TestFtpMisc()
2516 wxPuts(_T("*** Testing miscellaneous wxFTP functions ***"));
2518 if ( ftp
.SendCommand(_T("STAT")) != '2' )
2520 wxPuts(_T("ERROR: STAT failed"));
2524 wxPrintf(_T("STAT returned:\n\n%s\n"), ftp
.GetLastResult().c_str());
2527 if ( ftp
.SendCommand(_T("HELP SITE")) != '2' )
2529 wxPuts(_T("ERROR: HELP SITE failed"));
2533 wxPrintf(_T("The list of site-specific commands:\n\n%s\n"),
2534 ftp
.GetLastResult().c_str());
2538 static void TestFtpInteractive()
2540 wxPuts(_T("\n*** Interactive wxFTP test ***"));
2546 wxPrintf(_T("Enter FTP command: "));
2547 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
2550 // kill the last '\n'
2551 buf
[wxStrlen(buf
) - 1] = 0;
2553 // special handling of LIST and NLST as they require data connection
2554 wxString
start(buf
, 4);
2556 if ( start
== _T("LIST") || start
== _T("NLST") )
2559 if ( wxStrlen(buf
) > 4 )
2562 wxArrayString files
;
2563 if ( !ftp
.GetList(files
, wildcard
, start
== _T("LIST")) )
2565 wxPrintf(_T("ERROR: failed to get %s of files\n"), start
.c_str());
2569 wxPrintf(_T("--- %s of '%s' under '%s':\n"),
2570 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2571 size_t count
= files
.GetCount();
2572 for ( size_t n
= 0; n
< count
; n
++ )
2574 wxPrintf(_T("\t%s\n"), files
[n
].c_str());
2576 wxPuts(_T("--- End of the file list"));
2581 wxChar ch
= ftp
.SendCommand(buf
);
2582 wxPrintf(_T("Command %s"), ch
? _T("succeeded") : _T("failed"));
2585 wxPrintf(_T(" (return code %c)"), ch
);
2588 wxPrintf(_T(", server reply:\n%s\n\n"), ftp
.GetLastResult().c_str());
2592 wxPuts(_T("\n*** done ***"));
2595 static void TestFtpUpload()
2597 wxPuts(_T("*** Testing wxFTP uploading ***\n"));
2600 static const wxChar
*file1
= _T("test1");
2601 static const wxChar
*file2
= _T("test2");
2602 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2605 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2606 out
->Write("First hello", 11);
2610 // send a command to check the remote file
2611 if ( ftp
.SendCommand(wxString(_T("STAT ")) + file1
) != '2' )
2613 wxPrintf(_T("ERROR: STAT %s failed\n"), file1
);
2617 wxPrintf(_T("STAT %s returned:\n\n%s\n"),
2618 file1
, ftp
.GetLastResult().c_str());
2621 out
= ftp
.GetOutputStream(file2
);
2624 wxPrintf(_T("--- Uploading to %s ---\n"), file1
);
2625 out
->Write("Second hello", 12);
2632 // ----------------------------------------------------------------------------
2634 // ----------------------------------------------------------------------------
2636 #ifdef TEST_STDPATHS
2638 #include "wx/stdpaths.h"
2640 static void TestStandardPaths()
2642 wxPuts(_T("*** Testing wxStandardPaths ***\n"));
2644 wxTheApp
->SetAppName(_T("console"));
2646 wxStandardPaths
& stdp
= wxStandardPaths::Get();
2647 wxPrintf(_T("Config dir (sys):\t%s\n"), stdp
.GetConfigDir().c_str());
2648 wxPrintf(_T("Config dir (user):\t%s\n"), stdp
.GetUserConfigDir().c_str());
2649 wxPrintf(_T("Data dir (sys):\t\t%s\n"), stdp
.GetDataDir().c_str());
2650 wxPrintf(_T("Data dir (sys local):\t%s\n"), stdp
.GetLocalDataDir().c_str());
2651 wxPrintf(_T("Data dir (user):\t%s\n"), stdp
.GetUserDataDir().c_str());
2652 wxPrintf(_T("Data dir (user local):\t%s\n"), stdp
.GetUserLocalDataDir().c_str());
2653 wxPrintf(_T("Plugins dir:\t\t%s\n"), stdp
.GetPluginsDir().c_str());
2656 #endif // TEST_STDPATHS
2658 // ----------------------------------------------------------------------------
2660 // ----------------------------------------------------------------------------
2664 #include "wx/wfstream.h"
2665 #include "wx/mstream.h"
2667 static void TestFileStream()
2669 wxPuts(_T("*** Testing wxFileInputStream ***"));
2671 static const wxString filename
= _T("testdata.fs");
2673 wxFileOutputStream
fsOut(filename
);
2674 fsOut
.Write("foo", 3);
2677 wxFileInputStream
fsIn(filename
);
2678 wxPrintf(_T("File stream size: %u\n"), fsIn
.GetSize());
2679 while ( !fsIn
.Eof() )
2681 wxPutchar(fsIn
.GetC());
2684 if ( !wxRemoveFile(filename
) )
2686 wxPrintf(_T("ERROR: failed to remove the file '%s'.\n"), filename
.c_str());
2689 wxPuts(_T("\n*** wxFileInputStream test done ***"));
2692 static void TestMemoryStream()
2694 wxPuts(_T("*** Testing wxMemoryOutputStream ***"));
2696 wxMemoryOutputStream memOutStream
;
2697 wxPrintf(_T("Initially out stream offset: %lu\n"),
2698 (unsigned long)memOutStream
.TellO());
2700 for ( const wxChar
*p
= _T("Hello, stream!"); *p
; p
++ )
2702 memOutStream
.PutC(*p
);
2705 wxPrintf(_T("Final out stream offset: %lu\n"),
2706 (unsigned long)memOutStream
.TellO());
2708 wxPuts(_T("*** Testing wxMemoryInputStream ***"));
2711 size_t len
= memOutStream
.CopyTo(buf
, WXSIZEOF(buf
));
2713 wxMemoryInputStream
memInpStream(buf
, len
);
2714 wxPrintf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2715 while ( !memInpStream
.Eof() )
2717 wxPutchar(memInpStream
.GetC());
2720 wxPuts(_T("\n*** wxMemoryInputStream test done ***"));
2723 #endif // TEST_STREAMS
2725 // ----------------------------------------------------------------------------
2727 // ----------------------------------------------------------------------------
2731 #include "wx/timer.h"
2732 #include "wx/utils.h"
2734 static void TestStopWatch()
2736 wxPuts(_T("*** Testing wxStopWatch ***\n"));
2740 wxPrintf(_T("Initially paused, after 2 seconds time is..."));
2743 wxPrintf(_T("\t%ldms\n"), sw
.Time());
2745 wxPrintf(_T("Resuming stopwatch and sleeping 3 seconds..."));
2749 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2752 wxPrintf(_T("Pausing agan and sleeping 2 more seconds..."));
2755 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2758 wxPrintf(_T("Finally resuming and sleeping 2 more seconds..."));
2761 wxPrintf(_T("\telapsed time: %ldms\n"), sw
.Time());
2764 wxPuts(_T("\nChecking for 'backwards clock' bug..."));
2765 for ( size_t n
= 0; n
< 70; n
++ )
2769 for ( size_t m
= 0; m
< 100000; m
++ )
2771 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2773 wxPuts(_T("\ntime is negative - ERROR!"));
2781 wxPuts(_T(", ok."));
2784 #endif // TEST_TIMER
2786 // ----------------------------------------------------------------------------
2788 // ----------------------------------------------------------------------------
2792 #include "wx/vcard.h"
2794 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2797 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2800 wxPrintf(_T("%s%s"),
2801 wxString(_T('\t'), level
).c_str(),
2802 vcObj
->GetName().c_str());
2805 switch ( vcObj
->GetType() )
2807 case wxVCardObject::String
:
2808 case wxVCardObject::UString
:
2811 vcObj
->GetValue(&val
);
2812 value
<< _T('"') << val
<< _T('"');
2816 case wxVCardObject::Int
:
2819 vcObj
->GetValue(&i
);
2820 value
.Printf(_T("%u"), i
);
2824 case wxVCardObject::Long
:
2827 vcObj
->GetValue(&l
);
2828 value
.Printf(_T("%lu"), l
);
2832 case wxVCardObject::None
:
2835 case wxVCardObject::Object
:
2836 value
= _T("<node>");
2840 value
= _T("<unknown value type>");
2844 wxPrintf(_T(" = %s"), value
.c_str());
2847 DumpVObject(level
+ 1, *vcObj
);
2850 vcObj
= vcard
.GetNextProp(&cookie
);
2854 static void DumpVCardAddresses(const wxVCard
& vcard
)
2856 wxPuts(_T("\nShowing all addresses from vCard:\n"));
2860 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2864 int flags
= addr
->GetFlags();
2865 if ( flags
& wxVCardAddress::Domestic
)
2867 flagsStr
<< _T("domestic ");
2869 if ( flags
& wxVCardAddress::Intl
)
2871 flagsStr
<< _T("international ");
2873 if ( flags
& wxVCardAddress::Postal
)
2875 flagsStr
<< _T("postal ");
2877 if ( flags
& wxVCardAddress::Parcel
)
2879 flagsStr
<< _T("parcel ");
2881 if ( flags
& wxVCardAddress::Home
)
2883 flagsStr
<< _T("home ");
2885 if ( flags
& wxVCardAddress::Work
)
2887 flagsStr
<< _T("work ");
2890 wxPrintf(_T("Address %u:\n")
2892 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2895 addr
->GetPostOffice().c_str(),
2896 addr
->GetExtAddress().c_str(),
2897 addr
->GetStreet().c_str(),
2898 addr
->GetLocality().c_str(),
2899 addr
->GetRegion().c_str(),
2900 addr
->GetPostalCode().c_str(),
2901 addr
->GetCountry().c_str()
2905 addr
= vcard
.GetNextAddress(&cookie
);
2909 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
2911 wxPuts(_T("\nShowing all phone numbers from vCard:\n"));
2915 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
2919 int flags
= phone
->GetFlags();
2920 if ( flags
& wxVCardPhoneNumber::Voice
)
2922 flagsStr
<< _T("voice ");
2924 if ( flags
& wxVCardPhoneNumber::Fax
)
2926 flagsStr
<< _T("fax ");
2928 if ( flags
& wxVCardPhoneNumber::Cellular
)
2930 flagsStr
<< _T("cellular ");
2932 if ( flags
& wxVCardPhoneNumber::Modem
)
2934 flagsStr
<< _T("modem ");
2936 if ( flags
& wxVCardPhoneNumber::Home
)
2938 flagsStr
<< _T("home ");
2940 if ( flags
& wxVCardPhoneNumber::Work
)
2942 flagsStr
<< _T("work ");
2945 wxPrintf(_T("Phone number %u:\n")
2950 phone
->GetNumber().c_str()
2954 phone
= vcard
.GetNextPhoneNumber(&cookie
);
2958 static void TestVCardRead()
2960 wxPuts(_T("*** Testing wxVCard reading ***\n"));
2962 wxVCard
vcard(_T("vcard.vcf"));
2963 if ( !vcard
.IsOk() )
2965 wxPuts(_T("ERROR: couldn't load vCard."));
2969 // read individual vCard properties
2970 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
2974 vcObj
->GetValue(&value
);
2979 value
= _T("<none>");
2982 wxPrintf(_T("Full name retrieved directly: %s\n"), value
.c_str());
2985 if ( !vcard
.GetFullName(&value
) )
2987 value
= _T("<none>");
2990 wxPrintf(_T("Full name from wxVCard API: %s\n"), value
.c_str());
2992 // now show how to deal with multiply occuring properties
2993 DumpVCardAddresses(vcard
);
2994 DumpVCardPhoneNumbers(vcard
);
2996 // and finally show all
2997 wxPuts(_T("\nNow dumping the entire vCard:\n")
2998 "-----------------------------\n");
3000 DumpVObject(0, vcard
);
3004 static void TestVCardWrite()
3006 wxPuts(_T("*** Testing wxVCard writing ***\n"));
3009 if ( !vcard
.IsOk() )
3011 wxPuts(_T("ERROR: couldn't create vCard."));
3016 vcard
.SetName("Zeitlin", "Vadim");
3017 vcard
.SetFullName("Vadim Zeitlin");
3018 vcard
.SetOrganization("wxWidgets", "R&D");
3020 // just dump the vCard back
3021 wxPuts(_T("Entire vCard follows:\n"));
3022 wxPuts(vcard
.Write());
3026 #endif // TEST_VCARD
3028 // ----------------------------------------------------------------------------
3030 // ----------------------------------------------------------------------------
3032 #if !defined(__WIN32__) || !wxUSE_FSVOLUME
3038 #include "wx/volume.h"
3040 static const wxChar
*volumeKinds
[] =
3046 _T("network volume"),
3050 static void TestFSVolume()
3052 wxPuts(_T("*** Testing wxFSVolume class ***"));
3054 wxArrayString volumes
= wxFSVolume::GetVolumes();
3055 size_t count
= volumes
.GetCount();
3059 wxPuts(_T("ERROR: no mounted volumes?"));
3063 wxPrintf(_T("%u mounted volumes found:\n"), count
);
3065 for ( size_t n
= 0; n
< count
; n
++ )
3067 wxFSVolume
vol(volumes
[n
]);
3070 wxPuts(_T("ERROR: couldn't create volume"));
3074 wxPrintf(_T("%u: %s (%s), %s, %s, %s\n"),
3076 vol
.GetDisplayName().c_str(),
3077 vol
.GetName().c_str(),
3078 volumeKinds
[vol
.GetKind()],
3079 vol
.IsWritable() ? _T("rw") : _T("ro"),
3080 vol
.GetFlags() & wxFS_VOL_REMOVABLE
? _T("removable")
3085 #endif // TEST_VOLUME
3087 // ----------------------------------------------------------------------------
3088 // wide char and Unicode support
3089 // ----------------------------------------------------------------------------
3093 #include "wx/strconv.h"
3094 #include "wx/fontenc.h"
3095 #include "wx/encconv.h"
3096 #include "wx/buffer.h"
3098 static const unsigned char utf8koi8r
[] =
3100 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3101 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3102 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3103 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3104 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3105 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3106 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3109 static const unsigned char utf8iso8859_1
[] =
3111 0x53, 0x79, 0x73, 0x74, 0xc3, 0xa8, 0x6d, 0x65, 0x73, 0x20, 0x49, 0x6e,
3112 0x74, 0xc3, 0xa9, 0x67, 0x72, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x20, 0x65,
3113 0x6e, 0x20, 0x4d, 0xc3, 0xa9, 0x63, 0x61, 0x6e, 0x69, 0x71, 0x75, 0x65,
3114 0x20, 0x43, 0x6c, 0x61, 0x73, 0x73, 0x69, 0x71, 0x75, 0x65, 0x20, 0x65,
3115 0x74, 0x20, 0x51, 0x75, 0x61, 0x6e, 0x74, 0x69, 0x71, 0x75, 0x65, 0
3118 static const unsigned char utf8Invalid
[] =
3120 0x3c, 0x64, 0x69, 0x73, 0x70, 0x6c, 0x61, 0x79, 0x3e, 0x32, 0x30, 0x30,
3121 0x32, 0xe5, 0xb9, 0xb4, 0x30, 0x39, 0xe6, 0x9c, 0x88, 0x32, 0x35, 0xe6,
3122 0x97, 0xa5, 0x20, 0x30, 0x37, 0xe6, 0x99, 0x82, 0x33, 0x39, 0xe5, 0x88,
3123 0x86, 0x35, 0x37, 0xe7, 0xa7, 0x92, 0x3c, 0x2f, 0x64, 0x69, 0x73, 0x70,
3127 static const struct Utf8Data
3129 const unsigned char *text
;
3131 const wxChar
*charset
;
3132 wxFontEncoding encoding
;
3135 { utf8Invalid
, WXSIZEOF(utf8Invalid
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3136 { utf8koi8r
, WXSIZEOF(utf8koi8r
), _T("koi8-r"), wxFONTENCODING_KOI8
},
3137 { utf8iso8859_1
, WXSIZEOF(utf8iso8859_1
), _T("iso8859-1"), wxFONTENCODING_ISO8859_1
},
3140 static void TestUtf8()
3142 wxPuts(_T("*** Testing UTF8 support ***\n"));
3147 for ( size_t n
= 0; n
< WXSIZEOF(utf8data
); n
++ )
3149 const Utf8Data
& u8d
= utf8data
[n
];
3150 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)u8d
.text
,
3151 WXSIZEOF(wbuf
)) == (size_t)-1 )
3153 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3157 wxCSConv
conv(u8d
.charset
);
3158 if ( conv
.WC2MB(buf
, wbuf
, WXSIZEOF(buf
)) == (size_t)-1 )
3160 wxPrintf(_T("ERROR: conversion to %s failed.\n"), u8d
.charset
);
3164 wxPrintf(_T("String in %s: %s\n"), u8d
.charset
, buf
);
3168 wxString
s(wxConvUTF8
.cMB2WC((const char *)u8d
.text
));
3170 s
= _T("<< conversion failed >>");
3171 wxPrintf(_T("String in current cset: %s\n"), s
.c_str());
3175 wxPuts(wxEmptyString
);
3178 static void TestEncodingConverter()
3180 wxPuts(_T("*** Testing wxEncodingConverter ***\n"));
3182 // using wxEncodingConverter should give the same result as above
3185 if ( wxConvUTF8
.MB2WC(wbuf
, (const char *)utf8koi8r
,
3186 WXSIZEOF(utf8koi8r
)) == (size_t)-1 )
3188 wxPuts(_T("ERROR: UTF-8 decoding failed."));
3192 wxEncodingConverter ec
;
3193 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3194 ec
.Convert(wbuf
, buf
);
3195 wxPrintf(_T("The same KOI8-R string using wxEC: %s\n"), buf
);
3198 wxPuts(wxEmptyString
);
3201 #endif // TEST_WCHAR
3203 // ----------------------------------------------------------------------------
3205 // ----------------------------------------------------------------------------
3209 #include "wx/filesys.h"
3210 #include "wx/fs_zip.h"
3211 #include "wx/zipstrm.h"
3213 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3215 static void TestZipStreamRead()
3217 wxPuts(_T("*** Testing ZIP reading ***\n"));
3219 static const wxString filename
= _T("foo");
3220 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3221 wxPrintf(_T("Archive size: %u\n"), istr
.GetSize());
3223 wxPrintf(_T("Dumping the file '%s':\n"), filename
.c_str());
3224 while ( !istr
.Eof() )
3226 wxPutchar(istr
.GetC());
3230 wxPuts(_T("\n----- done ------"));
3233 static void DumpZipDirectory(wxFileSystem
& fs
,
3234 const wxString
& dir
,
3235 const wxString
& indent
)
3237 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3238 TESTFILE_ZIP
, dir
.c_str());
3239 wxString wildcard
= prefix
+ _T("/*");
3241 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3242 while ( !dirname
.empty() )
3244 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3246 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3251 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3253 DumpZipDirectory(fs
, dirname
,
3254 indent
+ wxString(_T(' '), 4));
3256 dirname
= fs
.FindNext();
3259 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3260 while ( !filename
.empty() )
3262 if ( !filename
.StartsWith(prefix
, &filename
) )
3264 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3269 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3271 filename
= fs
.FindNext();
3275 static void TestZipFileSystem()
3277 wxPuts(_T("*** Testing ZIP file system ***\n"));
3279 wxFileSystem::AddHandler(new wxZipFSHandler
);
3281 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3283 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3288 // ----------------------------------------------------------------------------
3290 // ----------------------------------------------------------------------------
3292 #ifdef TEST_DATETIME
3294 #include "wx/math.h"
3295 #include "wx/datetime.h"
3297 // this test miscellaneous static wxDateTime functions
3301 static void TestTimeStatic()
3303 wxPuts(_T("\n*** wxDateTime static methods test ***"));
3305 // some info about the current date
3306 int year
= wxDateTime::GetCurrentYear();
3307 wxPrintf(_T("Current year %d is %sa leap one and has %d days.\n"),
3309 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3310 wxDateTime::GetNumberOfDays(year
));
3312 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3313 wxPrintf(_T("Current month is '%s' ('%s') and it has %d days\n"),
3314 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3315 wxDateTime::GetMonthName(month
).c_str(),
3316 wxDateTime::GetNumberOfDays(month
));
3319 // test time zones stuff
3320 static void TestTimeZones()
3322 wxPuts(_T("\n*** wxDateTime timezone test ***"));
3324 wxDateTime now
= wxDateTime::Now();
3326 wxPrintf(_T("Current GMT time:\t%s\n"), now
.Format(_T("%c"), wxDateTime::GMT0
).c_str());
3327 wxPrintf(_T("Unix epoch (GMT):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::GMT0
).c_str());
3328 wxPrintf(_T("Unix epoch (EST):\t%s\n"), wxDateTime((time_t)0).Format(_T("%c"), wxDateTime::EST
).c_str());
3329 wxPrintf(_T("Current time in Paris:\t%s\n"), now
.Format(_T("%c"), wxDateTime::CET
).c_str());
3330 wxPrintf(_T(" Moscow:\t%s\n"), now
.Format(_T("%c"), wxDateTime::MSK
).c_str());
3331 wxPrintf(_T(" New York:\t%s\n"), now
.Format(_T("%c"), wxDateTime::EST
).c_str());
3333 wxPrintf(_T("%s\n"), wxDateTime::Now().Format(_T("Our timezone is %Z")).c_str());
3335 wxDateTime::Tm tm
= now
.GetTm();
3336 if ( wxDateTime(tm
) != now
)
3338 wxPrintf(_T("ERROR: got %s instead of %s\n"),
3339 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3343 // test some minimal support for the dates outside the standard range
3344 static void TestTimeRange()
3346 wxPuts(_T("\n*** wxDateTime out-of-standard-range dates test ***"));
3348 static const wxChar
*fmt
= _T("%d-%b-%Y %H:%M:%S");
3350 wxPrintf(_T("Unix epoch:\t%s\n"),
3351 wxDateTime(2440587.5).Format(fmt
).c_str());
3352 wxPrintf(_T("Feb 29, 0: \t%s\n"),
3353 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3354 wxPrintf(_T("JDN 0: \t%s\n"),
3355 wxDateTime(0.0).Format(fmt
).c_str());
3356 wxPrintf(_T("Jan 1, 1AD:\t%s\n"),
3357 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3358 wxPrintf(_T("May 29, 2099:\t%s\n"),
3359 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3362 // test DST calculations
3363 static void TestTimeDST()
3365 wxPuts(_T("\n*** wxDateTime DST test ***"));
3367 wxPrintf(_T("DST is%s in effect now.\n\n"),
3368 wxDateTime::Now().IsDST() ? wxEmptyString
: _T(" not"));
3370 for ( int year
= 1990; year
< 2005; year
++ )
3372 wxPrintf(_T("DST period in Europe for year %d: from %s to %s\n"),
3374 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3375 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3381 #if TEST_INTERACTIVE
3383 static void TestDateTimeInteractive()
3385 wxPuts(_T("\n*** interactive wxDateTime tests ***"));
3391 wxPrintf(_T("Enter a date: "));
3392 if ( !wxFgets(buf
, WXSIZEOF(buf
), stdin
) )
3395 // kill the last '\n'
3396 buf
[wxStrlen(buf
) - 1] = 0;
3399 const wxChar
*p
= dt
.ParseDate(buf
);
3402 wxPrintf(_T("ERROR: failed to parse the date '%s'.\n"), buf
);
3408 wxPrintf(_T("WARNING: parsed only first %u characters.\n"), p
- buf
);
3411 wxPrintf(_T("%s: day %u, week of month %u/%u, week of year %u\n"),
3412 dt
.Format(_T("%b %d, %Y")).c_str(),
3414 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3415 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3416 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
3419 wxPuts(_T("\n*** done ***"));
3422 #endif // TEST_INTERACTIVE
3426 static void TestTimeMS()
3428 wxPuts(_T("*** testing millisecond-resolution support in wxDateTime ***"));
3430 wxDateTime dt1
= wxDateTime::Now(),
3431 dt2
= wxDateTime::UNow();
3433 wxPrintf(_T("Now = %s\n"), dt1
.Format(_T("%H:%M:%S:%l")).c_str());
3434 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3435 wxPrintf(_T("Dummy loop: "));
3436 for ( int i
= 0; i
< 6000; i
++ )
3438 //for ( int j = 0; j < 10; j++ )
3441 s
.Printf(_T("%g"), sqrt((float)i
));
3447 wxPuts(_T(", done"));
3450 dt2
= wxDateTime::UNow();
3451 wxPrintf(_T("UNow = %s\n"), dt2
.Format(_T("%H:%M:%S:%l")).c_str());
3453 wxPrintf(_T("Loop executed in %s ms\n"), (dt2
- dt1
).Format(_T("%l")).c_str());
3455 wxPuts(_T("\n*** done ***"));
3458 static void TestTimeHolidays()
3460 wxPuts(_T("\n*** testing wxDateTimeHolidayAuthority ***\n"));
3462 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
3463 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
3464 dtEnd
= dtStart
.GetLastMonthDay();
3466 wxDateTimeArray hol
;
3467 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
3469 const wxChar
*format
= _T("%d-%b-%Y (%a)");
3471 wxPrintf(_T("All holidays between %s and %s:\n"),
3472 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
3474 size_t count
= hol
.GetCount();
3475 for ( size_t n
= 0; n
< count
; n
++ )
3477 wxPrintf(_T("\t%s\n"), hol
[n
].Format(format
).c_str());
3480 wxPuts(wxEmptyString
);
3483 static void TestTimeZoneBug()
3485 wxPuts(_T("\n*** testing for DST/timezone bug ***\n"));
3487 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
3488 for ( int i
= 0; i
< 31; i
++ )
3490 wxPrintf(_T("Date %s: week day %s.\n"),
3491 date
.Format(_T("%d-%m-%Y")).c_str(),
3492 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
3494 date
+= wxDateSpan::Day();
3497 wxPuts(wxEmptyString
);
3500 static void TestTimeSpanFormat()
3502 wxPuts(_T("\n*** wxTimeSpan tests ***"));
3504 static const wxChar
*formats
[] =
3506 _T("(default) %H:%M:%S"),
3507 _T("%E weeks and %D days"),
3508 _T("%l milliseconds"),
3509 _T("(with ms) %H:%M:%S:%l"),
3510 _T("100%% of minutes is %M"), // test "%%"
3511 _T("%D days and %H hours"),
3512 _T("or also %S seconds"),
3515 wxTimeSpan
ts1(1, 2, 3, 4),
3517 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
3519 wxPrintf(_T("ts1 = %s\tts2 = %s\n"),
3520 ts1
.Format(formats
[n
]).c_str(),
3521 ts2
.Format(formats
[n
]).c_str());
3524 wxPuts(wxEmptyString
);
3529 #endif // TEST_DATETIME
3531 // ----------------------------------------------------------------------------
3532 // wxTextInput/OutputStream
3533 // ----------------------------------------------------------------------------
3535 #ifdef TEST_TEXTSTREAM
3537 #include "wx/txtstrm.h"
3538 #include "wx/wfstream.h"
3540 static void TestTextInputStream()
3542 wxPuts(_T("\n*** wxTextInputStream test ***"));
3544 wxString filename
= _T("testdata.fc");
3545 wxFileInputStream
fsIn(filename
);
3548 wxPuts(_T("ERROR: couldn't open file."));
3552 wxTextInputStream
tis(fsIn
);
3557 const wxString s
= tis
.ReadLine();
3559 // line could be non empty if the last line of the file isn't
3560 // terminated with EOL
3561 if ( fsIn
.Eof() && s
.empty() )
3564 wxPrintf(_T("Line %d: %s\n"), line
++, s
.c_str());
3569 #endif // TEST_TEXTSTREAM
3571 // ----------------------------------------------------------------------------
3573 // ----------------------------------------------------------------------------
3577 #include "wx/thread.h"
3579 static size_t gs_counter
= (size_t)-1;
3580 static wxCriticalSection gs_critsect
;
3581 static wxSemaphore gs_cond
;
3583 class MyJoinableThread
: public wxThread
3586 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
3587 { m_n
= n
; Create(); }
3589 // thread execution starts here
3590 virtual ExitCode
Entry();
3596 wxThread::ExitCode
MyJoinableThread::Entry()
3598 unsigned long res
= 1;
3599 for ( size_t n
= 1; n
< m_n
; n
++ )
3603 // it's a loooong calculation :-)
3607 return (ExitCode
)res
;
3610 class MyDetachedThread
: public wxThread
3613 MyDetachedThread(size_t n
, wxChar ch
)
3617 m_cancelled
= false;
3622 // thread execution starts here
3623 virtual ExitCode
Entry();
3626 virtual void OnExit();
3629 size_t m_n
; // number of characters to write
3630 wxChar m_ch
; // character to write
3632 bool m_cancelled
; // false if we exit normally
3635 wxThread::ExitCode
MyDetachedThread::Entry()
3638 wxCriticalSectionLocker
lock(gs_critsect
);
3639 if ( gs_counter
== (size_t)-1 )
3645 for ( size_t n
= 0; n
< m_n
; n
++ )
3647 if ( TestDestroy() )
3657 wxThread::Sleep(100);
3663 void MyDetachedThread::OnExit()
3665 wxLogTrace(_T("thread"), _T("Thread %ld is in OnExit"), GetId());
3667 wxCriticalSectionLocker
lock(gs_critsect
);
3668 if ( !--gs_counter
&& !m_cancelled
)
3672 static void TestDetachedThreads()
3674 wxPuts(_T("\n*** Testing detached threads ***"));
3676 static const size_t nThreads
= 3;
3677 MyDetachedThread
*threads
[nThreads
];
3679 for ( n
= 0; n
< nThreads
; n
++ )
3681 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
3684 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
3685 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
3687 for ( n
= 0; n
< nThreads
; n
++ )
3692 // wait until all threads terminate
3695 wxPuts(wxEmptyString
);
3698 static void TestJoinableThreads()
3700 wxPuts(_T("\n*** Testing a joinable thread (a loooong calculation...) ***"));
3702 // calc 10! in the background
3703 MyJoinableThread
thread(10);
3706 wxPrintf(_T("\nThread terminated with exit code %lu.\n"),
3707 (unsigned long)thread
.Wait());
3710 static void TestThreadSuspend()
3712 wxPuts(_T("\n*** Testing thread suspend/resume functions ***"));
3714 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
3718 // this is for this demo only, in a real life program we'd use another
3719 // condition variable which would be signaled from wxThread::Entry() to
3720 // tell us that the thread really started running - but here just wait a
3721 // bit and hope that it will be enough (the problem is, of course, that
3722 // the thread might still not run when we call Pause() which will result
3724 wxThread::Sleep(300);
3726 for ( size_t n
= 0; n
< 3; n
++ )
3730 wxPuts(_T("\nThread suspended"));
3733 // don't sleep but resume immediately the first time
3734 wxThread::Sleep(300);
3736 wxPuts(_T("Going to resume the thread"));
3741 wxPuts(_T("Waiting until it terminates now"));
3743 // wait until the thread terminates
3746 wxPuts(wxEmptyString
);
3749 static void TestThreadDelete()
3751 // As above, using Sleep() is only for testing here - we must use some
3752 // synchronisation object instead to ensure that the thread is still
3753 // running when we delete it - deleting a detached thread which already
3754 // terminated will lead to a crash!
3756 wxPuts(_T("\n*** Testing thread delete function ***"));
3758 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
3762 wxPuts(_T("\nDeleted a thread which didn't start to run yet."));
3764 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
3768 wxThread::Sleep(300);
3772 wxPuts(_T("\nDeleted a running thread."));
3774 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
3778 wxThread::Sleep(300);
3784 wxPuts(_T("\nDeleted a sleeping thread."));
3786 MyJoinableThread
thread3(20);
3791 wxPuts(_T("\nDeleted a joinable thread."));
3793 MyJoinableThread
thread4(2);
3796 wxThread::Sleep(300);
3800 wxPuts(_T("\nDeleted a joinable thread which already terminated."));
3802 wxPuts(wxEmptyString
);
3805 class MyWaitingThread
: public wxThread
3808 MyWaitingThread( wxMutex
*mutex
, wxCondition
*condition
)
3811 m_condition
= condition
;
3816 virtual ExitCode
Entry()
3818 wxPrintf(_T("Thread %lu has started running.\n"), GetId());
3823 wxPrintf(_T("Thread %lu starts to wait...\n"), GetId());
3827 m_condition
->Wait();
3830 wxPrintf(_T("Thread %lu finished to wait, exiting.\n"), GetId());
3838 wxCondition
*m_condition
;
3841 static void TestThreadConditions()
3844 wxCondition
condition(mutex
);
3846 // otherwise its difficult to understand which log messages pertain to
3848 //wxLogTrace(_T("thread"), _T("Local condition var is %08x, gs_cond = %08x"),
3849 // condition.GetId(), gs_cond.GetId());
3851 // create and launch threads
3852 MyWaitingThread
*threads
[10];
3855 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3857 threads
[n
] = new MyWaitingThread( &mutex
, &condition
);
3860 for ( n
= 0; n
< WXSIZEOF(threads
); n
++ )
3865 // wait until all threads run
3866 wxPuts(_T("Main thread is waiting for the other threads to start"));
3869 size_t nRunning
= 0;
3870 while ( nRunning
< WXSIZEOF(threads
) )
3876 wxPrintf(_T("Main thread: %u already running\n"), nRunning
);
3880 wxPuts(_T("Main thread: all threads started up."));
3883 wxThread::Sleep(500);
3886 // now wake one of them up
3887 wxPrintf(_T("Main thread: about to signal the condition.\n"));
3892 wxThread::Sleep(200);
3894 // wake all the (remaining) threads up, so that they can exit
3895 wxPrintf(_T("Main thread: about to broadcast the condition.\n"));
3897 condition
.Broadcast();
3899 // give them time to terminate (dirty!)
3900 wxThread::Sleep(500);
3903 #include "wx/utils.h"
3905 class MyExecThread
: public wxThread
3908 MyExecThread(const wxString
& command
) : wxThread(wxTHREAD_JOINABLE
),
3914 virtual ExitCode
Entry()
3916 return (ExitCode
)wxExecute(m_command
, wxEXEC_SYNC
);
3923 static void TestThreadExec()
3925 wxPuts(_T("*** Testing wxExecute interaction with threads ***\n"));
3927 MyExecThread
thread(_T("true"));
3930 wxPrintf(_T("Main program exit code: %ld.\n"),
3931 wxExecute(_T("false"), wxEXEC_SYNC
));
3933 wxPrintf(_T("Thread exit code: %ld.\n"), (long)thread
.Wait());
3937 #include "wx/datetime.h"
3939 class MySemaphoreThread
: public wxThread
3942 MySemaphoreThread(int i
, wxSemaphore
*sem
)
3943 : wxThread(wxTHREAD_JOINABLE
),
3950 virtual ExitCode
Entry()
3952 wxPrintf(_T("%s: Thread #%d (%ld) starting to wait for semaphore...\n"),
3953 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3957 wxPrintf(_T("%s: Thread #%d (%ld) acquired the semaphore.\n"),
3958 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3962 wxPrintf(_T("%s: Thread #%d (%ld) releasing the semaphore.\n"),
3963 wxDateTime::Now().FormatTime().c_str(), m_i
, (long)GetId());
3975 WX_DEFINE_ARRAY_PTR(wxThread
*, ArrayThreads
);
3977 static void TestSemaphore()
3979 wxPuts(_T("*** Testing wxSemaphore class. ***"));
3981 static const int SEM_LIMIT
= 3;
3983 wxSemaphore
sem(SEM_LIMIT
, SEM_LIMIT
);
3984 ArrayThreads threads
;
3986 for ( int i
= 0; i
< 3*SEM_LIMIT
; i
++ )
3988 threads
.Add(new MySemaphoreThread(i
, &sem
));
3989 threads
.Last()->Run();
3992 for ( size_t n
= 0; n
< threads
.GetCount(); n
++ )
3999 #endif // TEST_THREADS
4001 // ----------------------------------------------------------------------------
4003 // ----------------------------------------------------------------------------
4005 #ifdef TEST_SNGLINST
4006 #include "wx/snglinst.h"
4007 #endif // TEST_SNGLINST
4009 int main(int argc
, char **argv
)
4011 wxApp::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE
, "program");
4013 wxInitializer initializer
;
4016 fprintf(stderr
, "Failed to initialize the wxWidgets library, aborting.");
4021 #ifdef TEST_SNGLINST
4022 wxSingleInstanceChecker checker
;
4023 if ( checker
.Create(_T(".wxconsole.lock")) )
4025 if ( checker
.IsAnotherRunning() )
4027 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
4032 // wait some time to give time to launch another instance
4033 wxPrintf(_T("Press \"Enter\" to continue..."));
4036 else // failed to create
4038 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
4040 #endif // TEST_SNGLINST
4043 TestCmdLineConvert();
4045 #if wxUSE_CMDLINE_PARSER
4046 static const wxCmdLineEntryDesc cmdLineDesc
[] =
4048 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), _T("show this help message"),
4049 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
4050 { wxCMD_LINE_SWITCH
, _T("v"), _T("verbose"), _T("be verbose") },
4051 { wxCMD_LINE_SWITCH
, _T("q"), _T("quiet"), _T("be quiet") },
4053 { wxCMD_LINE_OPTION
, _T("o"), _T("output"), _T("output file") },
4054 { wxCMD_LINE_OPTION
, _T("i"), _T("input"), _T("input dir") },
4055 { wxCMD_LINE_OPTION
, _T("s"), _T("size"), _T("output block size"),
4056 wxCMD_LINE_VAL_NUMBER
},
4057 { wxCMD_LINE_OPTION
, _T("d"), _T("date"), _T("output file date"),
4058 wxCMD_LINE_VAL_DATE
},
4060 { wxCMD_LINE_PARAM
, NULL
, NULL
, _T("input file"),
4061 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
4067 wxChar
**wargv
= new wxChar
*[argc
+ 1];
4072 for (n
= 0; n
< argc
; n
++ )
4074 wxMB2WXbuf warg
= wxConvertMB2WX(argv
[n
]);
4075 wargv
[n
] = wxStrdup(warg
);
4082 #endif // wxUSE_UNICODE
4084 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
4088 for ( int n
= 0; n
< argc
; n
++ )
4093 #endif // wxUSE_UNICODE
4095 parser
.AddOption(_T("project_name"), _T(""), _T("full path to project file"),
4096 wxCMD_LINE_VAL_STRING
,
4097 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
4099 switch ( parser
.Parse() )
4102 wxLogMessage(_T("Help was given, terminating."));
4106 ShowCmdLine(parser
);
4110 wxLogMessage(_T("Syntax error detected, aborting."));
4113 #endif // wxUSE_CMDLINE_PARSER
4115 #endif // TEST_CMDLINE
4125 #ifdef TEST_DLLLOADER
4127 TestDllListLoaded();
4128 #endif // TEST_DLLLOADER
4132 #endif // TEST_ENVIRON
4136 #endif // TEST_EXECUTE
4138 #ifdef TEST_FILECONF
4140 #endif // TEST_FILECONF
4144 #endif // TEST_LOCALE
4147 wxPuts(_T("*** Testing wxLog ***"));
4150 for ( size_t n
= 0; n
< 8000; n
++ )
4152 s
<< (wxChar
)(_T('A') + (n
% 26));
4155 wxLogWarning(_T("The length of the string is %lu"),
4156 (unsigned long)s
.length());
4159 msg
.Printf(_T("A very very long message: '%s', the end!\n"), s
.c_str());
4161 // this one shouldn't be truncated
4164 // but this one will because log functions use fixed size buffer
4165 // (note that it doesn't need '\n' at the end neither - will be added
4167 wxLogMessage(_T("A very very long message 2: '%s', the end!"), s
.c_str());
4176 #ifdef TEST_FILENAME
4177 TestFileNameConstruction();
4178 TestFileNameMakeRelative();
4179 TestFileNameMakeAbsolute();
4180 TestFileNameSplit();
4183 TestFileNameDirManip();
4184 TestFileNameComparison();
4185 TestFileNameOperations();
4186 #endif // TEST_FILENAME
4188 #ifdef TEST_FILETIME
4193 #endif // TEST_FILETIME
4196 wxLog::AddTraceMask(FTP_TRACE_MASK
);
4197 if ( TestFtpConnect() )
4207 #if TEST_INTERACTIVE
4208 TestFtpInteractive();
4211 //else: connecting to the FTP server failed
4219 wxLog::AddTraceMask(_T("mime"));
4223 TestMimeAssociate();
4228 #ifdef TEST_INFO_FUNCTIONS
4233 #if TEST_INTERACTIVE
4237 #endif // TEST_INFO_FUNCTIONS
4239 #ifdef TEST_PATHLIST
4241 #endif // TEST_PATHLIST
4249 #endif // TEST_PRINTF
4256 #endif // TEST_REGCONF
4258 #if defined TEST_REGEX && TEST_INTERACTIVE
4259 TestRegExInteractive();
4260 #endif // defined TEST_REGEX && TEST_INTERACTIVE
4262 #ifdef TEST_REGISTRY
4264 TestRegistryAssociation();
4265 #endif // TEST_REGISTRY
4270 #endif // TEST_SOCKETS
4277 #endif // TEST_STREAMS
4279 #ifdef TEST_TEXTSTREAM
4280 TestTextInputStream();
4281 #endif // TEST_TEXTSTREAM
4284 int nCPUs
= wxThread::GetCPUCount();
4285 wxPrintf(_T("This system has %d CPUs\n"), nCPUs
);
4287 wxThread::SetConcurrency(nCPUs
);
4289 TestJoinableThreads();
4292 TestJoinableThreads();
4293 TestDetachedThreads();
4294 TestThreadSuspend();
4296 TestThreadConditions();
4300 #endif // TEST_THREADS
4304 #endif // TEST_TIMER
4306 #ifdef TEST_DATETIME
4318 TestTimeArithmetics();
4320 TestTimeSpanFormat();
4326 #if TEST_INTERACTIVE
4327 TestDateTimeInteractive();
4329 #endif // TEST_DATETIME
4331 #ifdef TEST_SCOPEGUARD
4335 #ifdef TEST_STDPATHS
4336 TestStandardPaths();
4340 wxPuts(_T("Sleeping for 3 seconds... z-z-z-z-z..."));
4342 #endif // TEST_USLEEP
4347 #endif // TEST_VCARD
4351 #endif // TEST_VOLUME
4355 TestEncodingConverter();
4356 #endif // TEST_WCHAR
4359 TestZipStreamRead();
4360 TestZipFileSystem();