1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/console/console.cpp
3 // Purpose: a sample console (as opposed to GUI) progam using wxWindows
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 1999 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
23 #error "This sample can't be compiled in GUI mode."
28 #include "wx/string.h"
32 // without this pragma, the stupid compiler precompiles #defines below so that
33 // changing them doesn't "take place" later!
38 // ----------------------------------------------------------------------------
39 // conditional compilation
40 // ----------------------------------------------------------------------------
43 A note about all these conditional compilation macros: this file is used
44 both as a test suite for various non-GUI wxWindows classes and as a
45 scratchpad for quick tests. So there are two compilation modes: if you
46 define TEST_ALL all tests are run, otherwise you may enable the individual
47 tests individually in the "#else" branch below.
50 // what to test (in alphabetic order)? uncomment the line below to do all tests
58 #define TEST_DLLLOADER
67 #define TEST_INFO_FUNCTIONS
83 // #define TEST_VCARD -- don't enable this (VZ)
89 static const bool TEST_ALL
= TRUE
;
93 static const bool TEST_ALL
= FALSE
;
96 // some tests are interactive, define this to run them
97 #ifdef TEST_INTERACTIVE
98 #undef TEST_INTERACTIVE
100 static const bool TEST_INTERACTIVE
= FALSE
;
102 static const bool TEST_INTERACTIVE
= FALSE
;
105 // ----------------------------------------------------------------------------
106 // test class for container objects
107 // ----------------------------------------------------------------------------
109 #if defined(TEST_ARRAYS) || defined(TEST_LIST)
111 class Bar
// Foo is already taken in the hash test
114 Bar(const wxString
& name
) : m_name(name
) { ms_bars
++; }
115 ~Bar() { ms_bars
--; }
117 static size_t GetNumber() { return ms_bars
; }
119 const char *GetName() const { return m_name
; }
124 static size_t ms_bars
;
127 size_t Bar::ms_bars
= 0;
129 #endif // defined(TEST_ARRAYS) || defined(TEST_LIST)
131 // ============================================================================
133 // ============================================================================
135 // ----------------------------------------------------------------------------
137 // ----------------------------------------------------------------------------
139 #if defined(TEST_STRINGS) || defined(TEST_SOCKETS)
141 // replace TABs with \t and CRs with \n
142 static wxString
MakePrintable(const wxChar
*s
)
145 (void)str
.Replace(_T("\t"), _T("\\t"));
146 (void)str
.Replace(_T("\n"), _T("\\n"));
147 (void)str
.Replace(_T("\r"), _T("\\r"));
152 #endif // MakePrintable() is used
154 // ----------------------------------------------------------------------------
155 // wxFontMapper::CharsetToEncoding
156 // ----------------------------------------------------------------------------
160 #include "wx/fontmap.h"
162 static void TestCharset()
164 static const wxChar
*charsets
[] =
166 // some vali charsets
175 // and now some bogus ones
182 for ( size_t n
= 0; n
< WXSIZEOF(charsets
); n
++ )
184 wxFontEncoding enc
= wxTheFontMapper
->CharsetToEncoding(charsets
[n
]);
185 wxPrintf(_T("Charset: %s\tEncoding: %s (%s)\n"),
187 wxTheFontMapper
->GetEncodingName(enc
).c_str(),
188 wxTheFontMapper
->GetEncodingDescription(enc
).c_str());
192 #endif // TEST_CHARSET
194 // ----------------------------------------------------------------------------
196 // ----------------------------------------------------------------------------
200 #include "wx/cmdline.h"
201 #include "wx/datetime.h"
203 #if wxUSE_CMDLINE_PARSER
205 static void ShowCmdLine(const wxCmdLineParser
& parser
)
207 wxString s
= "Input files: ";
209 size_t count
= parser
.GetParamCount();
210 for ( size_t param
= 0; param
< count
; param
++ )
212 s
<< parser
.GetParam(param
) << ' ';
216 << "Verbose:\t" << (parser
.Found("v") ? "yes" : "no") << '\n'
217 << "Quiet:\t" << (parser
.Found("q") ? "yes" : "no") << '\n';
222 if ( parser
.Found("o", &strVal
) )
223 s
<< "Output file:\t" << strVal
<< '\n';
224 if ( parser
.Found("i", &strVal
) )
225 s
<< "Input dir:\t" << strVal
<< '\n';
226 if ( parser
.Found("s", &lVal
) )
227 s
<< "Size:\t" << lVal
<< '\n';
228 if ( parser
.Found("d", &dt
) )
229 s
<< "Date:\t" << dt
.FormatISODate() << '\n';
230 if ( parser
.Found("project_name", &strVal
) )
231 s
<< "Project:\t" << strVal
<< '\n';
236 #endif // wxUSE_CMDLINE_PARSER
238 static void TestCmdLineConvert()
240 static const char *cmdlines
[] =
243 "-a \"-bstring 1\" -c\"string 2\" \"string 3\"",
244 "literal \\\" and \"\"",
247 for ( size_t n
= 0; n
< WXSIZEOF(cmdlines
); n
++ )
249 const char *cmdline
= cmdlines
[n
];
250 printf("Parsing: %s\n", cmdline
);
251 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdline
);
253 size_t count
= args
.GetCount();
254 printf("\targc = %u\n", count
);
255 for ( size_t arg
= 0; arg
< count
; arg
++ )
257 printf("\targv[%u] = %s\n", arg
, args
[arg
].c_str());
262 #endif // TEST_CMDLINE
264 // ----------------------------------------------------------------------------
266 // ----------------------------------------------------------------------------
273 static const wxChar
*ROOTDIR
= _T("/");
274 static const wxChar
*TESTDIR
= _T("/usr");
275 #elif defined(__WXMSW__)
276 static const wxChar
*ROOTDIR
= _T("c:\\");
277 static const wxChar
*TESTDIR
= _T("d:\\");
279 #error "don't know where the root directory is"
282 static void TestDirEnumHelper(wxDir
& dir
,
283 int flags
= wxDIR_DEFAULT
,
284 const wxString
& filespec
= wxEmptyString
)
288 if ( !dir
.IsOpened() )
291 bool cont
= dir
.GetFirst(&filename
, filespec
, flags
);
294 printf("\t%s\n", filename
.c_str());
296 cont
= dir
.GetNext(&filename
);
302 static void TestDirEnum()
304 puts("*** Testing wxDir::GetFirst/GetNext ***");
306 wxDir
dir(wxGetCwd());
308 puts("Enumerating everything in current directory:");
309 TestDirEnumHelper(dir
);
311 puts("Enumerating really everything in current directory:");
312 TestDirEnumHelper(dir
, wxDIR_DEFAULT
| wxDIR_DOTDOT
);
314 puts("Enumerating object files in current directory:");
315 TestDirEnumHelper(dir
, wxDIR_DEFAULT
, "*.o");
317 puts("Enumerating directories in current directory:");
318 TestDirEnumHelper(dir
, wxDIR_DIRS
);
320 puts("Enumerating files in current directory:");
321 TestDirEnumHelper(dir
, wxDIR_FILES
);
323 puts("Enumerating files including hidden in current directory:");
324 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
328 puts("Enumerating everything in root directory:");
329 TestDirEnumHelper(dir
, wxDIR_DEFAULT
);
331 puts("Enumerating directories in root directory:");
332 TestDirEnumHelper(dir
, wxDIR_DIRS
);
334 puts("Enumerating files in root directory:");
335 TestDirEnumHelper(dir
, wxDIR_FILES
);
337 puts("Enumerating files including hidden in root directory:");
338 TestDirEnumHelper(dir
, wxDIR_FILES
| wxDIR_HIDDEN
);
340 puts("Enumerating files in non existing directory:");
341 wxDir
dirNo("nosuchdir");
342 TestDirEnumHelper(dirNo
);
345 class DirPrintTraverser
: public wxDirTraverser
348 virtual wxDirTraverseResult
OnFile(const wxString
& filename
)
350 return wxDIR_CONTINUE
;
353 virtual wxDirTraverseResult
OnDir(const wxString
& dirname
)
355 wxString path
, name
, ext
;
356 wxSplitPath(dirname
, &path
, &name
, &ext
);
359 name
<< _T('.') << ext
;
362 for ( const wxChar
*p
= path
.c_str(); *p
; p
++ )
364 if ( wxIsPathSeparator(*p
) )
368 printf("%s%s\n", indent
.c_str(), name
.c_str());
370 return wxDIR_CONTINUE
;
374 static void TestDirTraverse()
376 puts("*** Testing wxDir::Traverse() ***");
380 size_t n
= wxDir::GetAllFiles(TESTDIR
, &files
);
381 printf("There are %u files under '%s'\n", n
, TESTDIR
);
384 printf("First one is '%s'\n", files
[0u].c_str());
385 printf(" last one is '%s'\n", files
[n
- 1].c_str());
388 // enum again with custom traverser
390 DirPrintTraverser traverser
;
391 dir
.Traverse(traverser
, _T(""), wxDIR_DIRS
| wxDIR_HIDDEN
);
396 // ----------------------------------------------------------------------------
398 // ----------------------------------------------------------------------------
400 #ifdef TEST_DLLLOADER
402 #include "wx/dynlib.h"
404 static void TestDllLoad()
406 #if defined(__WXMSW__)
407 static const wxChar
*LIB_NAME
= _T("kernel32.dll");
408 static const wxChar
*FUNC_NAME
= _T("lstrlenA");
409 #elif defined(__UNIX__)
410 // weird: using just libc.so does *not* work!
411 static const wxChar
*LIB_NAME
= _T("/lib/libc-2.0.7.so");
412 static const wxChar
*FUNC_NAME
= _T("strlen");
414 #error "don't know how to test wxDllLoader on this platform"
417 puts("*** testing wxDllLoader ***\n");
419 wxDllType dllHandle
= wxDllLoader::LoadLibrary(LIB_NAME
);
422 wxPrintf(_T("ERROR: failed to load '%s'.\n"), LIB_NAME
);
426 typedef int (*strlenType
)(const char *);
427 strlenType pfnStrlen
= (strlenType
)wxDllLoader::GetSymbol(dllHandle
, FUNC_NAME
);
430 wxPrintf(_T("ERROR: function '%s' wasn't found in '%s'.\n"),
431 FUNC_NAME
, LIB_NAME
);
435 if ( pfnStrlen("foo") != 3 )
437 wxPrintf(_T("ERROR: loaded function is not strlen()!\n"));
445 wxDllLoader::UnloadLibrary(dllHandle
);
449 #endif // TEST_DLLLOADER
451 // ----------------------------------------------------------------------------
453 // ----------------------------------------------------------------------------
457 #include "wx/utils.h"
459 static wxString
MyGetEnv(const wxString
& var
)
462 if ( !wxGetEnv(var
, &val
) )
465 val
= wxString(_T('\'')) + val
+ _T('\'');
470 static void TestEnvironment()
472 const wxChar
*var
= _T("wxTestVar");
474 puts("*** testing environment access functions ***");
476 printf("Initially getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
477 wxSetEnv(var
, _T("value for wxTestVar"));
478 printf("After wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
479 wxSetEnv(var
, _T("another value"));
480 printf("After 2nd wxSetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
482 printf("After wxUnsetEnv: getenv(%s) = %s\n", var
, MyGetEnv(var
).c_str());
483 printf("PATH = %s\n", MyGetEnv(_T("PATH")).c_str());
486 #endif // TEST_ENVIRON
488 // ----------------------------------------------------------------------------
490 // ----------------------------------------------------------------------------
494 #include "wx/utils.h"
496 static void TestExecute()
498 puts("*** testing wxExecute ***");
501 #define COMMAND "cat -n ../../Makefile" // "echo hi"
502 #define SHELL_COMMAND "echo hi from shell"
503 #define REDIRECT_COMMAND COMMAND // "date"
504 #elif defined(__WXMSW__)
505 #define COMMAND "command.com -c 'echo hi'"
506 #define SHELL_COMMAND "echo hi"
507 #define REDIRECT_COMMAND COMMAND
509 #error "no command to exec"
512 printf("Testing wxShell: ");
514 if ( wxShell(SHELL_COMMAND
) )
519 printf("Testing wxExecute: ");
521 if ( wxExecute(COMMAND
, TRUE
/* sync */) == 0 )
526 #if 0 // no, it doesn't work (yet?)
527 printf("Testing async wxExecute: ");
529 if ( wxExecute(COMMAND
) != 0 )
530 puts("Ok (command launched).");
535 printf("Testing wxExecute with redirection:\n");
536 wxArrayString output
;
537 if ( wxExecute(REDIRECT_COMMAND
, output
) != 0 )
543 size_t count
= output
.GetCount();
544 for ( size_t n
= 0; n
< count
; n
++ )
546 printf("\t%s\n", output
[n
].c_str());
553 #endif // TEST_EXECUTE
555 // ----------------------------------------------------------------------------
557 // ----------------------------------------------------------------------------
562 #include "wx/ffile.h"
563 #include "wx/textfile.h"
565 static void TestFileRead()
567 puts("*** wxFile read test ***");
569 wxFile
file(_T("testdata.fc"));
570 if ( file
.IsOpened() )
572 printf("File length: %lu\n", file
.Length());
574 puts("File dump:\n----------");
576 static const off_t len
= 1024;
580 off_t nRead
= file
.Read(buf
, len
);
581 if ( nRead
== wxInvalidOffset
)
583 printf("Failed to read the file.");
587 fwrite(buf
, nRead
, 1, stdout
);
597 printf("ERROR: can't open test file.\n");
603 static void TestTextFileRead()
605 puts("*** wxTextFile read test ***");
607 wxTextFile
file(_T("testdata.fc"));
610 printf("Number of lines: %u\n", file
.GetLineCount());
611 printf("Last line: '%s'\n", file
.GetLastLine().c_str());
615 puts("\nDumping the entire file:");
616 for ( s
= file
.GetFirstLine(); !file
.Eof(); s
= file
.GetNextLine() )
618 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
620 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
622 puts("\nAnd now backwards:");
623 for ( s
= file
.GetLastLine();
624 file
.GetCurrentLine() != 0;
625 s
= file
.GetPrevLine() )
627 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
629 printf("%6u: %s\n", file
.GetCurrentLine() + 1, s
.c_str());
633 printf("ERROR: can't open '%s'\n", file
.GetName());
639 static void TestFileCopy()
641 puts("*** Testing wxCopyFile ***");
643 static const wxChar
*filename1
= _T("testdata.fc");
644 static const wxChar
*filename2
= _T("test2");
645 if ( !wxCopyFile(filename1
, filename2
) )
647 puts("ERROR: failed to copy file");
651 wxFFile
f1(filename1
, "rb"),
654 if ( !f1
.IsOpened() || !f2
.IsOpened() )
656 puts("ERROR: failed to open file(s)");
661 if ( !f1
.ReadAll(&s1
) || !f2
.ReadAll(&s2
) )
663 puts("ERROR: failed to read file(s)");
667 if ( (s1
.length() != s2
.length()) ||
668 (memcmp(s1
.c_str(), s2
.c_str(), s1
.length()) != 0) )
670 puts("ERROR: copy error!");
674 puts("File was copied ok.");
680 if ( !wxRemoveFile(filename2
) )
682 puts("ERROR: failed to remove the file");
690 // ----------------------------------------------------------------------------
692 // ----------------------------------------------------------------------------
696 #include "wx/confbase.h"
697 #include "wx/fileconf.h"
699 static const struct FileConfTestData
701 const wxChar
*name
; // value name
702 const wxChar
*value
; // the value from the file
705 { _T("value1"), _T("one") },
706 { _T("value2"), _T("two") },
707 { _T("novalue"), _T("default") },
710 static void TestFileConfRead()
712 puts("*** testing wxFileConfig loading/reading ***");
714 wxFileConfig
fileconf(_T("test"), wxEmptyString
,
715 _T("testdata.fc"), wxEmptyString
,
716 wxCONFIG_USE_RELATIVE_PATH
);
718 // test simple reading
719 puts("\nReading config file:");
720 wxString
defValue(_T("default")), value
;
721 for ( size_t n
= 0; n
< WXSIZEOF(fcTestData
); n
++ )
723 const FileConfTestData
& data
= fcTestData
[n
];
724 value
= fileconf
.Read(data
.name
, defValue
);
725 printf("\t%s = %s ", data
.name
, value
.c_str());
726 if ( value
== data
.value
)
732 printf("(ERROR: should be %s)\n", data
.value
);
736 // test enumerating the entries
737 puts("\nEnumerating all root entries:");
740 bool cont
= fileconf
.GetFirstEntry(name
, dummy
);
743 printf("\t%s = %s\n",
745 fileconf
.Read(name
.c_str(), _T("ERROR")).c_str());
747 cont
= fileconf
.GetNextEntry(name
, dummy
);
751 #endif // TEST_FILECONF
753 // ----------------------------------------------------------------------------
755 // ----------------------------------------------------------------------------
759 #include "wx/filename.h"
761 static void DumpFileName(const wxFileName
& fn
)
763 wxString full
= fn
.GetFullPath();
765 wxString vol
, path
, name
, ext
;
766 wxFileName::SplitPath(full
, &vol
, &path
, &name
, &ext
);
768 wxPrintf(_T("Filename '%s' -> vol '%s', path '%s', name '%s', ext '%s'\n"),
769 full
.c_str(), vol
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
772 static struct FileNameInfo
774 const wxChar
*fullname
;
775 const wxChar
*volume
;
784 { _T("/usr/bin/ls"), _T(""), _T("/usr/bin"), _T("ls"), _T(""), TRUE
, wxPATH_UNIX
},
785 { _T("/usr/bin/"), _T(""), _T("/usr/bin"), _T(""), _T(""), TRUE
, wxPATH_UNIX
},
786 { _T("~/.zshrc"), _T(""), _T("~"), _T(".zshrc"), _T(""), TRUE
, wxPATH_UNIX
},
787 { _T("../../foo"), _T(""), _T("../.."), _T("foo"), _T(""), FALSE
, wxPATH_UNIX
},
788 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
789 { _T("~/foo.bar"), _T(""), _T("~"), _T("foo"), _T("bar"), TRUE
, wxPATH_UNIX
},
790 { _T("/foo"), _T(""), _T("/"), _T("foo"), _T(""), TRUE
, wxPATH_UNIX
},
791 { _T("Mahogany-0.60/foo.bar"), _T(""), _T("Mahogany-0.60"), _T("foo"), _T("bar"), FALSE
, wxPATH_UNIX
},
792 { _T("/tmp/wxwin.tar.bz"), _T(""), _T("/tmp"), _T("wxwin.tar"), _T("bz"), TRUE
, wxPATH_UNIX
},
794 // Windows file names
795 { _T("foo.bar"), _T(""), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
796 { _T("\\foo.bar"), _T(""), _T("\\"), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
797 { _T("c:foo.bar"), _T("c"), _T(""), _T("foo"), _T("bar"), FALSE
, wxPATH_DOS
},
798 { _T("c:\\foo.bar"), _T("c"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
799 { _T("c:\\Windows\\command.com"), _T("c"), _T("\\Windows"), _T("command"), _T("com"), TRUE
, wxPATH_DOS
},
800 { _T("\\\\server\\foo.bar"), _T("server"), _T("\\"), _T("foo"), _T("bar"), TRUE
, wxPATH_DOS
},
803 { _T("Volume:Dir:File"), _T("Volume"), _T("Dir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
804 { _T("Volume:Dir:Subdir:File"), _T("Volume"), _T("Dir:Subdir"), _T("File"), _T(""), TRUE
, wxPATH_MAC
},
805 { _T("Volume:"), _T("Volume"), _T(""), _T(""), _T(""), TRUE
, wxPATH_MAC
},
806 { _T(":Dir:File"), _T(""), _T("Dir"), _T("File"), _T(""), FALSE
, wxPATH_MAC
},
807 { _T(":File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
808 { _T("File.Ext"), _T(""), _T(""), _T("File"), _T(".Ext"), FALSE
, wxPATH_MAC
},
811 { _T("device:[dir1.dir2.dir3]file.txt"), _T("device"), _T("dir1.dir2.dir3"), _T("file"), _T("txt"), TRUE
, wxPATH_VMS
},
812 { _T("file.txt"), _T(""), _T(""), _T("file"), _T("txt"), FALSE
, wxPATH_VMS
},
815 static void TestFileNameConstruction()
817 puts("*** testing wxFileName construction ***");
819 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
821 const FileNameInfo
& fni
= filenames
[n
];
823 wxFileName
fn(fni
.fullname
, fni
.format
);
825 wxString fullname
= fn
.GetFullPath(fni
.format
);
826 if ( fullname
!= fni
.fullname
)
828 printf("ERROR: fullname should be '%s'\n", fni
.fullname
);
831 bool isAbsolute
= fn
.IsAbsolute(fni
.format
);
832 printf("'%s' is %s (%s)\n\t",
834 isAbsolute
? "absolute" : "relative",
835 isAbsolute
== fni
.isAbsolute
? "ok" : "ERROR");
837 if ( !fn
.Normalize(wxPATH_NORM_ALL
, _T(""), fni
.format
) )
839 puts("ERROR (couldn't be normalized)");
843 printf("normalized: '%s'\n", fn
.GetFullPath(fni
.format
).c_str());
850 static void TestFileNameSplit()
852 puts("*** testing wxFileName splitting ***");
854 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
856 const FileNameInfo
& fni
= filenames
[n
];
857 wxString volume
, path
, name
, ext
;
858 wxFileName::SplitPath(fni
.fullname
,
859 &volume
, &path
, &name
, &ext
, fni
.format
);
861 printf("%s -> volume = '%s', path = '%s', name = '%s', ext = '%s'",
863 volume
.c_str(), path
.c_str(), name
.c_str(), ext
.c_str());
865 if ( volume
!= fni
.volume
)
866 printf(" (ERROR: volume = '%s')", fni
.volume
);
867 if ( path
!= fni
.path
)
868 printf(" (ERROR: path = '%s')", fni
.path
);
869 if ( name
!= fni
.name
)
870 printf(" (ERROR: name = '%s')", fni
.name
);
871 if ( ext
!= fni
.ext
)
872 printf(" (ERROR: ext = '%s')", fni
.ext
);
878 static void TestFileNameTemp()
880 puts("*** testing wxFileName temp file creation ***");
882 static const char *tmpprefixes
[] =
888 "/tmp/foo/bar", // this one must be an error
891 for ( size_t n
= 0; n
< WXSIZEOF(tmpprefixes
); n
++ )
893 wxString path
= wxFileName::CreateTempFileName(tmpprefixes
[n
]);
896 printf("Prefix '%s'\t-> temp file '%s'\n",
897 tmpprefixes
[n
], path
.c_str());
899 if ( !wxRemoveFile(path
) )
901 wxLogWarning("Failed to remove temp file '%s'", path
.c_str());
907 static void TestFileNameMakeRelative()
909 puts("*** testing wxFileName::MakeRelativeTo() ***");
911 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
913 const FileNameInfo
& fni
= filenames
[n
];
915 wxFileName
fn(fni
.fullname
, fni
.format
);
917 // choose the base dir of the same format
919 switch ( fni
.format
)
931 // TODO: I don't know how this is supposed to work there
934 case wxPATH_NATIVE
: // make gcc happy
936 wxFAIL_MSG( "unexpected path format" );
939 printf("'%s' relative to '%s': ",
940 fn
.GetFullPath(fni
.format
).c_str(), base
.c_str());
942 if ( !fn
.MakeRelativeTo(base
, fni
.format
) )
948 printf("'%s'\n", fn
.GetFullPath(fni
.format
).c_str());
953 static void TestFileNameComparison()
958 static void TestFileNameOperations()
963 static void TestFileNameCwd()
968 #endif // TEST_FILENAME
970 // ----------------------------------------------------------------------------
971 // wxFileName time functions
972 // ----------------------------------------------------------------------------
976 #include <wx/filename.h>
977 #include <wx/datetime.h>
979 static void TestFileGetTimes()
981 wxFileName
fn(_T("testdata.fc"));
983 wxDateTime dtAccess
, dtMod
, dtChange
;
984 if ( !fn
.GetTimes(&dtAccess
, &dtMod
, &dtChange
) )
986 wxPrintf(_T("ERROR: GetTimes() failed.\n"));
990 static const wxChar
*fmt
= _T("%Y-%b-%d %H:%M:%S");
992 wxPrintf(_T("File times for '%s':\n"), fn
.GetFullPath().c_str());
993 wxPrintf(_T("Access: \t%s\n"), dtAccess
.Format(fmt
).c_str());
994 wxPrintf(_T("Mod/creation:\t%s\n"), dtMod
.Format(fmt
).c_str());
995 wxPrintf(_T("Change: \t%s\n"), dtChange
.Format(fmt
).c_str());
999 static void TestFileSetTimes()
1001 wxFileName
fn(_T("testdata.fc"));
1005 wxPrintf(_T("ERROR: Touch() failed.\n"));
1009 #endif // TEST_FILETIME
1011 // ----------------------------------------------------------------------------
1013 // ----------------------------------------------------------------------------
1017 #include "wx/hash.h"
1021 Foo(int n_
) { n
= n_
; count
++; }
1026 static size_t count
;
1029 size_t Foo::count
= 0;
1031 WX_DECLARE_LIST(Foo
, wxListFoos
);
1032 WX_DECLARE_HASH(Foo
, wxListFoos
, wxHashFoos
);
1034 #include "wx/listimpl.cpp"
1036 WX_DEFINE_LIST(wxListFoos
);
1038 static void TestHash()
1040 puts("*** Testing wxHashTable ***\n");
1044 hash
.DeleteContents(TRUE
);
1046 printf("Hash created: %u foos in hash, %u foos totally\n",
1047 hash
.GetCount(), Foo::count
);
1049 static const int hashTestData
[] =
1051 0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
1055 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1057 hash
.Put(hashTestData
[n
], n
, new Foo(n
));
1060 printf("Hash filled: %u foos in hash, %u foos totally\n",
1061 hash
.GetCount(), Foo::count
);
1063 puts("Hash access test:");
1064 for ( n
= 0; n
< WXSIZEOF(hashTestData
); n
++ )
1066 printf("\tGetting element with key %d, value %d: ",
1067 hashTestData
[n
], n
);
1068 Foo
*foo
= hash
.Get(hashTestData
[n
], n
);
1071 printf("ERROR, not found.\n");
1075 printf("%d (%s)\n", foo
->n
,
1076 (size_t)foo
->n
== n
? "ok" : "ERROR");
1080 printf("\nTrying to get an element not in hash: ");
1082 if ( hash
.Get(1234) || hash
.Get(1, 0) )
1084 puts("ERROR: found!");
1088 puts("ok (not found)");
1092 printf("Hash destroyed: %u foos left\n", Foo::count
);
1097 // ----------------------------------------------------------------------------
1099 // ----------------------------------------------------------------------------
1103 #include "wx/list.h"
1105 WX_DECLARE_LIST(Bar
, wxListBars
);
1106 #include "wx/listimpl.cpp"
1107 WX_DEFINE_LIST(wxListBars
);
1109 static void TestListCtor()
1111 puts("*** Testing wxList construction ***\n");
1115 list1
.Append(new Bar(_T("first")));
1116 list1
.Append(new Bar(_T("second")));
1118 printf("After 1st list creation: %u objects in the list, %u objects total.\n",
1119 list1
.GetCount(), Bar::GetNumber());
1124 printf("After 2nd list creation: %u and %u objects in the lists, %u objects total.\n",
1125 list1
.GetCount(), list2
.GetCount(), Bar::GetNumber());
1127 list1
.DeleteContents(TRUE
);
1130 printf("After list destruction: %u objects left.\n", Bar::GetNumber());
1135 // ----------------------------------------------------------------------------
1137 // ----------------------------------------------------------------------------
1141 #include "wx/intl.h"
1142 #include "wx/utils.h" // for wxSetEnv
1144 static wxLocale
gs_localeDefault(wxLANGUAGE_ENGLISH
);
1146 // find the name of the language from its value
1147 static const char *GetLangName(int lang
)
1149 static const char *languageNames
[] =
1170 "ARABIC_SAUDI_ARABIA",
1195 "CHINESE_SIMPLIFIED",
1196 "CHINESE_TRADITIONAL",
1199 "CHINESE_SINGAPORE",
1210 "ENGLISH_AUSTRALIA",
1214 "ENGLISH_CARIBBEAN",
1218 "ENGLISH_NEW_ZEALAND",
1219 "ENGLISH_PHILIPPINES",
1220 "ENGLISH_SOUTH_AFRICA",
1232 "FRENCH_LUXEMBOURG",
1241 "GERMAN_LIECHTENSTEIN",
1242 "GERMAN_LUXEMBOURG",
1283 "MALAY_BRUNEI_DARUSSALAM",
1295 "NORWEGIAN_NYNORSK",
1302 "PORTUGUESE_BRAZILIAN",
1327 "SPANISH_ARGENTINA",
1331 "SPANISH_COSTA_RICA",
1332 "SPANISH_DOMINICAN_REPUBLIC",
1334 "SPANISH_EL_SALVADOR",
1335 "SPANISH_GUATEMALA",
1339 "SPANISH_NICARAGUA",
1343 "SPANISH_PUERTO_RICO",
1346 "SPANISH_VENEZUELA",
1383 if ( (size_t)lang
< WXSIZEOF(languageNames
) )
1384 return languageNames
[lang
];
1389 static void TestDefaultLang()
1391 puts("*** Testing wxLocale::GetSystemLanguage ***");
1393 static const wxChar
*langStrings
[] =
1395 NULL
, // system default
1402 _T("de_DE.iso88591"),
1404 _T("?"), // invalid lang spec
1405 _T("klingonese"), // I bet on some systems it does exist...
1408 wxPrintf(_T("The default system encoding is %s (%d)\n"),
1409 wxLocale::GetSystemEncodingName().c_str(),
1410 wxLocale::GetSystemEncoding());
1412 for ( size_t n
= 0; n
< WXSIZEOF(langStrings
); n
++ )
1414 const char *langStr
= langStrings
[n
];
1417 // FIXME: this doesn't do anything at all under Windows, we need
1418 // to create a new wxLocale!
1419 wxSetEnv(_T("LC_ALL"), langStr
);
1422 int lang
= gs_localeDefault
.GetSystemLanguage();
1423 printf("Locale for '%s' is %s.\n",
1424 langStr
? langStr
: "system default", GetLangName(lang
));
1428 #endif // TEST_LOCALE
1430 // ----------------------------------------------------------------------------
1432 // ----------------------------------------------------------------------------
1436 #include "wx/mimetype.h"
1438 static void TestMimeEnum()
1440 wxPuts(_T("*** Testing wxMimeTypesManager::EnumAllFileTypes() ***\n"));
1442 wxArrayString mimetypes
;
1444 size_t count
= wxTheMimeTypesManager
->EnumAllFileTypes(mimetypes
);
1446 printf("*** All %u known filetypes: ***\n", count
);
1451 for ( size_t n
= 0; n
< count
; n
++ )
1453 wxFileType
*filetype
=
1454 wxTheMimeTypesManager
->GetFileTypeFromMimeType(mimetypes
[n
]);
1457 printf("nothing known about the filetype '%s'!\n",
1458 mimetypes
[n
].c_str());
1462 filetype
->GetDescription(&desc
);
1463 filetype
->GetExtensions(exts
);
1465 filetype
->GetIcon(NULL
);
1468 for ( size_t e
= 0; e
< exts
.GetCount(); e
++ )
1471 extsAll
<< _T(", ");
1475 printf("\t%s: %s (%s)\n",
1476 mimetypes
[n
].c_str(), desc
.c_str(), extsAll
.c_str());
1482 static void TestMimeOverride()
1484 wxPuts(_T("*** Testing wxMimeTypesManager additional files loading ***\n"));
1486 static const wxChar
*mailcap
= _T("/tmp/mailcap");
1487 static const wxChar
*mimetypes
= _T("/tmp/mime.types");
1489 if ( wxFile::Exists(mailcap
) )
1490 wxPrintf(_T("Loading mailcap from '%s': %s\n"),
1492 wxTheMimeTypesManager
->ReadMailcap(mailcap
) ? _T("ok") : _T("ERROR"));
1494 wxPrintf(_T("WARN: mailcap file '%s' doesn't exist, not loaded.\n"),
1497 if ( wxFile::Exists(mimetypes
) )
1498 wxPrintf(_T("Loading mime.types from '%s': %s\n"),
1500 wxTheMimeTypesManager
->ReadMimeTypes(mimetypes
) ? _T("ok") : _T("ERROR"));
1502 wxPrintf(_T("WARN: mime.types file '%s' doesn't exist, not loaded.\n"),
1508 static void TestMimeFilename()
1510 wxPuts(_T("*** Testing MIME type from filename query ***\n"));
1512 static const wxChar
*filenames
[] =
1519 for ( size_t n
= 0; n
< WXSIZEOF(filenames
); n
++ )
1521 const wxString fname
= filenames
[n
];
1522 wxString ext
= fname
.AfterLast(_T('.'));
1523 wxFileType
*ft
= wxTheMimeTypesManager
->GetFileTypeFromExtension(ext
);
1526 wxPrintf(_T("WARNING: extension '%s' is unknown.\n"), ext
.c_str());
1531 if ( !ft
->GetDescription(&desc
) )
1532 desc
= _T("<no description>");
1535 if ( !ft
->GetOpenCommand(&cmd
,
1536 wxFileType::MessageParameters(fname
, _T(""))) )
1537 cmd
= _T("<no command available>");
1539 wxPrintf(_T("To open %s (%s) do '%s'.\n"),
1540 fname
.c_str(), desc
.c_str(), cmd
.c_str());
1549 static void TestMimeAssociate()
1551 wxPuts(_T("*** Testing creation of filetype association ***\n"));
1553 wxFileTypeInfo
ftInfo(
1554 _T("application/x-xyz"),
1555 _T("xyzview '%s'"), // open cmd
1556 _T(""), // print cmd
1557 _T("XYZ File") // description
1558 _T(".xyz"), // extensions
1559 NULL
// end of extensions
1561 ftInfo
.SetShortDesc(_T("XYZFile")); // used under Win32 only
1563 wxFileType
*ft
= wxTheMimeTypesManager
->Associate(ftInfo
);
1566 wxPuts(_T("ERROR: failed to create association!"));
1570 // TODO: read it back
1579 // ----------------------------------------------------------------------------
1580 // misc information functions
1581 // ----------------------------------------------------------------------------
1583 #ifdef TEST_INFO_FUNCTIONS
1585 #include "wx/utils.h"
1587 static void TestDiskInfo()
1589 puts("*** Testing wxGetDiskSpace() ***");
1594 printf("\nEnter a directory name: ");
1595 if ( !fgets(pathname
, WXSIZEOF(pathname
), stdin
) )
1598 // kill the last '\n'
1599 pathname
[strlen(pathname
) - 1] = 0;
1601 wxLongLong total
, free
;
1602 if ( !wxGetDiskSpace(pathname
, &total
, &free
) )
1604 wxPuts(_T("ERROR: wxGetDiskSpace failed."));
1608 wxPrintf(_T("%sKb total, %sKb free on '%s'.\n"),
1609 (total
/ 1024).ToString().c_str(),
1610 (free
/ 1024).ToString().c_str(),
1616 static void TestOsInfo()
1618 puts("*** Testing OS info functions ***\n");
1621 wxGetOsVersion(&major
, &minor
);
1622 printf("Running under: %s, version %d.%d\n",
1623 wxGetOsDescription().c_str(), major
, minor
);
1625 printf("%ld free bytes of memory left.\n", wxGetFreeMemory());
1627 printf("Host name is %s (%s).\n",
1628 wxGetHostName().c_str(), wxGetFullHostName().c_str());
1633 static void TestUserInfo()
1635 puts("*** Testing user info functions ***\n");
1637 printf("User id is:\t%s\n", wxGetUserId().c_str());
1638 printf("User name is:\t%s\n", wxGetUserName().c_str());
1639 printf("Home dir is:\t%s\n", wxGetHomeDir().c_str());
1640 printf("Email address:\t%s\n", wxGetEmailAddress().c_str());
1645 #endif // TEST_INFO_FUNCTIONS
1647 // ----------------------------------------------------------------------------
1649 // ----------------------------------------------------------------------------
1651 #ifdef TEST_LONGLONG
1653 #include "wx/longlong.h"
1654 #include "wx/timer.h"
1656 // make a 64 bit number from 4 16 bit ones
1657 #define MAKE_LL(x1, x2, x3, x4) wxLongLong((x1 << 16) | x2, (x3 << 16) | x3)
1659 // get a random 64 bit number
1660 #define RAND_LL() MAKE_LL(rand(), rand(), rand(), rand())
1662 static const long testLongs
[] =
1673 #if wxUSE_LONGLONG_WX
1674 inline bool operator==(const wxLongLongWx
& a
, const wxLongLongNative
& b
)
1675 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1676 inline bool operator==(const wxLongLongNative
& a
, const wxLongLongWx
& b
)
1677 { return a
.GetHi() == b
.GetHi() && a
.GetLo() == b
.GetLo(); }
1678 #endif // wxUSE_LONGLONG_WX
1680 static void TestSpeed()
1682 static const long max
= 100000000;
1689 for ( n
= 0; n
< max
; n
++ )
1694 printf("Summing longs took %ld milliseconds.\n", sw
.Time());
1697 #if wxUSE_LONGLONG_NATIVE
1702 for ( n
= 0; n
< max
; n
++ )
1707 printf("Summing wxLongLong_t took %ld milliseconds.\n", sw
.Time());
1709 #endif // wxUSE_LONGLONG_NATIVE
1715 for ( n
= 0; n
< max
; n
++ )
1720 printf("Summing wxLongLongs took %ld milliseconds.\n", sw
.Time());
1724 static void TestLongLongConversion()
1726 puts("*** Testing wxLongLong conversions ***\n");
1730 for ( size_t n
= 0; n
< 100000; n
++ )
1734 #if wxUSE_LONGLONG_NATIVE
1735 wxLongLongNative
b(a
.GetHi(), a
.GetLo());
1737 wxASSERT_MSG( a
== b
, "conversions failure" );
1739 puts("Can't do it without native long long type, test skipped.");
1742 #endif // wxUSE_LONGLONG_NATIVE
1744 if ( !(nTested
% 1000) )
1756 static void TestMultiplication()
1758 puts("*** Testing wxLongLong multiplication ***\n");
1762 for ( size_t n
= 0; n
< 100000; n
++ )
1767 #if wxUSE_LONGLONG_NATIVE
1768 wxLongLongNative
aa(a
.GetHi(), a
.GetLo());
1769 wxLongLongNative
bb(b
.GetHi(), b
.GetLo());
1771 wxASSERT_MSG( a
*b
== aa
*bb
, "multiplication failure" );
1772 #else // !wxUSE_LONGLONG_NATIVE
1773 puts("Can't do it without native long long type, test skipped.");
1776 #endif // wxUSE_LONGLONG_NATIVE
1778 if ( !(nTested
% 1000) )
1790 static void TestDivision()
1792 puts("*** Testing wxLongLong division ***\n");
1796 for ( size_t n
= 0; n
< 100000; n
++ )
1798 // get a random wxLongLong (shifting by 12 the MSB ensures that the
1799 // multiplication will not overflow)
1800 wxLongLong ll
= MAKE_LL((rand() >> 12), rand(), rand(), rand());
1802 // get a random long (not wxLongLong for now) to divide it with
1807 #if wxUSE_LONGLONG_NATIVE
1808 wxLongLongNative
m(ll
.GetHi(), ll
.GetLo());
1810 wxLongLongNative p
= m
/ l
, s
= m
% l
;
1811 wxASSERT_MSG( q
== p
&& r
== s
, "division failure" );
1812 #else // !wxUSE_LONGLONG_NATIVE
1813 // verify the result
1814 wxASSERT_MSG( ll
== q
*l
+ r
, "division failure" );
1815 #endif // wxUSE_LONGLONG_NATIVE
1817 if ( !(nTested
% 1000) )
1829 static void TestAddition()
1831 puts("*** Testing wxLongLong addition ***\n");
1835 for ( size_t n
= 0; n
< 100000; n
++ )
1841 #if wxUSE_LONGLONG_NATIVE
1842 wxASSERT_MSG( c
== wxLongLongNative(a
.GetHi(), a
.GetLo()) +
1843 wxLongLongNative(b
.GetHi(), b
.GetLo()),
1844 "addition failure" );
1845 #else // !wxUSE_LONGLONG_NATIVE
1846 wxASSERT_MSG( c
- b
== a
, "addition failure" );
1847 #endif // wxUSE_LONGLONG_NATIVE
1849 if ( !(nTested
% 1000) )
1861 static void TestBitOperations()
1863 puts("*** Testing wxLongLong bit operation ***\n");
1867 for ( size_t n
= 0; n
< 100000; n
++ )
1871 #if wxUSE_LONGLONG_NATIVE
1872 for ( size_t n
= 0; n
< 33; n
++ )
1875 #else // !wxUSE_LONGLONG_NATIVE
1876 puts("Can't do it without native long long type, test skipped.");
1879 #endif // wxUSE_LONGLONG_NATIVE
1881 if ( !(nTested
% 1000) )
1893 static void TestLongLongComparison()
1895 #if wxUSE_LONGLONG_WX
1896 puts("*** Testing wxLongLong comparison ***\n");
1898 static const long ls
[2] =
1904 wxLongLongWx lls
[2];
1908 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1912 for ( size_t m
= 0; m
< WXSIZEOF(lls
); m
++ )
1914 res
= lls
[m
] > testLongs
[n
];
1915 printf("0x%lx > 0x%lx is %s (%s)\n",
1916 ls
[m
], testLongs
[n
], res
? "true" : "false",
1917 res
== (ls
[m
] > testLongs
[n
]) ? "ok" : "ERROR");
1919 res
= lls
[m
] < testLongs
[n
];
1920 printf("0x%lx < 0x%lx is %s (%s)\n",
1921 ls
[m
], testLongs
[n
], res
? "true" : "false",
1922 res
== (ls
[m
] < testLongs
[n
]) ? "ok" : "ERROR");
1924 res
= lls
[m
] == testLongs
[n
];
1925 printf("0x%lx == 0x%lx is %s (%s)\n",
1926 ls
[m
], testLongs
[n
], res
? "true" : "false",
1927 res
== (ls
[m
] == testLongs
[n
]) ? "ok" : "ERROR");
1930 #endif // wxUSE_LONGLONG_WX
1933 static void TestLongLongPrint()
1935 wxPuts(_T("*** Testing wxLongLong printing ***\n"));
1937 for ( size_t n
= 0; n
< WXSIZEOF(testLongs
); n
++ )
1939 wxLongLong ll
= testLongs
[n
];
1940 wxPrintf(_T("%ld == %s\n"), testLongs
[n
], ll
.ToString().c_str());
1943 wxLongLong
ll(0x12345678, 0x87654321);
1944 wxPrintf(_T("0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1947 wxPrintf(_T("-0x1234567887654321 = %s\n"), ll
.ToString().c_str());
1953 #endif // TEST_LONGLONG
1955 // ----------------------------------------------------------------------------
1957 // ----------------------------------------------------------------------------
1959 #ifdef TEST_PATHLIST
1961 static void TestPathList()
1963 puts("*** Testing wxPathList ***\n");
1965 wxPathList pathlist
;
1966 pathlist
.AddEnvList("PATH");
1967 wxString path
= pathlist
.FindValidPath("ls");
1970 printf("ERROR: command not found in the path.\n");
1974 printf("Command found in the path as '%s'.\n", path
.c_str());
1978 #endif // TEST_PATHLIST
1980 // ----------------------------------------------------------------------------
1981 // regular expressions
1982 // ----------------------------------------------------------------------------
1986 #include "wx/regex.h"
1988 static void TestRegExCompile()
1990 wxPuts(_T("*** Testing RE compilation ***\n"));
1992 static struct RegExCompTestData
1994 const wxChar
*pattern
;
1996 } regExCompTestData
[] =
1998 { _T("foo"), TRUE
},
1999 { _T("foo("), FALSE
},
2000 { _T("foo(bar"), FALSE
},
2001 { _T("foo(bar)"), TRUE
},
2002 { _T("foo["), FALSE
},
2003 { _T("foo[bar"), FALSE
},
2004 { _T("foo[bar]"), TRUE
},
2005 { _T("foo{"), TRUE
},
2006 { _T("foo{1"), FALSE
},
2007 { _T("foo{bar"), TRUE
},
2008 { _T("foo{1}"), TRUE
},
2009 { _T("foo{1,2}"), TRUE
},
2010 { _T("foo{bar}"), TRUE
},
2011 { _T("foo*"), TRUE
},
2012 { _T("foo**"), FALSE
},
2013 { _T("foo+"), TRUE
},
2014 { _T("foo++"), FALSE
},
2015 { _T("foo?"), TRUE
},
2016 { _T("foo??"), FALSE
},
2017 { _T("foo?+"), FALSE
},
2021 for ( size_t n
= 0; n
< WXSIZEOF(regExCompTestData
); n
++ )
2023 const RegExCompTestData
& data
= regExCompTestData
[n
];
2024 bool ok
= re
.Compile(data
.pattern
);
2026 wxPrintf(_T("'%s' is %sa valid RE (%s)\n"),
2028 ok
? _T("") : _T("not "),
2029 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2033 static void TestRegExMatch()
2035 wxPuts(_T("*** Testing RE matching ***\n"));
2037 static struct RegExMatchTestData
2039 const wxChar
*pattern
;
2042 } regExMatchTestData
[] =
2044 { _T("foo"), _T("bar"), FALSE
},
2045 { _T("foo"), _T("foobar"), TRUE
},
2046 { _T("^foo"), _T("foobar"), TRUE
},
2047 { _T("^foo"), _T("barfoo"), FALSE
},
2048 { _T("bar$"), _T("barbar"), TRUE
},
2049 { _T("bar$"), _T("barbar "), FALSE
},
2052 for ( size_t n
= 0; n
< WXSIZEOF(regExMatchTestData
); n
++ )
2054 const RegExMatchTestData
& data
= regExMatchTestData
[n
];
2056 wxRegEx
re(data
.pattern
);
2057 bool ok
= re
.Matches(data
.text
);
2059 wxPrintf(_T("'%s' %s %s (%s)\n"),
2061 ok
? _T("matches") : _T("doesn't match"),
2063 ok
== data
.correct
? _T("ok") : _T("ERROR"));
2067 static void TestRegExSubmatch()
2069 wxPuts(_T("*** Testing RE subexpressions ***\n"));
2071 wxRegEx
re(_T("([[:alpha:]]+) ([[:alpha:]]+) ([[:digit:]]+).*([[:digit:]]+)$"));
2072 if ( !re
.IsValid() )
2074 wxPuts(_T("ERROR: compilation failed."));
2078 wxString text
= _T("Fri Jul 13 18:37:52 CEST 2001");
2080 if ( !re
.Matches(text
) )
2082 wxPuts(_T("ERROR: match expected."));
2086 wxPrintf(_T("Entire match: %s\n"), re
.GetMatch(text
).c_str());
2088 wxPrintf(_T("Date: %s/%s/%s, wday: %s\n"),
2089 re
.GetMatch(text
, 3).c_str(),
2090 re
.GetMatch(text
, 2).c_str(),
2091 re
.GetMatch(text
, 4).c_str(),
2092 re
.GetMatch(text
, 1).c_str());
2096 static void TestRegExReplacement()
2098 wxPuts(_T("*** Testing RE replacement ***"));
2100 static struct RegExReplTestData
2104 const wxChar
*result
;
2106 } regExReplTestData
[] =
2108 { _T("foo123"), _T("bar"), _T("bar"), 1 },
2109 { _T("foo123"), _T("\\2\\1"), _T("123foo"), 1 },
2110 { _T("foo_123"), _T("\\2\\1"), _T("123foo"), 1 },
2111 { _T("123foo"), _T("bar"), _T("123foo"), 0 },
2112 { _T("123foo456foo"), _T("&&"), _T("123foo456foo456foo"), 1 },
2113 { _T("foo123foo123"), _T("bar"), _T("barbar"), 2 },
2114 { _T("foo123_foo456_foo789"), _T("bar"), _T("bar_bar_bar"), 3 },
2117 const wxChar
*pattern
= _T("([a-z]+)[^0-9]*([0-9]+)");
2118 wxRegEx
re(pattern
);
2120 wxPrintf(_T("Using pattern '%s' for replacement.\n"), pattern
);
2122 for ( size_t n
= 0; n
< WXSIZEOF(regExReplTestData
); n
++ )
2124 const RegExReplTestData
& data
= regExReplTestData
[n
];
2126 wxString text
= data
.text
;
2127 size_t nRepl
= re
.Replace(&text
, data
.repl
);
2129 wxPrintf(_T("%s =~ s/RE/%s/g: %u match%s, result = '%s' ("),
2130 data
.text
, data
.repl
,
2131 nRepl
, nRepl
== 1 ? _T("") : _T("es"),
2133 if ( text
== data
.result
&& nRepl
== data
.count
)
2139 wxPrintf(_T("ERROR: should be %u and '%s')\n"),
2140 data
.count
, data
.result
);
2145 static void TestRegExInteractive()
2147 wxPuts(_T("*** Testing RE interactively ***"));
2152 printf("\nEnter a pattern: ");
2153 if ( !fgets(pattern
, WXSIZEOF(pattern
), stdin
) )
2156 // kill the last '\n'
2157 pattern
[strlen(pattern
) - 1] = 0;
2160 if ( !re
.Compile(pattern
) )
2168 printf("Enter text to match: ");
2169 if ( !fgets(text
, WXSIZEOF(text
), stdin
) )
2172 // kill the last '\n'
2173 text
[strlen(text
) - 1] = 0;
2175 if ( !re
.Matches(text
) )
2177 printf("No match.\n");
2181 printf("Pattern matches at '%s'\n", re
.GetMatch(text
).c_str());
2184 for ( size_t n
= 1; ; n
++ )
2186 if ( !re
.GetMatch(&start
, &len
, n
) )
2191 printf("Subexpr %u matched '%s'\n",
2192 n
, wxString(text
+ start
, len
).c_str());
2199 #endif // TEST_REGEX
2201 // ----------------------------------------------------------------------------
2202 // registry and related stuff
2203 // ----------------------------------------------------------------------------
2205 // this is for MSW only
2208 #undef TEST_REGISTRY
2213 #include "wx/confbase.h"
2214 #include "wx/msw/regconf.h"
2216 static void TestRegConfWrite()
2218 wxRegConfig
regconf(_T("console"), _T("wxwindows"));
2219 regconf
.Write(_T("Hello"), wxString(_T("world")));
2222 #endif // TEST_REGCONF
2224 #ifdef TEST_REGISTRY
2226 #include "wx/msw/registry.h"
2228 // I chose this one because I liked its name, but it probably only exists under
2230 static const wxChar
*TESTKEY
=
2231 _T("HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Control\\CrashControl");
2233 static void TestRegistryRead()
2235 puts("*** testing registry reading ***");
2237 wxRegKey
key(TESTKEY
);
2238 printf("The test key name is '%s'.\n", key
.GetName().c_str());
2241 puts("ERROR: test key can't be opened, aborting test.");
2246 size_t nSubKeys
, nValues
;
2247 if ( key
.GetKeyInfo(&nSubKeys
, NULL
, &nValues
, NULL
) )
2249 printf("It has %u subkeys and %u values.\n", nSubKeys
, nValues
);
2252 printf("Enumerating values:\n");
2256 bool cont
= key
.GetFirstValue(value
, dummy
);
2259 printf("Value '%s': type ", value
.c_str());
2260 switch ( key
.GetValueType(value
) )
2262 case wxRegKey::Type_None
: printf("ERROR (none)"); break;
2263 case wxRegKey::Type_String
: printf("SZ"); break;
2264 case wxRegKey::Type_Expand_String
: printf("EXPAND_SZ"); break;
2265 case wxRegKey::Type_Binary
: printf("BINARY"); break;
2266 case wxRegKey::Type_Dword
: printf("DWORD"); break;
2267 case wxRegKey::Type_Multi_String
: printf("MULTI_SZ"); break;
2268 default: printf("other (unknown)"); break;
2271 printf(", value = ");
2272 if ( key
.IsNumericValue(value
) )
2275 key
.QueryValue(value
, &val
);
2281 key
.QueryValue(value
, val
);
2282 printf("'%s'", val
.c_str());
2284 key
.QueryRawValue(value
, val
);
2285 printf(" (raw value '%s')", val
.c_str());
2290 cont
= key
.GetNextValue(value
, dummy
);
2294 static void TestRegistryAssociation()
2297 The second call to deleteself genertaes an error message, with a
2298 messagebox saying .flo is crucial to system operation, while the .ddf
2299 call also fails, but with no error message
2304 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2306 key
= "ddxf_auto_file" ;
2307 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2309 key
= "ddxf_auto_file" ;
2310 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2313 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2315 key
= "program \"%1\"" ;
2317 key
.SetName("HKEY_CLASSES_ROOT\\.ddf" );
2319 key
.SetName("HKEY_CLASSES_ROOT\\.flo" );
2321 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\DefaultIcon");
2323 key
.SetName("HKEY_CLASSES_ROOT\\ddxf_auto_file\\shell\\open\\command");
2327 #endif // TEST_REGISTRY
2329 // ----------------------------------------------------------------------------
2331 // ----------------------------------------------------------------------------
2335 #include "wx/socket.h"
2336 #include "wx/protocol/protocol.h"
2337 #include "wx/protocol/http.h"
2339 static void TestSocketServer()
2341 puts("*** Testing wxSocketServer ***\n");
2343 static const int PORT
= 3000;
2348 wxSocketServer
*server
= new wxSocketServer(addr
);
2349 if ( !server
->Ok() )
2351 puts("ERROR: failed to bind");
2358 printf("Server: waiting for connection on port %d...\n", PORT
);
2360 wxSocketBase
*socket
= server
->Accept();
2363 puts("ERROR: wxSocketServer::Accept() failed.");
2367 puts("Server: got a client.");
2369 server
->SetTimeout(60); // 1 min
2371 while ( socket
->IsConnected() )
2377 if ( socket
->Read(&ch
, sizeof(ch
)).Error() )
2379 // don't log error if the client just close the connection
2380 if ( socket
->IsConnected() )
2382 puts("ERROR: in wxSocket::Read.");
2402 printf("Server: got '%s'.\n", s
.c_str());
2403 if ( s
== _T("bye") )
2410 socket
->Write(s
.MakeUpper().c_str(), s
.length());
2411 socket
->Write("\r\n", 2);
2412 printf("Server: wrote '%s'.\n", s
.c_str());
2415 puts("Server: lost a client.");
2420 // same as "delete server" but is consistent with GUI programs
2424 static void TestSocketClient()
2426 puts("*** Testing wxSocketClient ***\n");
2428 static const char *hostname
= "www.wxwindows.org";
2431 addr
.Hostname(hostname
);
2434 printf("--- Attempting to connect to %s:80...\n", hostname
);
2436 wxSocketClient client
;
2437 if ( !client
.Connect(addr
) )
2439 printf("ERROR: failed to connect to %s\n", hostname
);
2443 printf("--- Connected to %s:%u...\n",
2444 addr
.Hostname().c_str(), addr
.Service());
2448 // could use simply "GET" here I suppose
2450 wxString::Format("GET http://%s/\r\n", hostname
);
2451 client
.Write(cmdGet
, cmdGet
.length());
2452 printf("--- Sent command '%s' to the server\n",
2453 MakePrintable(cmdGet
).c_str());
2454 client
.Read(buf
, WXSIZEOF(buf
));
2455 printf("--- Server replied:\n%s", buf
);
2459 #endif // TEST_SOCKETS
2461 // ----------------------------------------------------------------------------
2463 // ----------------------------------------------------------------------------
2467 #include "wx/protocol/ftp.h"
2471 #define FTP_ANONYMOUS
2473 #ifdef FTP_ANONYMOUS
2474 static const char *directory
= "/pub";
2475 static const char *filename
= "welcome.msg";
2477 static const char *directory
= "/etc";
2478 static const char *filename
= "issue";
2481 static bool TestFtpConnect()
2483 puts("*** Testing FTP connect ***");
2485 #ifdef FTP_ANONYMOUS
2486 static const char *hostname
= "ftp.wxwindows.org";
2488 printf("--- Attempting to connect to %s:21 anonymously...\n", hostname
);
2489 #else // !FTP_ANONYMOUS
2490 static const char *hostname
= "localhost";
2493 fgets(user
, WXSIZEOF(user
), stdin
);
2494 user
[strlen(user
) - 1] = '\0'; // chop off '\n'
2498 printf("Password for %s: ", password
);
2499 fgets(password
, WXSIZEOF(password
), stdin
);
2500 password
[strlen(password
) - 1] = '\0'; // chop off '\n'
2501 ftp
.SetPassword(password
);
2503 printf("--- Attempting to connect to %s:21 as %s...\n", hostname
, user
);
2504 #endif // FTP_ANONYMOUS/!FTP_ANONYMOUS
2506 if ( !ftp
.Connect(hostname
) )
2508 printf("ERROR: failed to connect to %s\n", hostname
);
2514 printf("--- Connected to %s, current directory is '%s'\n",
2515 hostname
, ftp
.Pwd().c_str());
2521 // test (fixed?) wxFTP bug with wu-ftpd >= 2.6.0?
2522 static void TestFtpWuFtpd()
2525 static const char *hostname
= "ftp.eudora.com";
2526 if ( !ftp
.Connect(hostname
) )
2528 printf("ERROR: failed to connect to %s\n", hostname
);
2532 static const char *filename
= "eudora/pubs/draft-gellens-submit-09.txt";
2533 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2536 printf("ERROR: couldn't get input stream for %s\n", filename
);
2540 size_t size
= in
->StreamSize();
2541 printf("Reading file %s (%u bytes)...", filename
, size
);
2543 char *data
= new char[size
];
2544 if ( !in
->Read(data
, size
) )
2546 puts("ERROR: read error");
2550 printf("Successfully retrieved the file.\n");
2559 static void TestFtpList()
2561 puts("*** Testing wxFTP file listing ***\n");
2564 if ( !ftp
.ChDir(directory
) )
2566 printf("ERROR: failed to cd to %s\n", directory
);
2569 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2571 // test NLIST and LIST
2572 wxArrayString files
;
2573 if ( !ftp
.GetFilesList(files
) )
2575 puts("ERROR: failed to get NLIST of files");
2579 printf("Brief list of files under '%s':\n", ftp
.Pwd().c_str());
2580 size_t count
= files
.GetCount();
2581 for ( size_t n
= 0; n
< count
; n
++ )
2583 printf("\t%s\n", files
[n
].c_str());
2585 puts("End of the file list");
2588 if ( !ftp
.GetDirList(files
) )
2590 puts("ERROR: failed to get LIST of files");
2594 printf("Detailed list of files under '%s':\n", ftp
.Pwd().c_str());
2595 size_t count
= files
.GetCount();
2596 for ( size_t n
= 0; n
< count
; n
++ )
2598 printf("\t%s\n", files
[n
].c_str());
2600 puts("End of the file list");
2603 if ( !ftp
.ChDir(_T("..")) )
2605 puts("ERROR: failed to cd to ..");
2608 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2611 static void TestFtpDownload()
2613 puts("*** Testing wxFTP download ***\n");
2616 wxInputStream
*in
= ftp
.GetInputStream(filename
);
2619 printf("ERROR: couldn't get input stream for %s\n", filename
);
2623 size_t size
= in
->StreamSize();
2624 printf("Reading file %s (%u bytes)...", filename
, size
);
2627 char *data
= new char[size
];
2628 if ( !in
->Read(data
, size
) )
2630 puts("ERROR: read error");
2634 printf("\nContents of %s:\n%s\n", filename
, data
);
2642 static void TestFtpFileSize()
2644 puts("*** Testing FTP SIZE command ***");
2646 if ( !ftp
.ChDir(directory
) )
2648 printf("ERROR: failed to cd to %s\n", directory
);
2651 printf("Current directory is '%s'\n", ftp
.Pwd().c_str());
2653 if ( ftp
.FileExists(filename
) )
2655 int size
= ftp
.GetFileSize(filename
);
2657 printf("ERROR: couldn't get size of '%s'\n", filename
);
2659 printf("Size of '%s' is %d bytes.\n", filename
, size
);
2663 printf("ERROR: '%s' doesn't exist\n", filename
);
2667 static void TestFtpMisc()
2669 puts("*** Testing miscellaneous wxFTP functions ***");
2671 if ( ftp
.SendCommand("STAT") != '2' )
2673 puts("ERROR: STAT failed");
2677 printf("STAT returned:\n\n%s\n", ftp
.GetLastResult().c_str());
2680 if ( ftp
.SendCommand("HELP SITE") != '2' )
2682 puts("ERROR: HELP SITE failed");
2686 printf("The list of site-specific commands:\n\n%s\n",
2687 ftp
.GetLastResult().c_str());
2691 static void TestFtpInteractive()
2693 puts("\n*** Interactive wxFTP test ***");
2699 printf("Enter FTP command: ");
2700 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
2703 // kill the last '\n'
2704 buf
[strlen(buf
) - 1] = 0;
2706 // special handling of LIST and NLST as they require data connection
2707 wxString
start(buf
, 4);
2709 if ( start
== "LIST" || start
== "NLST" )
2712 if ( strlen(buf
) > 4 )
2715 wxArrayString files
;
2716 if ( !ftp
.GetList(files
, wildcard
, start
== "LIST") )
2718 printf("ERROR: failed to get %s of files\n", start
.c_str());
2722 printf("--- %s of '%s' under '%s':\n",
2723 start
.c_str(), wildcard
.c_str(), ftp
.Pwd().c_str());
2724 size_t count
= files
.GetCount();
2725 for ( size_t n
= 0; n
< count
; n
++ )
2727 printf("\t%s\n", files
[n
].c_str());
2729 puts("--- End of the file list");
2734 char ch
= ftp
.SendCommand(buf
);
2735 printf("Command %s", ch
? "succeeded" : "failed");
2738 printf(" (return code %c)", ch
);
2741 printf(", server reply:\n%s\n\n", ftp
.GetLastResult().c_str());
2745 puts("\n*** done ***");
2748 static void TestFtpUpload()
2750 puts("*** Testing wxFTP uploading ***\n");
2753 static const char *file1
= "test1";
2754 static const char *file2
= "test2";
2755 wxOutputStream
*out
= ftp
.GetOutputStream(file1
);
2758 printf("--- Uploading to %s ---\n", file1
);
2759 out
->Write("First hello", 11);
2763 // send a command to check the remote file
2764 if ( ftp
.SendCommand(wxString("STAT ") + file1
) != '2' )
2766 printf("ERROR: STAT %s failed\n", file1
);
2770 printf("STAT %s returned:\n\n%s\n",
2771 file1
, ftp
.GetLastResult().c_str());
2774 out
= ftp
.GetOutputStream(file2
);
2777 printf("--- Uploading to %s ---\n", file1
);
2778 out
->Write("Second hello", 12);
2785 // ----------------------------------------------------------------------------
2787 // ----------------------------------------------------------------------------
2791 #include "wx/wfstream.h"
2792 #include "wx/mstream.h"
2794 static void TestFileStream()
2796 puts("*** Testing wxFileInputStream ***");
2798 static const wxChar
*filename
= _T("testdata.fs");
2800 wxFileOutputStream
fsOut(filename
);
2801 fsOut
.Write("foo", 3);
2804 wxFileInputStream
fsIn(filename
);
2805 printf("File stream size: %u\n", fsIn
.GetSize());
2806 while ( !fsIn
.Eof() )
2808 putchar(fsIn
.GetC());
2811 if ( !wxRemoveFile(filename
) )
2813 printf("ERROR: failed to remove the file '%s'.\n", filename
);
2816 puts("\n*** wxFileInputStream test done ***");
2819 static void TestMemoryStream()
2821 puts("*** Testing wxMemoryInputStream ***");
2824 wxStrncpy(buf
, _T("Hello, stream!"), WXSIZEOF(buf
));
2826 wxMemoryInputStream
memInpStream(buf
, wxStrlen(buf
));
2827 printf(_T("Memory stream size: %u\n"), memInpStream
.GetSize());
2828 while ( !memInpStream
.Eof() )
2830 putchar(memInpStream
.GetC());
2833 puts("\n*** wxMemoryInputStream test done ***");
2836 #endif // TEST_STREAMS
2838 // ----------------------------------------------------------------------------
2840 // ----------------------------------------------------------------------------
2844 #include "wx/timer.h"
2845 #include "wx/utils.h"
2847 static void TestStopWatch()
2849 puts("*** Testing wxStopWatch ***\n");
2852 printf("Sleeping 3 seconds...");
2854 printf("\telapsed time: %ldms\n", sw
.Time());
2857 printf("Sleeping 2 more seconds...");
2859 printf("\telapsed time: %ldms\n", sw
.Time());
2862 printf("And 3 more seconds...");
2864 printf("\telapsed time: %ldms\n", sw
.Time());
2867 puts("\nChecking for 'backwards clock' bug...");
2868 for ( size_t n
= 0; n
< 70; n
++ )
2872 for ( size_t m
= 0; m
< 100000; m
++ )
2874 if ( sw
.Time() < 0 || sw2
.Time() < 0 )
2876 puts("\ntime is negative - ERROR!");
2886 #endif // TEST_TIMER
2888 // ----------------------------------------------------------------------------
2890 // ----------------------------------------------------------------------------
2894 #include "wx/vcard.h"
2896 static void DumpVObject(size_t level
, const wxVCardObject
& vcard
)
2899 wxVCardObject
*vcObj
= vcard
.GetFirstProp(&cookie
);
2903 wxString(_T('\t'), level
).c_str(),
2904 vcObj
->GetName().c_str());
2907 switch ( vcObj
->GetType() )
2909 case wxVCardObject::String
:
2910 case wxVCardObject::UString
:
2913 vcObj
->GetValue(&val
);
2914 value
<< _T('"') << val
<< _T('"');
2918 case wxVCardObject::Int
:
2921 vcObj
->GetValue(&i
);
2922 value
.Printf(_T("%u"), i
);
2926 case wxVCardObject::Long
:
2929 vcObj
->GetValue(&l
);
2930 value
.Printf(_T("%lu"), l
);
2934 case wxVCardObject::None
:
2937 case wxVCardObject::Object
:
2938 value
= _T("<node>");
2942 value
= _T("<unknown value type>");
2946 printf(" = %s", value
.c_str());
2949 DumpVObject(level
+ 1, *vcObj
);
2952 vcObj
= vcard
.GetNextProp(&cookie
);
2956 static void DumpVCardAddresses(const wxVCard
& vcard
)
2958 puts("\nShowing all addresses from vCard:\n");
2962 wxVCardAddress
*addr
= vcard
.GetFirstAddress(&cookie
);
2966 int flags
= addr
->GetFlags();
2967 if ( flags
& wxVCardAddress::Domestic
)
2969 flagsStr
<< _T("domestic ");
2971 if ( flags
& wxVCardAddress::Intl
)
2973 flagsStr
<< _T("international ");
2975 if ( flags
& wxVCardAddress::Postal
)
2977 flagsStr
<< _T("postal ");
2979 if ( flags
& wxVCardAddress::Parcel
)
2981 flagsStr
<< _T("parcel ");
2983 if ( flags
& wxVCardAddress::Home
)
2985 flagsStr
<< _T("home ");
2987 if ( flags
& wxVCardAddress::Work
)
2989 flagsStr
<< _T("work ");
2992 printf("Address %u:\n"
2994 "\tvalue = %s;%s;%s;%s;%s;%s;%s\n",
2997 addr
->GetPostOffice().c_str(),
2998 addr
->GetExtAddress().c_str(),
2999 addr
->GetStreet().c_str(),
3000 addr
->GetLocality().c_str(),
3001 addr
->GetRegion().c_str(),
3002 addr
->GetPostalCode().c_str(),
3003 addr
->GetCountry().c_str()
3007 addr
= vcard
.GetNextAddress(&cookie
);
3011 static void DumpVCardPhoneNumbers(const wxVCard
& vcard
)
3013 puts("\nShowing all phone numbers from vCard:\n");
3017 wxVCardPhoneNumber
*phone
= vcard
.GetFirstPhoneNumber(&cookie
);
3021 int flags
= phone
->GetFlags();
3022 if ( flags
& wxVCardPhoneNumber::Voice
)
3024 flagsStr
<< _T("voice ");
3026 if ( flags
& wxVCardPhoneNumber::Fax
)
3028 flagsStr
<< _T("fax ");
3030 if ( flags
& wxVCardPhoneNumber::Cellular
)
3032 flagsStr
<< _T("cellular ");
3034 if ( flags
& wxVCardPhoneNumber::Modem
)
3036 flagsStr
<< _T("modem ");
3038 if ( flags
& wxVCardPhoneNumber::Home
)
3040 flagsStr
<< _T("home ");
3042 if ( flags
& wxVCardPhoneNumber::Work
)
3044 flagsStr
<< _T("work ");
3047 printf("Phone number %u:\n"
3052 phone
->GetNumber().c_str()
3056 phone
= vcard
.GetNextPhoneNumber(&cookie
);
3060 static void TestVCardRead()
3062 puts("*** Testing wxVCard reading ***\n");
3064 wxVCard
vcard(_T("vcard.vcf"));
3065 if ( !vcard
.IsOk() )
3067 puts("ERROR: couldn't load vCard.");
3071 // read individual vCard properties
3072 wxVCardObject
*vcObj
= vcard
.GetProperty("FN");
3076 vcObj
->GetValue(&value
);
3081 value
= _T("<none>");
3084 printf("Full name retrieved directly: %s\n", value
.c_str());
3087 if ( !vcard
.GetFullName(&value
) )
3089 value
= _T("<none>");
3092 printf("Full name from wxVCard API: %s\n", value
.c_str());
3094 // now show how to deal with multiply occuring properties
3095 DumpVCardAddresses(vcard
);
3096 DumpVCardPhoneNumbers(vcard
);
3098 // and finally show all
3099 puts("\nNow dumping the entire vCard:\n"
3100 "-----------------------------\n");
3102 DumpVObject(0, vcard
);
3106 static void TestVCardWrite()
3108 puts("*** Testing wxVCard writing ***\n");
3111 if ( !vcard
.IsOk() )
3113 puts("ERROR: couldn't create vCard.");
3118 vcard
.SetName("Zeitlin", "Vadim");
3119 vcard
.SetFullName("Vadim Zeitlin");
3120 vcard
.SetOrganization("wxWindows", "R&D");
3122 // just dump the vCard back
3123 puts("Entire vCard follows:\n");
3124 puts(vcard
.Write());
3128 #endif // TEST_VCARD
3130 // ----------------------------------------------------------------------------
3131 // wide char (Unicode) support
3132 // ----------------------------------------------------------------------------
3136 #include "wx/strconv.h"
3137 #include "wx/fontenc.h"
3138 #include "wx/encconv.h"
3139 #include "wx/buffer.h"
3141 static void TestUtf8()
3143 puts("*** Testing UTF8 support ***\n");
3145 static const char textInUtf8
[] =
3147 208, 157, 208, 181, 209, 129, 208, 186, 208, 176, 208, 183, 208, 176,
3148 208, 189, 208, 189, 208, 190, 32, 208, 191, 208, 190, 209, 128, 208,
3149 176, 208, 180, 208, 190, 208, 178, 208, 176, 208, 187, 32, 208, 188,
3150 208, 181, 208, 189, 209, 143, 32, 209, 129, 208, 178, 208, 190, 208,
3151 181, 208, 185, 32, 208, 186, 209, 128, 209, 131, 209, 130, 208, 181,
3152 208, 185, 209, 136, 208, 181, 208, 185, 32, 208, 189, 208, 190, 208,
3153 178, 208, 190, 209, 129, 209, 130, 209, 140, 209, 142, 0
3158 if ( wxConvUTF8
.MB2WC(wbuf
, textInUtf8
, WXSIZEOF(textInUtf8
)) <= 0 )
3160 puts("ERROR: UTF-8 decoding failed.");
3164 // using wxEncodingConverter
3166 wxEncodingConverter ec
;
3167 ec
.Init(wxFONTENCODING_UNICODE
, wxFONTENCODING_KOI8
);
3168 ec
.Convert(wbuf
, buf
);
3169 #else // using wxCSConv
3170 wxCSConv
conv(_T("koi8-r"));
3171 if ( conv
.WC2MB(buf
, wbuf
, 0 /* not needed wcslen(wbuf) */) <= 0 )
3173 puts("ERROR: conversion to KOI8-R failed.");
3178 printf("The resulting string (in koi8-r): %s\n", buf
);
3182 #endif // TEST_WCHAR
3184 // ----------------------------------------------------------------------------
3186 // ----------------------------------------------------------------------------
3190 #include "wx/filesys.h"
3191 #include "wx/fs_zip.h"
3192 #include "wx/zipstrm.h"
3194 static const wxChar
*TESTFILE_ZIP
= _T("testdata.zip");
3196 static void TestZipStreamRead()
3198 puts("*** Testing ZIP reading ***\n");
3200 static const wxChar
*filename
= _T("foo");
3201 wxZipInputStream
istr(TESTFILE_ZIP
, filename
);
3202 printf("Archive size: %u\n", istr
.GetSize());
3204 printf("Dumping the file '%s':\n", filename
);
3205 while ( !istr
.Eof() )
3207 putchar(istr
.GetC());
3211 puts("\n----- done ------");
3214 static void DumpZipDirectory(wxFileSystem
& fs
,
3215 const wxString
& dir
,
3216 const wxString
& indent
)
3218 wxString prefix
= wxString::Format(_T("%s#zip:%s"),
3219 TESTFILE_ZIP
, dir
.c_str());
3220 wxString wildcard
= prefix
+ _T("/*");
3222 wxString dirname
= fs
.FindFirst(wildcard
, wxDIR
);
3223 while ( !dirname
.empty() )
3225 if ( !dirname
.StartsWith(prefix
+ _T('/'), &dirname
) )
3227 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3232 wxPrintf(_T("%s%s\n"), indent
.c_str(), dirname
.c_str());
3234 DumpZipDirectory(fs
, dirname
,
3235 indent
+ wxString(_T(' '), 4));
3237 dirname
= fs
.FindNext();
3240 wxString filename
= fs
.FindFirst(wildcard
, wxFILE
);
3241 while ( !filename
.empty() )
3243 if ( !filename
.StartsWith(prefix
, &filename
) )
3245 wxPrintf(_T("ERROR: unexpected wxFileSystem::FindNext result\n"));
3250 wxPrintf(_T("%s%s\n"), indent
.c_str(), filename
.c_str());
3252 filename
= fs
.FindNext();
3256 static void TestZipFileSystem()
3258 puts("*** Testing ZIP file system ***\n");
3260 wxFileSystem::AddHandler(new wxZipFSHandler
);
3262 wxPrintf(_T("Dumping all files in the archive %s:\n"), TESTFILE_ZIP
);
3264 DumpZipDirectory(fs
, _T(""), wxString(_T(' '), 4));
3269 // ----------------------------------------------------------------------------
3271 // ----------------------------------------------------------------------------
3275 #include "wx/zstream.h"
3276 #include "wx/wfstream.h"
3278 static const wxChar
*FILENAME_GZ
= _T("test.gz");
3279 static const char *TEST_DATA
= "hello and hello again";
3281 static void TestZlibStreamWrite()
3283 puts("*** Testing Zlib stream reading ***\n");
3285 wxFileOutputStream
fileOutStream(FILENAME_GZ
);
3286 wxZlibOutputStream
ostr(fileOutStream
, 0);
3287 printf("Compressing the test string... ");
3288 ostr
.Write(TEST_DATA
, sizeof(TEST_DATA
));
3291 puts("(ERROR: failed)");
3298 puts("\n----- done ------");
3301 static void TestZlibStreamRead()
3303 puts("*** Testing Zlib stream reading ***\n");
3305 wxFileInputStream
fileInStream(FILENAME_GZ
);
3306 wxZlibInputStream
istr(fileInStream
);
3307 printf("Archive size: %u\n", istr
.GetSize());
3309 puts("Dumping the file:");
3310 while ( !istr
.Eof() )
3312 putchar(istr
.GetC());
3316 puts("\n----- done ------");
3321 // ----------------------------------------------------------------------------
3323 // ----------------------------------------------------------------------------
3325 #ifdef TEST_DATETIME
3329 #include "wx/date.h"
3330 #include "wx/datetime.h"
3335 wxDateTime::wxDateTime_t day
;
3336 wxDateTime::Month month
;
3338 wxDateTime::wxDateTime_t hour
, min
, sec
;
3340 wxDateTime::WeekDay wday
;
3341 time_t gmticks
, ticks
;
3343 void Init(const wxDateTime::Tm
& tm
)
3352 gmticks
= ticks
= -1;
3355 wxDateTime
DT() const
3356 { return wxDateTime(day
, month
, year
, hour
, min
, sec
); }
3358 bool SameDay(const wxDateTime::Tm
& tm
) const
3360 return day
== tm
.mday
&& month
== tm
.mon
&& year
== tm
.year
;
3363 wxString
Format() const
3366 s
.Printf("%02d:%02d:%02d %10s %02d, %4d%s",
3368 wxDateTime::GetMonthName(month
).c_str(),
3370 abs(wxDateTime::ConvertYearToBC(year
)),
3371 year
> 0 ? "AD" : "BC");
3375 wxString
FormatDate() const
3378 s
.Printf("%02d-%s-%4d%s",
3380 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3381 abs(wxDateTime::ConvertYearToBC(year
)),
3382 year
> 0 ? "AD" : "BC");
3387 static const Date testDates
[] =
3389 { 1, wxDateTime::Jan
, 1970, 00, 00, 00, 2440587.5, wxDateTime::Thu
, 0, -3600 },
3390 { 21, wxDateTime::Jan
, 2222, 00, 00, 00, 2532648.5, wxDateTime::Mon
, -1, -1 },
3391 { 29, wxDateTime::May
, 1976, 12, 00, 00, 2442928.0, wxDateTime::Sat
, 202219200, 202212000 },
3392 { 29, wxDateTime::Feb
, 1976, 00, 00, 00, 2442837.5, wxDateTime::Sun
, 194400000, 194396400 },
3393 { 1, wxDateTime::Jan
, 1900, 12, 00, 00, 2415021.0, wxDateTime::Mon
, -1, -1 },
3394 { 1, wxDateTime::Jan
, 1900, 00, 00, 00, 2415020.5, wxDateTime::Mon
, -1, -1 },
3395 { 15, wxDateTime::Oct
, 1582, 00, 00, 00, 2299160.5, wxDateTime::Fri
, -1, -1 },
3396 { 4, wxDateTime::Oct
, 1582, 00, 00, 00, 2299149.5, wxDateTime::Mon
, -1, -1 },
3397 { 1, wxDateTime::Mar
, 1, 00, 00, 00, 1721484.5, wxDateTime::Thu
, -1, -1 },
3398 { 1, wxDateTime::Jan
, 1, 00, 00, 00, 1721425.5, wxDateTime::Mon
, -1, -1 },
3399 { 31, wxDateTime::Dec
, 0, 00, 00, 00, 1721424.5, wxDateTime::Sun
, -1, -1 },
3400 { 1, wxDateTime::Jan
, 0, 00, 00, 00, 1721059.5, wxDateTime::Sat
, -1, -1 },
3401 { 12, wxDateTime::Aug
, -1234, 00, 00, 00, 1270573.5, wxDateTime::Fri
, -1, -1 },
3402 { 12, wxDateTime::Aug
, -4000, 00, 00, 00, 260313.5, wxDateTime::Sat
, -1, -1 },
3403 { 24, wxDateTime::Nov
, -4713, 00, 00, 00, -0.5, wxDateTime::Mon
, -1, -1 },
3406 // this test miscellaneous static wxDateTime functions
3407 static void TestTimeStatic()
3409 puts("\n*** wxDateTime static methods test ***");
3411 // some info about the current date
3412 int year
= wxDateTime::GetCurrentYear();
3413 printf("Current year %d is %sa leap one and has %d days.\n",
3415 wxDateTime::IsLeapYear(year
) ? "" : "not ",
3416 wxDateTime::GetNumberOfDays(year
));
3418 wxDateTime::Month month
= wxDateTime::GetCurrentMonth();
3419 printf("Current month is '%s' ('%s') and it has %d days\n",
3420 wxDateTime::GetMonthName(month
, wxDateTime::Name_Abbr
).c_str(),
3421 wxDateTime::GetMonthName(month
).c_str(),
3422 wxDateTime::GetNumberOfDays(month
));
3425 static const size_t nYears
= 5;
3426 static const size_t years
[2][nYears
] =
3428 // first line: the years to test
3429 { 1990, 1976, 2000, 2030, 1984, },
3431 // second line: TRUE if leap, FALSE otherwise
3432 { FALSE
, TRUE
, TRUE
, FALSE
, TRUE
}
3435 for ( size_t n
= 0; n
< nYears
; n
++ )
3437 int year
= years
[0][n
];
3438 bool should
= years
[1][n
] != 0,
3439 is
= wxDateTime::IsLeapYear(year
);
3441 printf("Year %d is %sa leap year (%s)\n",
3444 should
== is
? "ok" : "ERROR");
3446 wxASSERT( should
== wxDateTime::IsLeapYear(year
) );
3450 // test constructing wxDateTime objects
3451 static void TestTimeSet()
3453 puts("\n*** wxDateTime construction test ***");
3455 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3457 const Date
& d1
= testDates
[n
];
3458 wxDateTime dt
= d1
.DT();
3461 d2
.Init(dt
.GetTm());
3463 wxString s1
= d1
.Format(),
3466 printf("Date: %s == %s (%s)\n",
3467 s1
.c_str(), s2
.c_str(),
3468 s1
== s2
? "ok" : "ERROR");
3472 // test time zones stuff
3473 static void TestTimeZones()
3475 puts("\n*** wxDateTime timezone test ***");
3477 wxDateTime now
= wxDateTime::Now();
3479 printf("Current GMT time:\t%s\n", now
.Format("%c", wxDateTime::GMT0
).c_str());
3480 printf("Unix epoch (GMT):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::GMT0
).c_str());
3481 printf("Unix epoch (EST):\t%s\n", wxDateTime((time_t)0).Format("%c", wxDateTime::EST
).c_str());
3482 printf("Current time in Paris:\t%s\n", now
.Format("%c", wxDateTime::CET
).c_str());
3483 printf(" Moscow:\t%s\n", now
.Format("%c", wxDateTime::MSK
).c_str());
3484 printf(" New York:\t%s\n", now
.Format("%c", wxDateTime::EST
).c_str());
3486 wxDateTime::Tm tm
= now
.GetTm();
3487 if ( wxDateTime(tm
) != now
)
3489 printf("ERROR: got %s instead of %s\n",
3490 wxDateTime(tm
).Format().c_str(), now
.Format().c_str());
3494 // test some minimal support for the dates outside the standard range
3495 static void TestTimeRange()
3497 puts("\n*** wxDateTime out-of-standard-range dates test ***");
3499 static const char *fmt
= "%d-%b-%Y %H:%M:%S";
3501 printf("Unix epoch:\t%s\n",
3502 wxDateTime(2440587.5).Format(fmt
).c_str());
3503 printf("Feb 29, 0: \t%s\n",
3504 wxDateTime(29, wxDateTime::Feb
, 0).Format(fmt
).c_str());
3505 printf("JDN 0: \t%s\n",
3506 wxDateTime(0.0).Format(fmt
).c_str());
3507 printf("Jan 1, 1AD:\t%s\n",
3508 wxDateTime(1, wxDateTime::Jan
, 1).Format(fmt
).c_str());
3509 printf("May 29, 2099:\t%s\n",
3510 wxDateTime(29, wxDateTime::May
, 2099).Format(fmt
).c_str());
3513 static void TestTimeTicks()
3515 puts("\n*** wxDateTime ticks test ***");
3517 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3519 const Date
& d
= testDates
[n
];
3520 if ( d
.ticks
== -1 )
3523 wxDateTime dt
= d
.DT();
3524 long ticks
= (dt
.GetValue() / 1000).ToLong();
3525 printf("Ticks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3526 if ( ticks
== d
.ticks
)
3532 printf(" (ERROR: should be %ld, delta = %ld)\n",
3533 d
.ticks
, ticks
- d
.ticks
);
3536 dt
= d
.DT().ToTimezone(wxDateTime::GMT0
);
3537 ticks
= (dt
.GetValue() / 1000).ToLong();
3538 printf("GMtks of %s:\t% 10ld", d
.Format().c_str(), ticks
);
3539 if ( ticks
== d
.gmticks
)
3545 printf(" (ERROR: should be %ld, delta = %ld)\n",
3546 d
.gmticks
, ticks
- d
.gmticks
);
3553 // test conversions to JDN &c
3554 static void TestTimeJDN()
3556 puts("\n*** wxDateTime to JDN test ***");
3558 for ( size_t n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3560 const Date
& d
= testDates
[n
];
3561 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3562 double jdn
= dt
.GetJulianDayNumber();
3564 printf("JDN of %s is:\t% 15.6f", d
.Format().c_str(), jdn
);
3571 printf(" (ERROR: should be %f, delta = %f)\n",
3572 d
.jdn
, jdn
- d
.jdn
);
3577 // test week days computation
3578 static void TestTimeWDays()
3580 puts("\n*** wxDateTime weekday test ***");
3582 // test GetWeekDay()
3584 for ( n
= 0; n
< WXSIZEOF(testDates
); n
++ )
3586 const Date
& d
= testDates
[n
];
3587 wxDateTime
dt(d
.day
, d
.month
, d
.year
, d
.hour
, d
.min
, d
.sec
);
3589 wxDateTime::WeekDay wday
= dt
.GetWeekDay();
3592 wxDateTime::GetWeekDayName(wday
).c_str());
3593 if ( wday
== d
.wday
)
3599 printf(" (ERROR: should be %s)\n",
3600 wxDateTime::GetWeekDayName(d
.wday
).c_str());
3606 // test SetToWeekDay()
3607 struct WeekDateTestData
3609 Date date
; // the real date (precomputed)
3610 int nWeek
; // its week index in the month
3611 wxDateTime::WeekDay wday
; // the weekday
3612 wxDateTime::Month month
; // the month
3613 int year
; // and the year
3615 wxString
Format() const
3618 switch ( nWeek
< -1 ? -nWeek
: nWeek
)
3620 case 1: which
= "first"; break;
3621 case 2: which
= "second"; break;
3622 case 3: which
= "third"; break;
3623 case 4: which
= "fourth"; break;
3624 case 5: which
= "fifth"; break;
3626 case -1: which
= "last"; break;
3631 which
+= " from end";
3634 s
.Printf("The %s %s of %s in %d",
3636 wxDateTime::GetWeekDayName(wday
).c_str(),
3637 wxDateTime::GetMonthName(month
).c_str(),
3644 // the array data was generated by the following python program
3646 from DateTime import *
3647 from whrandom import *
3648 from string import *
3650 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3651 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3653 week = DateTimeDelta(7)
3656 year = randint(1900, 2100)
3657 month = randint(1, 12)
3658 day = randint(1, 28)
3659 dt = DateTime(year, month, day)
3660 wday = dt.day_of_week
3662 countFromEnd = choice([-1, 1])
3665 while dt.month is month:
3666 dt = dt - countFromEnd * week
3667 weekNum = weekNum + countFromEnd
3669 data = { 'day': rjust(`day`, 2), 'month': monthNames[month - 1], 'year': year, 'weekNum': rjust(`weekNum`, 2), 'wday': wdayNames[wday] }
3671 print "{ { %(day)s, wxDateTime::%(month)s, %(year)d }, %(weekNum)d, "\
3672 "wxDateTime::%(wday)s, wxDateTime::%(month)s, %(year)d }," % data
3675 static const WeekDateTestData weekDatesTestData
[] =
3677 { { 20, wxDateTime::Mar
, 2045 }, 3, wxDateTime::Mon
, wxDateTime::Mar
, 2045 },
3678 { { 5, wxDateTime::Jun
, 1985 }, -4, wxDateTime::Wed
, wxDateTime::Jun
, 1985 },
3679 { { 12, wxDateTime::Nov
, 1961 }, -3, wxDateTime::Sun
, wxDateTime::Nov
, 1961 },
3680 { { 27, wxDateTime::Feb
, 2093 }, -1, wxDateTime::Fri
, wxDateTime::Feb
, 2093 },
3681 { { 4, wxDateTime::Jul
, 2070 }, -4, wxDateTime::Fri
, wxDateTime::Jul
, 2070 },
3682 { { 2, wxDateTime::Apr
, 1906 }, -5, wxDateTime::Mon
, wxDateTime::Apr
, 1906 },
3683 { { 19, wxDateTime::Jul
, 2023 }, -2, wxDateTime::Wed
, wxDateTime::Jul
, 2023 },
3684 { { 5, wxDateTime::May
, 1958 }, -4, wxDateTime::Mon
, wxDateTime::May
, 1958 },
3685 { { 11, wxDateTime::Aug
, 1900 }, 2, wxDateTime::Sat
, wxDateTime::Aug
, 1900 },
3686 { { 14, wxDateTime::Feb
, 1945 }, 2, wxDateTime::Wed
, wxDateTime::Feb
, 1945 },
3687 { { 25, wxDateTime::Jul
, 1967 }, -1, wxDateTime::Tue
, wxDateTime::Jul
, 1967 },
3688 { { 9, wxDateTime::May
, 1916 }, -4, wxDateTime::Tue
, wxDateTime::May
, 1916 },
3689 { { 20, wxDateTime::Jun
, 1927 }, 3, wxDateTime::Mon
, wxDateTime::Jun
, 1927 },
3690 { { 2, wxDateTime::Aug
, 2000 }, 1, wxDateTime::Wed
, wxDateTime::Aug
, 2000 },
3691 { { 20, wxDateTime::Apr
, 2044 }, 3, wxDateTime::Wed
, wxDateTime::Apr
, 2044 },
3692 { { 20, wxDateTime::Feb
, 1932 }, -2, wxDateTime::Sat
, wxDateTime::Feb
, 1932 },
3693 { { 25, wxDateTime::Jul
, 2069 }, 4, wxDateTime::Thu
, wxDateTime::Jul
, 2069 },
3694 { { 3, wxDateTime::Apr
, 1925 }, 1, wxDateTime::Fri
, wxDateTime::Apr
, 1925 },
3695 { { 21, wxDateTime::Mar
, 2093 }, 3, wxDateTime::Sat
, wxDateTime::Mar
, 2093 },
3696 { { 3, wxDateTime::Dec
, 2074 }, -5, wxDateTime::Mon
, wxDateTime::Dec
, 2074 },
3699 static const char *fmt
= "%d-%b-%Y";
3702 for ( n
= 0; n
< WXSIZEOF(weekDatesTestData
); n
++ )
3704 const WeekDateTestData
& wd
= weekDatesTestData
[n
];
3706 dt
.SetToWeekDay(wd
.wday
, wd
.nWeek
, wd
.month
, wd
.year
);
3708 printf("%s is %s", wd
.Format().c_str(), dt
.Format(fmt
).c_str());
3710 const Date
& d
= wd
.date
;
3711 if ( d
.SameDay(dt
.GetTm()) )
3717 dt
.Set(d
.day
, d
.month
, d
.year
);
3719 printf(" (ERROR: should be %s)\n", dt
.Format(fmt
).c_str());
3724 // test the computation of (ISO) week numbers
3725 static void TestTimeWNumber()
3727 puts("\n*** wxDateTime week number test ***");
3729 struct WeekNumberTestData
3731 Date date
; // the date
3732 wxDateTime::wxDateTime_t week
; // the week number in the year
3733 wxDateTime::wxDateTime_t wmon
; // the week number in the month
3734 wxDateTime::wxDateTime_t wmon2
; // same but week starts with Sun
3735 wxDateTime::wxDateTime_t dnum
; // day number in the year
3738 // data generated with the following python script:
3740 from DateTime import *
3741 from whrandom import *
3742 from string import *
3744 monthNames = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]
3745 wdayNames = [ 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ]
3747 def GetMonthWeek(dt):
3748 weekNumMonth = dt.iso_week[1] - DateTime(dt.year, dt.month, 1).iso_week[1] + 1
3749 if weekNumMonth < 0:
3750 weekNumMonth = weekNumMonth + 53
3753 def GetLastSundayBefore(dt):
3754 if dt.iso_week[2] == 7:
3757 return dt - DateTimeDelta(dt.iso_week[2])
3760 year = randint(1900, 2100)
3761 month = randint(1, 12)
3762 day = randint(1, 28)
3763 dt = DateTime(year, month, day)
3764 dayNum = dt.day_of_year
3765 weekNum = dt.iso_week[1]
3766 weekNumMonth = GetMonthWeek(dt)
3769 dtSunday = GetLastSundayBefore(dt)
3771 while dtSunday >= GetLastSundayBefore(DateTime(dt.year, dt.month, 1)):
3772 weekNumMonth2 = weekNumMonth2 + 1
3773 dtSunday = dtSunday - DateTimeDelta(7)
3775 data = { 'day': rjust(`day`, 2), \
3776 'month': monthNames[month - 1], \
3778 'weekNum': rjust(`weekNum`, 2), \
3779 'weekNumMonth': weekNumMonth, \
3780 'weekNumMonth2': weekNumMonth2, \
3781 'dayNum': rjust(`dayNum`, 3) }
3783 print " { { %(day)s, "\
3784 "wxDateTime::%(month)s, "\
3787 "%(weekNumMonth)s, "\
3788 "%(weekNumMonth2)s, "\
3789 "%(dayNum)s }," % data
3792 static const WeekNumberTestData weekNumberTestDates
[] =
3794 { { 27, wxDateTime::Dec
, 1966 }, 52, 5, 5, 361 },
3795 { { 22, wxDateTime::Jul
, 1926 }, 29, 4, 4, 203 },
3796 { { 22, wxDateTime::Oct
, 2076 }, 43, 4, 4, 296 },
3797 { { 1, wxDateTime::Jul
, 1967 }, 26, 1, 1, 182 },
3798 { { 8, wxDateTime::Nov
, 2004 }, 46, 2, 2, 313 },
3799 { { 21, wxDateTime::Mar
, 1920 }, 12, 3, 4, 81 },
3800 { { 7, wxDateTime::Jan
, 1965 }, 1, 2, 2, 7 },
3801 { { 19, wxDateTime::Oct
, 1999 }, 42, 4, 4, 292 },
3802 { { 13, wxDateTime::Aug
, 1955 }, 32, 2, 2, 225 },
3803 { { 18, wxDateTime::Jul
, 2087 }, 29, 3, 3, 199 },
3804 { { 2, wxDateTime::Sep
, 2028 }, 35, 1, 1, 246 },
3805 { { 28, wxDateTime::Jul
, 1945 }, 30, 5, 4, 209 },
3806 { { 15, wxDateTime::Jun
, 1901 }, 24, 3, 3, 166 },
3807 { { 10, wxDateTime::Oct
, 1939 }, 41, 3, 2, 283 },
3808 { { 3, wxDateTime::Dec
, 1965 }, 48, 1, 1, 337 },
3809 { { 23, wxDateTime::Feb
, 1940 }, 8, 4, 4, 54 },
3810 { { 2, wxDateTime::Jan
, 1987 }, 1, 1, 1, 2 },
3811 { { 11, wxDateTime::Aug
, 2079 }, 32, 2, 2, 223 },
3812 { { 2, wxDateTime::Feb
, 2063 }, 5, 1, 1, 33 },
3813 { { 16, wxDateTime::Oct
, 1942 }, 42, 3, 3, 289 },
3816 for ( size_t n
= 0; n
< WXSIZEOF(weekNumberTestDates
); n
++ )
3818 const WeekNumberTestData
& wn
= weekNumberTestDates
[n
];
3819 const Date
& d
= wn
.date
;
3821 wxDateTime dt
= d
.DT();
3823 wxDateTime::wxDateTime_t
3824 week
= dt
.GetWeekOfYear(wxDateTime::Monday_First
),
3825 wmon
= dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
3826 wmon2
= dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
3827 dnum
= dt
.GetDayOfYear();
3829 printf("%s: the day number is %d",
3830 d
.FormatDate().c_str(), dnum
);
3831 if ( dnum
== wn
.dnum
)
3837 printf(" (ERROR: should be %d)", wn
.dnum
);
3840 printf(", week in month is %d", wmon
);
3841 if ( wmon
== wn
.wmon
)
3847 printf(" (ERROR: should be %d)", wn
.wmon
);
3850 printf(" or %d", wmon2
);
3851 if ( wmon2
== wn
.wmon2
)
3857 printf(" (ERROR: should be %d)", wn
.wmon2
);
3860 printf(", week in year is %d", week
);
3861 if ( week
== wn
.week
)
3867 printf(" (ERROR: should be %d)\n", wn
.week
);
3872 // test DST calculations
3873 static void TestTimeDST()
3875 puts("\n*** wxDateTime DST test ***");
3877 printf("DST is%s in effect now.\n\n",
3878 wxDateTime::Now().IsDST() ? "" : " not");
3880 // taken from http://www.energy.ca.gov/daylightsaving.html
3881 static const Date datesDST
[2][2004 - 1900 + 1] =
3884 { 1, wxDateTime::Apr
, 1990 },
3885 { 7, wxDateTime::Apr
, 1991 },
3886 { 5, wxDateTime::Apr
, 1992 },
3887 { 4, wxDateTime::Apr
, 1993 },
3888 { 3, wxDateTime::Apr
, 1994 },
3889 { 2, wxDateTime::Apr
, 1995 },
3890 { 7, wxDateTime::Apr
, 1996 },
3891 { 6, wxDateTime::Apr
, 1997 },
3892 { 5, wxDateTime::Apr
, 1998 },
3893 { 4, wxDateTime::Apr
, 1999 },
3894 { 2, wxDateTime::Apr
, 2000 },
3895 { 1, wxDateTime::Apr
, 2001 },
3896 { 7, wxDateTime::Apr
, 2002 },
3897 { 6, wxDateTime::Apr
, 2003 },
3898 { 4, wxDateTime::Apr
, 2004 },
3901 { 28, wxDateTime::Oct
, 1990 },
3902 { 27, wxDateTime::Oct
, 1991 },
3903 { 25, wxDateTime::Oct
, 1992 },
3904 { 31, wxDateTime::Oct
, 1993 },
3905 { 30, wxDateTime::Oct
, 1994 },
3906 { 29, wxDateTime::Oct
, 1995 },
3907 { 27, wxDateTime::Oct
, 1996 },
3908 { 26, wxDateTime::Oct
, 1997 },
3909 { 25, wxDateTime::Oct
, 1998 },
3910 { 31, wxDateTime::Oct
, 1999 },
3911 { 29, wxDateTime::Oct
, 2000 },
3912 { 28, wxDateTime::Oct
, 2001 },
3913 { 27, wxDateTime::Oct
, 2002 },
3914 { 26, wxDateTime::Oct
, 2003 },
3915 { 31, wxDateTime::Oct
, 2004 },
3920 for ( year
= 1990; year
< 2005; year
++ )
3922 wxDateTime dtBegin
= wxDateTime::GetBeginDST(year
, wxDateTime::USA
),
3923 dtEnd
= wxDateTime::GetEndDST(year
, wxDateTime::USA
);
3925 printf("DST period in the US for year %d: from %s to %s",
3926 year
, dtBegin
.Format().c_str(), dtEnd
.Format().c_str());
3928 size_t n
= year
- 1990;
3929 const Date
& dBegin
= datesDST
[0][n
];
3930 const Date
& dEnd
= datesDST
[1][n
];
3932 if ( dBegin
.SameDay(dtBegin
.GetTm()) && dEnd
.SameDay(dtEnd
.GetTm()) )
3938 printf(" (ERROR: should be %s %d to %s %d)\n",
3939 wxDateTime::GetMonthName(dBegin
.month
).c_str(), dBegin
.day
,
3940 wxDateTime::GetMonthName(dEnd
.month
).c_str(), dEnd
.day
);
3946 for ( year
= 1990; year
< 2005; year
++ )
3948 printf("DST period in Europe for year %d: from %s to %s\n",
3950 wxDateTime::GetBeginDST(year
, wxDateTime::Country_EEC
).Format().c_str(),
3951 wxDateTime::GetEndDST(year
, wxDateTime::Country_EEC
).Format().c_str());
3955 // test wxDateTime -> text conversion
3956 static void TestTimeFormat()
3958 puts("\n*** wxDateTime formatting test ***");
3960 // some information may be lost during conversion, so store what kind
3961 // of info should we recover after a round trip
3964 CompareNone
, // don't try comparing
3965 CompareBoth
, // dates and times should be identical
3966 CompareDate
, // dates only
3967 CompareTime
// time only
3972 CompareKind compareKind
;
3974 } formatTestFormats
[] =
3976 { CompareBoth
, "---> %c" },
3977 { CompareDate
, "Date is %A, %d of %B, in year %Y" },
3978 { CompareBoth
, "Date is %x, time is %X" },
3979 { CompareTime
, "Time is %H:%M:%S or %I:%M:%S %p" },
3980 { CompareNone
, "The day of year: %j, the week of year: %W" },
3981 { CompareDate
, "ISO date without separators: %4Y%2m%2d" },
3984 static const Date formatTestDates
[] =
3986 { 29, wxDateTime::May
, 1976, 18, 30, 00 },
3987 { 31, wxDateTime::Dec
, 1999, 23, 30, 00 },
3989 // this test can't work for other centuries because it uses two digit
3990 // years in formats, so don't even try it
3991 { 29, wxDateTime::May
, 2076, 18, 30, 00 },
3992 { 29, wxDateTime::Feb
, 2400, 02, 15, 25 },
3993 { 01, wxDateTime::Jan
, -52, 03, 16, 47 },
3997 // an extra test (as it doesn't depend on date, don't do it in the loop)
3998 printf("%s\n", wxDateTime::Now().Format("Our timezone is %Z").c_str());
4000 for ( size_t d
= 0; d
< WXSIZEOF(formatTestDates
) + 1; d
++ )
4004 wxDateTime dt
= d
== 0 ? wxDateTime::Now() : formatTestDates
[d
- 1].DT();
4005 for ( size_t n
= 0; n
< WXSIZEOF(formatTestFormats
); n
++ )
4007 wxString s
= dt
.Format(formatTestFormats
[n
].format
);
4008 printf("%s", s
.c_str());
4010 // what can we recover?
4011 int kind
= formatTestFormats
[n
].compareKind
;
4015 const wxChar
*result
= dt2
.ParseFormat(s
, formatTestFormats
[n
].format
);
4018 // converion failed - should it have?
4019 if ( kind
== CompareNone
)
4022 puts(" (ERROR: conversion back failed)");
4026 // should have parsed the entire string
4027 puts(" (ERROR: conversion back stopped too soon)");
4031 bool equal
= FALSE
; // suppress compilaer warning
4039 equal
= dt
.IsSameDate(dt2
);
4043 equal
= dt
.IsSameTime(dt2
);
4049 printf(" (ERROR: got back '%s' instead of '%s')\n",
4050 dt2
.Format().c_str(), dt
.Format().c_str());
4061 // test text -> wxDateTime conversion
4062 static void TestTimeParse()
4064 puts("\n*** wxDateTime parse test ***");
4066 struct ParseTestData
4073 static const ParseTestData parseTestDates
[] =
4075 { "Sat, 18 Dec 1999 00:46:40 +0100", { 18, wxDateTime::Dec
, 1999, 00, 46, 40 }, TRUE
},
4076 { "Wed, 1 Dec 1999 05:17:20 +0300", { 1, wxDateTime::Dec
, 1999, 03, 17, 20 }, TRUE
},
4079 for ( size_t n
= 0; n
< WXSIZEOF(parseTestDates
); n
++ )
4081 const char *format
= parseTestDates
[n
].format
;
4083 printf("%s => ", format
);
4086 if ( dt
.ParseRfc822Date(format
) )
4088 printf("%s ", dt
.Format().c_str());
4090 if ( parseTestDates
[n
].good
)
4092 wxDateTime dtReal
= parseTestDates
[n
].date
.DT();
4099 printf("(ERROR: should be %s)\n", dtReal
.Format().c_str());
4104 puts("(ERROR: bad format)");
4109 printf("bad format (%s)\n",
4110 parseTestDates
[n
].good
? "ERROR" : "ok");
4115 static void TestDateTimeInteractive()
4117 puts("\n*** interactive wxDateTime tests ***");
4123 printf("Enter a date: ");
4124 if ( !fgets(buf
, WXSIZEOF(buf
), stdin
) )
4127 // kill the last '\n'
4128 buf
[strlen(buf
) - 1] = 0;
4131 const char *p
= dt
.ParseDate(buf
);
4134 printf("ERROR: failed to parse the date '%s'.\n", buf
);
4140 printf("WARNING: parsed only first %u characters.\n", p
- buf
);
4143 printf("%s: day %u, week of month %u/%u, week of year %u\n",
4144 dt
.Format("%b %d, %Y").c_str(),
4146 dt
.GetWeekOfMonth(wxDateTime::Monday_First
),
4147 dt
.GetWeekOfMonth(wxDateTime::Sunday_First
),
4148 dt
.GetWeekOfYear(wxDateTime::Monday_First
));
4151 puts("\n*** done ***");
4154 static void TestTimeMS()
4156 puts("*** testing millisecond-resolution support in wxDateTime ***");
4158 wxDateTime dt1
= wxDateTime::Now(),
4159 dt2
= wxDateTime::UNow();
4161 printf("Now = %s\n", dt1
.Format("%H:%M:%S:%l").c_str());
4162 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4163 printf("Dummy loop: ");
4164 for ( int i
= 0; i
< 6000; i
++ )
4166 //for ( int j = 0; j < 10; j++ )
4169 s
.Printf("%g", sqrt(i
));
4178 dt2
= wxDateTime::UNow();
4179 printf("UNow = %s\n", dt2
.Format("%H:%M:%S:%l").c_str());
4181 printf("Loop executed in %s ms\n", (dt2
- dt1
).Format("%l").c_str());
4183 puts("\n*** done ***");
4186 static void TestTimeArithmetics()
4188 puts("\n*** testing arithmetic operations on wxDateTime ***");
4190 static const struct ArithmData
4192 ArithmData(const wxDateSpan
& sp
, const char *nam
)
4193 : span(sp
), name(nam
) { }
4197 } testArithmData
[] =
4199 ArithmData(wxDateSpan::Day(), "day"),
4200 ArithmData(wxDateSpan::Week(), "week"),
4201 ArithmData(wxDateSpan::Month(), "month"),
4202 ArithmData(wxDateSpan::Year(), "year"),
4203 ArithmData(wxDateSpan(1, 2, 3, 4), "year, 2 months, 3 weeks, 4 days"),
4206 wxDateTime
dt(29, wxDateTime::Dec
, 1999), dt1
, dt2
;
4208 for ( size_t n
= 0; n
< WXSIZEOF(testArithmData
); n
++ )
4210 wxDateSpan span
= testArithmData
[n
].span
;
4214 const char *name
= testArithmData
[n
].name
;
4215 printf("%s + %s = %s, %s - %s = %s\n",
4216 dt
.FormatISODate().c_str(), name
, dt1
.FormatISODate().c_str(),
4217 dt
.FormatISODate().c_str(), name
, dt2
.FormatISODate().c_str());
4219 printf("Going back: %s", (dt1
- span
).FormatISODate().c_str());
4220 if ( dt1
- span
== dt
)
4226 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4229 printf("Going forward: %s", (dt2
+ span
).FormatISODate().c_str());
4230 if ( dt2
+ span
== dt
)
4236 printf(" (ERROR: should be %s)\n", dt
.FormatISODate().c_str());
4239 printf("Double increment: %s", (dt2
+ 2*span
).FormatISODate().c_str());
4240 if ( dt2
+ 2*span
== dt1
)
4246 printf(" (ERROR: should be %s)\n", dt2
.FormatISODate().c_str());
4253 static void TestTimeHolidays()
4255 puts("\n*** testing wxDateTimeHolidayAuthority ***\n");
4257 wxDateTime::Tm tm
= wxDateTime(29, wxDateTime::May
, 2000).GetTm();
4258 wxDateTime
dtStart(1, tm
.mon
, tm
.year
),
4259 dtEnd
= dtStart
.GetLastMonthDay();
4261 wxDateTimeArray hol
;
4262 wxDateTimeHolidayAuthority::GetHolidaysInRange(dtStart
, dtEnd
, hol
);
4264 const wxChar
*format
= "%d-%b-%Y (%a)";
4266 printf("All holidays between %s and %s:\n",
4267 dtStart
.Format(format
).c_str(), dtEnd
.Format(format
).c_str());
4269 size_t count
= hol
.GetCount();
4270 for ( size_t n
= 0; n
< count
; n
++ )
4272 printf("\t%s\n", hol
[n
].Format(format
).c_str());
4278 static void TestTimeZoneBug()
4280 puts("\n*** testing for DST/timezone bug ***\n");
4282 wxDateTime date
= wxDateTime(1, wxDateTime::Mar
, 2000);
4283 for ( int i
= 0; i
< 31; i
++ )
4285 printf("Date %s: week day %s.\n",
4286 date
.Format(_T("%d-%m-%Y")).c_str(),
4287 date
.GetWeekDayName(date
.GetWeekDay()).c_str());
4289 date
+= wxDateSpan::Day();
4295 static void TestTimeSpanFormat()
4297 puts("\n*** wxTimeSpan tests ***");
4299 static const char *formats
[] =
4301 _T("(default) %H:%M:%S"),
4302 _T("%E weeks and %D days"),
4303 _T("%l milliseconds"),
4304 _T("(with ms) %H:%M:%S:%l"),
4305 _T("100%% of minutes is %M"), // test "%%"
4306 _T("%D days and %H hours"),
4307 _T("or also %S seconds"),
4310 wxTimeSpan
ts1(1, 2, 3, 4),
4312 for ( size_t n
= 0; n
< WXSIZEOF(formats
); n
++ )
4314 printf("ts1 = %s\tts2 = %s\n",
4315 ts1
.Format(formats
[n
]).c_str(),
4316 ts2
.Format(formats
[n
]).c_str());
4324 // test compatibility with the old wxDate/wxTime classes
4325 static void TestTimeCompatibility()
4327 puts("\n*** wxDateTime compatibility test ***");
4329 printf("wxDate for JDN 0: %s\n", wxDate(0l).FormatDate().c_str());
4330 printf("wxDate for MJD 0: %s\n", wxDate(2400000).FormatDate().c_str());
4332 double jdnNow
= wxDateTime::Now().GetJDN();
4333 long jdnMidnight
= (long)(jdnNow
- 0.5);
4334 printf("wxDate for today: %s\n", wxDate(jdnMidnight
).FormatDate().c_str());
4336 jdnMidnight
= wxDate().Set().GetJulianDate();
4337 printf("wxDateTime for today: %s\n",
4338 wxDateTime((double)(jdnMidnight
+ 0.5)).Format("%c", wxDateTime::GMT0
).c_str());
4340 int flags
= wxEUROPEAN
;//wxFULL;
4343 printf("Today is %s\n", date
.FormatDate(flags
).c_str());
4344 for ( int n
= 0; n
< 7; n
++ )
4346 printf("Previous %s is %s\n",
4347 wxDateTime::GetWeekDayName((wxDateTime::WeekDay
)n
),
4348 date
.Previous(n
+ 1).FormatDate(flags
).c_str());
4354 #endif // TEST_DATETIME
4356 // ----------------------------------------------------------------------------
4358 // ----------------------------------------------------------------------------
4362 #include "wx/thread.h"
4364 static size_t gs_counter
= (size_t)-1;
4365 static wxCriticalSection gs_critsect
;
4366 static wxCondition gs_cond
;
4368 class MyJoinableThread
: public wxThread
4371 MyJoinableThread(size_t n
) : wxThread(wxTHREAD_JOINABLE
)
4372 { m_n
= n
; Create(); }
4374 // thread execution starts here
4375 virtual ExitCode
Entry();
4381 wxThread::ExitCode
MyJoinableThread::Entry()
4383 unsigned long res
= 1;
4384 for ( size_t n
= 1; n
< m_n
; n
++ )
4388 // it's a loooong calculation :-)
4392 return (ExitCode
)res
;
4395 class MyDetachedThread
: public wxThread
4398 MyDetachedThread(size_t n
, char ch
)
4402 m_cancelled
= FALSE
;
4407 // thread execution starts here
4408 virtual ExitCode
Entry();
4411 virtual void OnExit();
4414 size_t m_n
; // number of characters to write
4415 char m_ch
; // character to write
4417 bool m_cancelled
; // FALSE if we exit normally
4420 wxThread::ExitCode
MyDetachedThread::Entry()
4423 wxCriticalSectionLocker
lock(gs_critsect
);
4424 if ( gs_counter
== (size_t)-1 )
4430 for ( size_t n
= 0; n
< m_n
; n
++ )
4432 if ( TestDestroy() )
4442 wxThread::Sleep(100);
4448 void MyDetachedThread::OnExit()
4450 wxLogTrace("thread", "Thread %ld is in OnExit", GetId());
4452 wxCriticalSectionLocker
lock(gs_critsect
);
4453 if ( !--gs_counter
&& !m_cancelled
)
4457 void TestDetachedThreads()
4459 puts("\n*** Testing detached threads ***");
4461 static const size_t nThreads
= 3;
4462 MyDetachedThread
*threads
[nThreads
];
4464 for ( n
= 0; n
< nThreads
; n
++ )
4466 threads
[n
] = new MyDetachedThread(10, 'A' + n
);
4469 threads
[0]->SetPriority(WXTHREAD_MIN_PRIORITY
);
4470 threads
[1]->SetPriority(WXTHREAD_MAX_PRIORITY
);
4472 for ( n
= 0; n
< nThreads
; n
++ )
4477 // wait until all threads terminate
4483 void TestJoinableThreads()
4485 puts("\n*** Testing a joinable thread (a loooong calculation...) ***");
4487 // calc 10! in the background
4488 MyJoinableThread
thread(10);
4491 printf("\nThread terminated with exit code %lu.\n",
4492 (unsigned long)thread
.Wait());
4495 void TestThreadSuspend()
4497 puts("\n*** Testing thread suspend/resume functions ***");
4499 MyDetachedThread
*thread
= new MyDetachedThread(15, 'X');
4503 // this is for this demo only, in a real life program we'd use another
4504 // condition variable which would be signaled from wxThread::Entry() to
4505 // tell us that the thread really started running - but here just wait a
4506 // bit and hope that it will be enough (the problem is, of course, that
4507 // the thread might still not run when we call Pause() which will result
4509 wxThread::Sleep(300);
4511 for ( size_t n
= 0; n
< 3; n
++ )
4515 puts("\nThread suspended");
4518 // don't sleep but resume immediately the first time
4519 wxThread::Sleep(300);
4521 puts("Going to resume the thread");
4526 puts("Waiting until it terminates now");
4528 // wait until the thread terminates
4534 void TestThreadDelete()
4536 // As above, using Sleep() is only for testing here - we must use some
4537 // synchronisation object instead to ensure that the thread is still
4538 // running when we delete it - deleting a detached thread which already
4539 // terminated will lead to a crash!
4541 puts("\n*** Testing thread delete function ***");
4543 MyDetachedThread
*thread0
= new MyDetachedThread(30, 'W');
4547 puts("\nDeleted a thread which didn't start to run yet.");
4549 MyDetachedThread
*thread1
= new MyDetachedThread(30, 'Y');
4553 wxThread::Sleep(300);
4557 puts("\nDeleted a running thread.");
4559 MyDetachedThread
*thread2
= new MyDetachedThread(30, 'Z');
4563 wxThread::Sleep(300);
4569 puts("\nDeleted a sleeping thread.");
4571 MyJoinableThread
thread3(20);
4576 puts("\nDeleted a joinable thread.");
4578 MyJoinableThread
thread4(2);
4581 wxThread::Sleep(300);
4585 puts("\nDeleted a joinable thread which already terminated.");
4590 #endif // TEST_THREADS
4592 // ----------------------------------------------------------------------------
4594 // ----------------------------------------------------------------------------
4598 static void PrintArray(const char* name
, const wxArrayString
& array
)
4600 printf("Dump of the array '%s'\n", name
);
4602 size_t nCount
= array
.GetCount();
4603 for ( size_t n
= 0; n
< nCount
; n
++ )
4605 printf("\t%s[%u] = '%s'\n", name
, n
, array
[n
].c_str());
4609 static void PrintArray(const char* name
, const wxArrayInt
& array
)
4611 printf("Dump of the array '%s'\n", name
);
4613 size_t nCount
= array
.GetCount();
4614 for ( size_t n
= 0; n
< nCount
; n
++ )
4616 printf("\t%s[%u] = %d\n", name
, n
, array
[n
]);
4620 int wxCMPFUNC_CONV
StringLenCompare(const wxString
& first
,
4621 const wxString
& second
)
4623 return first
.length() - second
.length();
4626 int wxCMPFUNC_CONV
IntCompare(int *first
,
4629 return *first
- *second
;
4632 int wxCMPFUNC_CONV
IntRevCompare(int *first
,
4635 return *second
- *first
;
4638 static void TestArrayOfInts()
4640 puts("*** Testing wxArrayInt ***\n");
4651 puts("After sort:");
4655 puts("After reverse sort:");
4656 a
.Sort(IntRevCompare
);
4660 #include "wx/dynarray.h"
4662 WX_DECLARE_OBJARRAY(Bar
, ArrayBars
);
4663 #include "wx/arrimpl.cpp"
4664 WX_DEFINE_OBJARRAY(ArrayBars
);
4666 static void TestArrayOfObjects()
4668 puts("*** Testing wxObjArray ***\n");
4672 Bar
bar("second bar");
4674 printf("Initially: %u objects in the array, %u objects total.\n",
4675 bars
.GetCount(), Bar::GetNumber());
4677 bars
.Add(new Bar("first bar"));
4680 printf("Now: %u objects in the array, %u objects total.\n",
4681 bars
.GetCount(), Bar::GetNumber());
4685 printf("After Empty(): %u objects in the array, %u objects total.\n",
4686 bars
.GetCount(), Bar::GetNumber());
4689 printf("Finally: no more objects in the array, %u objects total.\n",
4693 #endif // TEST_ARRAYS
4695 // ----------------------------------------------------------------------------
4697 // ----------------------------------------------------------------------------
4701 #include "wx/timer.h"
4702 #include "wx/tokenzr.h"
4704 static void TestStringConstruction()
4706 puts("*** Testing wxString constructores ***");
4708 #define TEST_CTOR(args, res) \
4711 printf("wxString%s = %s ", #args, s.c_str()); \
4718 printf("(ERROR: should be %s)\n", res); \
4722 TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
4723 TEST_CTOR((_T("Hello"), 4), _T("Hell"));
4724 TEST_CTOR((_T("Hello"), 5), _T("Hello"));
4725 // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
4727 static const wxChar
*s
= _T("?really!");
4728 const wxChar
*start
= wxStrchr(s
, _T('r'));
4729 const wxChar
*end
= wxStrchr(s
, _T('!'));
4730 TEST_CTOR((start
, end
), _T("really"));
4735 static void TestString()
4745 for (int i
= 0; i
< 1000000; ++i
)
4749 c
= "! How'ya doin'?";
4752 c
= "Hello world! What's up?";
4757 printf ("TestString elapsed time: %ld\n", sw
.Time());
4760 static void TestPChar()
4768 for (int i
= 0; i
< 1000000; ++i
)
4770 strcpy (a
, "Hello");
4771 strcpy (b
, " world");
4772 strcpy (c
, "! How'ya doin'?");
4775 strcpy (c
, "Hello world! What's up?");
4776 if (strcmp (c
, a
) == 0)
4780 printf ("TestPChar elapsed time: %ld\n", sw
.Time());
4783 static void TestStringSub()
4785 wxString
s("Hello, world!");
4787 puts("*** Testing wxString substring extraction ***");
4789 printf("String = '%s'\n", s
.c_str());
4790 printf("Left(5) = '%s'\n", s
.Left(5).c_str());
4791 printf("Right(6) = '%s'\n", s
.Right(6).c_str());
4792 printf("Mid(3, 5) = '%s'\n", s(3, 5).c_str());
4793 printf("Mid(3) = '%s'\n", s
.Mid(3).c_str());
4794 printf("substr(3, 5) = '%s'\n", s
.substr(3, 5).c_str());
4795 printf("substr(3) = '%s'\n", s
.substr(3).c_str());
4797 static const wxChar
*prefixes
[] =
4801 _T("Hello, world!"),
4802 _T("Hello, world!!!"),
4808 for ( size_t n
= 0; n
< WXSIZEOF(prefixes
); n
++ )
4810 wxString prefix
= prefixes
[n
], rest
;
4811 bool rc
= s
.StartsWith(prefix
, &rest
);
4812 printf("StartsWith('%s') = %s", prefix
.c_str(), rc
? "TRUE" : "FALSE");
4815 printf(" (the rest is '%s')\n", rest
.c_str());
4826 static void TestStringFormat()
4828 puts("*** Testing wxString formatting ***");
4831 s
.Printf("%03d", 18);
4833 printf("Number 18: %s\n", wxString::Format("%03d", 18).c_str());
4834 printf("Number 18: %s\n", s
.c_str());
4839 // returns "not found" for npos, value for all others
4840 static wxString
PosToString(size_t res
)
4842 wxString s
= res
== wxString::npos
? wxString(_T("not found"))
4843 : wxString::Format(_T("%u"), res
);
4847 static void TestStringFind()
4849 puts("*** Testing wxString find() functions ***");
4851 static const wxChar
*strToFind
= _T("ell");
4852 static const struct StringFindTest
4856 result
; // of searching "ell" in str
4859 { _T("Well, hello world"), 0, 1 },
4860 { _T("Well, hello world"), 6, 7 },
4861 { _T("Well, hello world"), 9, wxString::npos
},
4864 for ( size_t n
= 0; n
< WXSIZEOF(findTestData
); n
++ )
4866 const StringFindTest
& ft
= findTestData
[n
];
4867 size_t res
= wxString(ft
.str
).find(strToFind
, ft
.start
);
4869 printf(_T("Index of '%s' in '%s' starting from %u is %s "),
4870 strToFind
, ft
.str
, ft
.start
, PosToString(res
).c_str());
4872 size_t resTrue
= ft
.result
;
4873 if ( res
== resTrue
)
4879 printf(_T("(ERROR: should be %s)\n"),
4880 PosToString(resTrue
).c_str());
4887 static void TestStringTokenizer()
4889 puts("*** Testing wxStringTokenizer ***");
4891 static const wxChar
*modeNames
[] =
4895 _T("return all empty"),
4900 static const struct StringTokenizerTest
4902 const wxChar
*str
; // string to tokenize
4903 const wxChar
*delims
; // delimiters to use
4904 size_t count
; // count of token
4905 wxStringTokenizerMode mode
; // how should we tokenize it
4906 } tokenizerTestData
[] =
4908 { _T(""), _T(" "), 0 },
4909 { _T("Hello, world"), _T(" "), 2 },
4910 { _T("Hello, world "), _T(" "), 2 },
4911 { _T("Hello, world"), _T(","), 2 },
4912 { _T("Hello, world!"), _T(",!"), 2 },
4913 { _T("Hello,, world!"), _T(",!"), 3 },
4914 { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL
},
4915 { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
4916 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 4 },
4917 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 6, wxTOKEN_RET_EMPTY
},
4918 { _T("1 \t3\t4 6 "), wxDEFAULT_DELIMITERS
, 9, wxTOKEN_RET_EMPTY_ALL
},
4919 { _T("01/02/99"), _T("/-"), 3 },
4920 { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS
},
4923 for ( size_t n
= 0; n
< WXSIZEOF(tokenizerTestData
); n
++ )
4925 const StringTokenizerTest
& tt
= tokenizerTestData
[n
];
4926 wxStringTokenizer
tkz(tt
.str
, tt
.delims
, tt
.mode
);
4928 size_t count
= tkz
.CountTokens();
4929 printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
4930 MakePrintable(tt
.str
).c_str(),
4932 MakePrintable(tt
.delims
).c_str(),
4933 modeNames
[tkz
.GetMode()]);
4934 if ( count
== tt
.count
)
4940 printf(_T("(ERROR: should be %u)\n"), tt
.count
);
4945 // if we emulate strtok(), check that we do it correctly
4946 wxChar
*buf
, *s
= NULL
, *last
;
4948 if ( tkz
.GetMode() == wxTOKEN_STRTOK
)
4950 buf
= new wxChar
[wxStrlen(tt
.str
) + 1];
4951 wxStrcpy(buf
, tt
.str
);
4953 s
= wxStrtok(buf
, tt
.delims
, &last
);
4960 // now show the tokens themselves
4962 while ( tkz
.HasMoreTokens() )
4964 wxString token
= tkz
.GetNextToken();
4966 printf(_T("\ttoken %u: '%s'"),
4968 MakePrintable(token
).c_str());
4978 printf(" (ERROR: should be %s)\n", s
);
4981 s
= wxStrtok(NULL
, tt
.delims
, &last
);
4985 // nothing to compare with
4990 if ( count2
!= count
)
4992 puts(_T("\tERROR: token count mismatch"));
5001 static void TestStringReplace()
5003 puts("*** Testing wxString::replace ***");
5005 static const struct StringReplaceTestData
5007 const wxChar
*original
; // original test string
5008 size_t start
, len
; // the part to replace
5009 const wxChar
*replacement
; // the replacement string
5010 const wxChar
*result
; // and the expected result
5011 } stringReplaceTestData
[] =
5013 { _T("012-AWORD-XYZ"), 4, 5, _T("BWORD"), _T("012-BWORD-XYZ") },
5014 { _T("increase"), 0, 2, _T("de"), _T("decrease") },
5015 { _T("wxWindow"), 8, 0, _T("s"), _T("wxWindows") },
5016 { _T("foobar"), 3, 0, _T("-"), _T("foo-bar") },
5017 { _T("barfoo"), 0, 6, _T("foobar"), _T("foobar") },
5020 for ( size_t n
= 0; n
< WXSIZEOF(stringReplaceTestData
); n
++ )
5022 const StringReplaceTestData data
= stringReplaceTestData
[n
];
5024 wxString original
= data
.original
;
5025 original
.replace(data
.start
, data
.len
, data
.replacement
);
5027 wxPrintf(_T("wxString(\"%s\").replace(%u, %u, %s) = %s "),
5028 data
.original
, data
.start
, data
.len
, data
.replacement
,
5031 if ( original
== data
.result
)
5037 wxPrintf(_T("(ERROR: should be '%s')\n"), data
.result
);
5044 static void TestStringMatch()
5046 wxPuts(_T("*** Testing wxString::Matches() ***"));
5048 static const struct StringMatchTestData
5051 const wxChar
*wildcard
;
5053 } stringMatchTestData
[] =
5055 { _T("foobar"), _T("foo*"), 1 },
5056 { _T("foobar"), _T("*oo*"), 1 },
5057 { _T("foobar"), _T("*bar"), 1 },
5058 { _T("foobar"), _T("??????"), 1 },
5059 { _T("foobar"), _T("f??b*"), 1 },
5060 { _T("foobar"), _T("f?b*"), 0 },
5061 { _T("foobar"), _T("*goo*"), 0 },
5062 { _T("foobar"), _T("*foo"), 0 },
5063 { _T("foobarfoo"), _T("*foo"), 1 },
5064 { _T(""), _T("*"), 1 },
5065 { _T(""), _T("?"), 0 },
5068 for ( size_t n
= 0; n
< WXSIZEOF(stringMatchTestData
); n
++ )
5070 const StringMatchTestData
& data
= stringMatchTestData
[n
];
5071 bool matches
= wxString(data
.text
).Matches(data
.wildcard
);
5072 wxPrintf(_T("'%s' %s '%s' (%s)\n"),
5074 matches
? _T("matches") : _T("doesn't match"),
5076 matches
== data
.matches
? _T("ok") : _T("ERROR"));
5082 #endif // TEST_STRINGS
5084 // ----------------------------------------------------------------------------
5086 // ----------------------------------------------------------------------------
5088 #ifdef TEST_SNGLINST
5089 #include "wx/snglinst.h"
5090 #endif // TEST_SNGLINST
5092 int main(int argc
, char **argv
)
5094 wxInitializer initializer
;
5097 fprintf(stderr
, "Failed to initialize the wxWindows library, aborting.");
5102 #ifdef TEST_SNGLINST
5103 wxSingleInstanceChecker checker
;
5104 if ( checker
.Create(_T(".wxconsole.lock")) )
5106 if ( checker
.IsAnotherRunning() )
5108 wxPrintf(_T("Another instance of the program is running, exiting.\n"));
5113 // wait some time to give time to launch another instance
5114 wxPrintf(_T("Press \"Enter\" to continue..."));
5117 else // failed to create
5119 wxPrintf(_T("Failed to init wxSingleInstanceChecker.\n"));
5121 #endif // TEST_SNGLINST
5125 #endif // TEST_CHARSET
5128 TestCmdLineConvert();
5130 #if wxUSE_CMDLINE_PARSER
5131 static const wxCmdLineEntryDesc cmdLineDesc
[] =
5133 { wxCMD_LINE_SWITCH
, _T("h"), _T("help"), "show this help message",
5134 wxCMD_LINE_VAL_NONE
, wxCMD_LINE_OPTION_HELP
},
5135 { wxCMD_LINE_SWITCH
, "v", "verbose", "be verbose" },
5136 { wxCMD_LINE_SWITCH
, "q", "quiet", "be quiet" },
5138 { wxCMD_LINE_OPTION
, "o", "output", "output file" },
5139 { wxCMD_LINE_OPTION
, "i", "input", "input dir" },
5140 { wxCMD_LINE_OPTION
, "s", "size", "output block size",
5141 wxCMD_LINE_VAL_NUMBER
},
5142 { wxCMD_LINE_OPTION
, "d", "date", "output file date",
5143 wxCMD_LINE_VAL_DATE
},
5145 { wxCMD_LINE_PARAM
, NULL
, NULL
, "input file",
5146 wxCMD_LINE_VAL_STRING
, wxCMD_LINE_PARAM_MULTIPLE
},
5151 wxCmdLineParser
parser(cmdLineDesc
, argc
, argv
);
5153 parser
.AddOption("project_name", "", "full path to project file",
5154 wxCMD_LINE_VAL_STRING
,
5155 wxCMD_LINE_OPTION_MANDATORY
| wxCMD_LINE_NEEDS_SEPARATOR
);
5157 switch ( parser
.Parse() )
5160 wxLogMessage("Help was given, terminating.");
5164 ShowCmdLine(parser
);
5168 wxLogMessage("Syntax error detected, aborting.");
5171 #endif // wxUSE_CMDLINE_PARSER
5173 #endif // TEST_CMDLINE
5181 TestStringConstruction();
5184 TestStringTokenizer();
5185 TestStringReplace();
5191 #endif // TEST_STRINGS
5204 puts("*** Initially:");
5206 PrintArray("a1", a1
);
5208 wxArrayString
a2(a1
);
5209 PrintArray("a2", a2
);
5211 wxSortedArrayString
a3(a1
);
5212 PrintArray("a3", a3
);
5214 puts("*** After deleting a string from a1");
5217 PrintArray("a1", a1
);
5218 PrintArray("a2", a2
);
5219 PrintArray("a3", a3
);
5221 puts("*** After reassigning a1 to a2 and a3");
5223 PrintArray("a2", a2
);
5224 PrintArray("a3", a3
);
5226 puts("*** After sorting a1");
5228 PrintArray("a1", a1
);
5230 puts("*** After sorting a1 in reverse order");
5232 PrintArray("a1", a1
);
5234 puts("*** After sorting a1 by the string length");
5235 a1
.Sort(StringLenCompare
);
5236 PrintArray("a1", a1
);
5238 TestArrayOfObjects();
5244 #endif // TEST_ARRAYS
5254 #ifdef TEST_DLLLOADER
5256 #endif // TEST_DLLLOADER
5260 #endif // TEST_ENVIRON
5264 #endif // TEST_EXECUTE
5266 #ifdef TEST_FILECONF
5268 #endif // TEST_FILECONF
5276 #endif // TEST_LOCALE
5280 for ( size_t n
= 0; n
< 8000; n
++ )
5282 s
<< (char)('A' + (n
% 26));
5286 msg
.Printf("A very very long message: '%s', the end!\n", s
.c_str());
5288 // this one shouldn't be truncated
5291 // but this one will because log functions use fixed size buffer
5292 // (note that it doesn't need '\n' at the end neither - will be added
5294 wxLogMessage("A very very long message 2: '%s', the end!", s
.c_str());
5306 #ifdef TEST_FILENAME
5310 fn
.Assign("c:\\foo", "bar.baz");
5317 TestFileNameConstruction();
5318 TestFileNameMakeRelative();
5319 TestFileNameSplit();
5322 TestFileNameComparison();
5323 TestFileNameOperations();
5325 #endif // TEST_FILENAME
5327 #ifdef TEST_FILETIME
5330 #endif // TEST_FILETIME
5333 wxLog::AddTraceMask(FTP_TRACE_MASK
);
5334 if ( TestFtpConnect() )
5345 if ( TEST_INTERACTIVE
)
5346 TestFtpInteractive();
5348 //else: connecting to the FTP server failed
5355 int nCPUs
= wxThread::GetCPUCount();
5356 printf("This system has %d CPUs\n", nCPUs
);
5358 wxThread::SetConcurrency(nCPUs
);
5360 if ( argc
> 1 && argv
[1][0] == 't' )
5361 wxLog::AddTraceMask("thread");
5364 TestDetachedThreads();
5366 TestJoinableThreads();
5368 TestThreadSuspend();
5372 #endif // TEST_THREADS
5374 #ifdef TEST_LONGLONG
5375 // seed pseudo random generator
5376 srand((unsigned)time(NULL
));
5385 TestMultiplication();
5388 TestLongLongConversion();
5389 TestBitOperations();
5390 TestLongLongComparison();
5391 TestLongLongPrint();
5393 #endif // TEST_LONGLONG
5400 wxLog::AddTraceMask(_T("mime"));
5408 TestMimeAssociate();
5411 #ifdef TEST_INFO_FUNCTIONS
5418 #endif // TEST_INFO_FUNCTIONS
5420 #ifdef TEST_PATHLIST
5422 #endif // TEST_PATHLIST
5426 #endif // TEST_REGCONF
5429 // TODO: write a real test using src/regex/tests file
5434 TestRegExSubmatch();
5435 TestRegExReplacement();
5437 if ( TEST_INTERACTIVE
)
5438 TestRegExInteractive();
5440 #endif // TEST_REGEX
5442 #ifdef TEST_REGISTRY
5444 TestRegistryAssociation();
5445 #endif // TEST_REGISTRY
5450 #endif // TEST_SOCKETS
5455 #endif // TEST_STREAMS
5459 #endif // TEST_TIMER
5461 #ifdef TEST_DATETIME
5474 TestTimeArithmetics();
5477 TestTimeSpanFormat();
5483 if ( TEST_INTERACTIVE
)
5484 TestDateTimeInteractive();
5485 #endif // TEST_DATETIME
5488 puts("Sleeping for 3 seconds... z-z-z-z-z...");
5490 #endif // TEST_USLEEP
5495 #endif // TEST_VCARD
5499 #endif // TEST_WCHAR
5502 TestZipStreamRead();
5503 TestZipFileSystem();
5507 TestZlibStreamWrite();
5508 TestZlibStreamRead();