]> git.saurik.com Git - wxWidgets.git/blobdiff - samples/console/console.cpp
Made clean target be not quite so agressive, added 'cleanall'
[wxWidgets.git] / samples / console / console.cpp
index e01cf964bf4935a097787f79a15863177b5b2afd..37042997953f80cbb3726bf690c044eeae79c3e6 100644 (file)
 #include <wx/file.h>
 #include <wx/app.h>
 
+// without this pragma, the stupid compiler precompiles #defines below so that
+// changing them doesn't "take place" later!
+#ifdef __VISUALC__
+    #pragma hdrstop
+#endif
+
 // ----------------------------------------------------------------------------
 // conditional compilation
 // ----------------------------------------------------------------------------
 
-// what to test?
+// what to test (in alphabetic order)?
 
 //#define TEST_ARRAYS
 //#define TEST_CMDLINE
+//#define TEST_DATETIME
 //#define TEST_DIR
+//#define TEST_EXECUTE
+//#define TEST_FILECONF
+//#define TEST_HASH
 //#define TEST_LOG
 //#define TEST_LONGLONG
 //#define TEST_MIME
+//#define TEST_SOCKETS
 //#define TEST_STRINGS
 //#define TEST_THREADS
-#define TEST_TIME
+#define TEST_TIMER
 
 // ============================================================================
 // implementation
 // ============================================================================
 
-#ifdef TEST_CMDLINE
-
 // ----------------------------------------------------------------------------
 // wxCmdLineParser
 // ----------------------------------------------------------------------------
 
+#ifdef TEST_CMDLINE
+
 #include <wx/cmdline.h>
 #include <wx/datetime.h>
 
@@ -160,6 +171,222 @@ static void TestDirEnum()
 
 #endif // TEST_DIR
 
+// ----------------------------------------------------------------------------
+// wxExecute
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_EXECUTE
+
+#include <wx/utils.h>
+
+static void TestExecute()
+{
+    puts("*** testing wxExecute ***");
+
+#ifdef __UNIX__
+    #define COMMAND "echo hi"
+    #define SHELL_COMMAND "echo hi from shell"
+    #define REDIRECT_COMMAND "date"
+#elif defined(__WXMSW__)
+    #define COMMAND "command.com -c 'echo hi'"
+    #define SHELL_COMMAND "echo hi"
+    #define REDIRECT_COMMAND COMMAND
+#else
+    #error "no command to exec"
+#endif // OS
+
+    printf("Testing wxShell: ");
+    fflush(stdout);
+    if ( wxShell(SHELL_COMMAND) )
+        puts("Ok.");
+    else
+        puts("ERROR.");
+
+    printf("Testing wxExecute: ");
+    fflush(stdout);
+    if ( wxExecute(COMMAND, TRUE /* sync */) == 0 )
+        puts("Ok.");
+    else
+        puts("ERROR.");
+
+#if 0 // no, it doesn't work (yet?)
+    printf("Testing async wxExecute: ");
+    fflush(stdout);
+    if ( wxExecute(COMMAND) != 0 )
+        puts("Ok (command launched).");
+    else
+        puts("ERROR.");
+#endif // 0
+
+    printf("Testing wxExecute with redirection:\n");
+    wxArrayString output;
+    if ( wxExecute(REDIRECT_COMMAND, output) != 0 )
+    {
+        puts("ERROR.");
+    }
+    else
+    {
+        size_t count = output.GetCount();
+        for ( size_t n = 0; n < count; n++ )
+        {
+            printf("\t%s\n", output[n].c_str());
+        }
+
+        puts("Ok.");
+    }
+}
+
+#endif // TEST_EXECUTE
+
+// ----------------------------------------------------------------------------
+// wxFileConfig
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_FILECONF
+
+#include <wx/confbase.h>
+#include <wx/fileconf.h>
+
+static const struct FileConfTestData
+{
+    const wxChar *name;      // value name
+    const wxChar *value;     // the value from the file
+} fcTestData[] =
+{
+    { _T("value1"),                       _T("one") },
+    { _T("value2"),                       _T("two") },
+    { _T("novalue"),                      _T("default") },
+};
+
+static void TestFileConfRead()
+{
+    puts("*** testing wxFileConfig loading/reading ***");
+
+    wxFileConfig fileconf(_T("test"), wxEmptyString,
+                          _T("testdata.fc"), wxEmptyString,
+                          wxCONFIG_USE_RELATIVE_PATH);
+
+    // test simple reading
+    puts("\nReading config file:");
+    wxString defValue(_T("default")), value;
+    for ( size_t n = 0; n < WXSIZEOF(fcTestData); n++ )
+    {
+        const FileConfTestData& data = fcTestData[n];
+        value = fileconf.Read(data.name, defValue);
+        printf("\t%s = %s ", data.name, value.c_str());
+        if ( value == data.value )
+        {
+            puts("(ok)");
+        }
+        else
+        {
+            printf("(ERROR: should be %s)\n", data.value);
+        }
+    }
+
+    // test enumerating the entries
+    puts("\nEnumerating all root entries:");
+    long dummy;
+    wxString name;
+    bool cont = fileconf.GetFirstEntry(name, dummy);
+    while ( cont )
+    {
+        printf("\t%s = %s\n",
+               name.c_str(),
+               fileconf.Read(name.c_str(), _T("ERROR")).c_str());
+
+        cont = fileconf.GetNextEntry(name, dummy);
+    }
+}
+
+#endif // TEST_FILECONF
+
+// ----------------------------------------------------------------------------
+// wxHashTable
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_HASH
+
+#include <wx/hash.h>
+
+struct Foo
+{
+    Foo(int n_) { n = n_; count++; }
+    ~Foo() { count--; }
+
+    int n;
+
+    static size_t count;
+};
+
+size_t Foo::count = 0;
+
+WX_DECLARE_LIST(Foo, wxListFoos);
+WX_DECLARE_HASH(Foo, wxListFoos, wxHashFoos);
+
+#include <wx/listimpl.cpp>
+
+WX_DEFINE_LIST(wxListFoos);
+
+static void TestHash()
+{
+    puts("*** Testing wxHashTable ***\n");
+
+    {
+        wxHashFoos hash;
+        hash.DeleteContents(TRUE);
+
+        printf("Hash created: %u foos in hash, %u foos totally\n",
+               hash.GetCount(), Foo::count);
+
+        static const int hashTestData[] =
+        {
+            0, 1, 17, -2, 2, 4, -4, 345, 3, 3, 2, 1,
+        };
+
+        size_t n;
+        for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
+        {
+            hash.Put(hashTestData[n], n, new Foo(n));
+        }
+
+        printf("Hash filled: %u foos in hash, %u foos totally\n",
+               hash.GetCount(), Foo::count);
+
+        puts("Hash access test:");
+        for ( n = 0; n < WXSIZEOF(hashTestData); n++ )
+        {
+            printf("\tGetting element with key %d, value %d: ",
+                   hashTestData[n], n);
+            Foo *foo = hash.Get(hashTestData[n], n);
+            if ( !foo )
+            {
+                printf("ERROR, not found.\n");
+            }
+            else
+            {
+                printf("%d (%s)\n", foo->n,
+                       (size_t)foo->n == n ? "ok" : "ERROR");
+            }
+        }
+
+        printf("\nTrying to get an element not in hash: ");
+
+        if ( hash.Get(1234) || hash.Get(1, 0) )
+        {
+            puts("ERROR: found!");
+        }
+        else
+        {
+            puts("ok (not found)");
+        }
+    }
+
+    printf("Hash destroyed: %u foos left\n", Foo::count);
+}
+
+#endif // TEST_HASH
+
 // ----------------------------------------------------------------------------
 // MIME types
 // ----------------------------------------------------------------------------
@@ -225,12 +452,12 @@ static void TestMimeEnum()
 // get a random 64 bit number
 #define RAND_LL()   MAKE_LL(rand(), rand(), rand(), rand())
 
-#if wxUSE_LONGLONG_NATIVE
+#if wxUSE_LONGLONG_WX
 inline bool operator==(const wxLongLongWx& a, const wxLongLongNative& b)
     { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
 inline bool operator==(const wxLongLongNative& a, const wxLongLongWx& b)
     { return a.GetHi() == b.GetHi() && a.GetLo() == b.GetLo(); }
-#endif // wxUSE_LONGLONG_NATIVE
+#endif // wxUSE_LONGLONG_WX
 
 static void TestSpeed()
 {
@@ -396,7 +623,7 @@ static void TestAddition()
 #if wxUSE_LONGLONG_NATIVE
         wxASSERT_MSG( c == wxLongLongNative(a.GetHi(), a.GetLo()) +
                            wxLongLongNative(b.GetHi(), b.GetLo()),
-                      "addition failure" ); 
+                      "addition failure" );
 #else // !wxUSE_LONGLONG_NATIVE
         wxASSERT_MSG( c - b == a, "addition failure" );
 #endif // wxUSE_LONGLONG_NATIVE
@@ -462,11 +689,94 @@ static void TestBitOperations()
 
 #endif // TEST_LONGLONG
 
+// ----------------------------------------------------------------------------
+// sockets
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_SOCKETS
+
+#include <wx/socket.h>
+
+static void TestSocketClient()
+{
+    puts("*** Testing wxSocketClient ***\n");
+
+    wxIPV4address addrDst;
+    addrDst.Hostname("www.wxwindows.org");
+    addrDst.Service(80);
+
+    wxSocketClient client;
+    if ( !client.Connect(addrDst) )
+    {
+        printf("ERROR: failed to connect to %s\n", addrDst.Hostname().c_str());
+    }
+    else
+    {
+        char buf[8192];
+
+        client.Write("get /front.htm\n", 17);
+        client.Read(buf, WXSIZEOF(buf));
+        printf("Server replied:\n%s", buf);
+    }
+}
+
+#endif // TEST_SOCKETS
+
+// ----------------------------------------------------------------------------
+// timers
+// ----------------------------------------------------------------------------
+
+#ifdef TEST_TIMER
+
+#include <wx/timer.h>
+#include <wx/utils.h>
+
+static void TestStopWatch()
+{
+    puts("*** Testing wxStopWatch ***\n");
+
+    wxStopWatch sw;
+    printf("Sleeping 3 seconds...");
+    wxSleep(3);
+    printf("\telapsed time: %ldms\n", sw.Time());
+
+    sw.Pause();
+    printf("Sleeping 2 more seconds...");
+    wxSleep(2);
+    printf("\telapsed time: %ldms\n", sw.Time());
+
+    sw.Resume();
+    printf("And 3 more seconds...");
+    wxSleep(3);
+    printf("\telapsed time: %ldms\n", sw.Time());
+
+    wxStopWatch sw2;
+    puts("\nChecking for 'backwards clock' bug...");
+    for ( size_t n = 0; n < 70; n++ )
+    {
+        sw2.Start();
+
+        for ( size_t m = 0; m < 100000; m++ )
+        {
+            if ( sw.Time() < 0 || sw2.Time() < 0 )
+            {
+                puts("\ntime is negative - ERROR!");
+            }
+        }
+
+        putchar('.');
+    }
+
+    puts(", ok.");
+}
+
+#endif // TEST_TIMER
+
 // ----------------------------------------------------------------------------
 // date time
 // ----------------------------------------------------------------------------
 
-#ifdef TEST_TIME
+#ifdef TEST_DATETIME
 
 #include <wx/date.h>
 
@@ -892,7 +1202,7 @@ def GetMonthWeek(dt):
     if weekNumMonth < 0:
         weekNumMonth = weekNumMonth + 53
     return weekNumMonth
-    
+
 def GetLastSundayBefore(dt):
     if dt.iso_week[2] == 7:
         return dt
@@ -1293,7 +1603,7 @@ static void TestTimeArithmetics()
     {
         wxDateSpan span;
         const char *name;
-    } testArithmData[] = 
+    } testArithmData[] =
     {
         { wxDateSpan::Day(),           "day"                                },
         { wxDateSpan::Week(),          "week"                               },
@@ -1301,7 +1611,7 @@ static void TestTimeArithmetics()
         { wxDateSpan::Year(),          "year"                               },
         { wxDateSpan(1, 2, 3, 4),      "year, 2 months, 3 weeks, 4 days"    },
     };
-    
+
     wxDateTime dt(29, wxDateTime::Dec, 1999), dt1, dt2;
 
     for ( size_t n = 0; n < WXSIZEOF(testArithmData); n++ )
@@ -1406,7 +1716,7 @@ static void TestTimeCompatibility()
 
 #endif // 0
 
-#endif // TEST_TIME
+#endif // TEST_DATETIME
 
 // ----------------------------------------------------------------------------
 // threads
@@ -1670,6 +1980,38 @@ void PrintArray(const char* name, const wxArrayString& array)
 #ifdef TEST_STRINGS
 
 #include "wx/timer.h"
+#include "wx/tokenzr.h"
+
+static void TestStringConstruction()
+{
+    puts("*** Testing wxString constructores ***");
+
+    #define TEST_CTOR(args, res)                                               \
+        {                                                                      \
+            wxString s args ;                                                  \
+            printf("wxString%s = %s ", #args, s.c_str());                      \
+            if ( s == res )                                                    \
+            {                                                                  \
+                puts("(ok)");                                                  \
+            }                                                                  \
+            else                                                               \
+            {                                                                  \
+                printf("(ERROR: should be %s)\n", res);                        \
+            }                                                                  \
+        }
+
+    TEST_CTOR((_T('Z'), 4), _T("ZZZZ"));
+    TEST_CTOR((_T("Hello"), 4), _T("Hell"));
+    TEST_CTOR((_T("Hello"), 5), _T("Hello"));
+    // TEST_CTOR((_T("Hello"), 6), _T("Hello")); -- should give assert failure
+
+    static const wxChar *s = _T("?really!");
+    const wxChar *start = wxStrchr(s, _T('r'));
+    const wxChar *end = wxStrchr(s, _T('!'));
+    TEST_CTOR((start, end), _T("really"));
+
+    puts("");
+}
 
 static void TestString()
 {
@@ -1749,6 +2091,179 @@ static void TestStringFormat()
     puts("");
 }
 
+// returns "not found" for npos, value for all others
+static wxString PosToString(size_t res)
+{
+    wxString s = res == wxString::npos ? wxString(_T("not found"))
+                                       : wxString::Format(_T("%u"), res);
+    return s;
+}
+
+static void TestStringFind()
+{
+    puts("*** Testing wxString find() functions ***");
+
+    static const wxChar *strToFind = _T("ell");
+    static const struct StringFindTest
+    {
+        const wxChar *str;
+        size_t        start,
+                      result;   // of searching "ell" in str
+    } findTestData[] =
+    {
+        { _T("Well, hello world"),  0, 1 },
+        { _T("Well, hello world"),  6, 7 },
+        { _T("Well, hello world"),  9, wxString::npos },
+    };
+
+    for ( size_t n = 0; n < WXSIZEOF(findTestData); n++ )
+    {
+        const StringFindTest& ft = findTestData[n];
+        size_t res = wxString(ft.str).find(strToFind, ft.start);
+
+        printf(_T("Index of '%s' in '%s' starting from %u is %s "),
+               strToFind, ft.str, ft.start, PosToString(res).c_str());
+
+        size_t resTrue = ft.result;
+        if ( res == resTrue )
+        {
+            puts(_T("(ok)"));
+        }
+        else
+        {
+            printf(_T("(ERROR: should be %s)\n"),
+                   PosToString(resTrue).c_str());
+        }
+    }
+
+    puts("");
+}
+
+// replace TABs with \t and CRs with \n
+static wxString MakePrintable(const wxChar *s)
+{
+    wxString str(s);
+    (void)str.Replace(_T("\t"), _T("\\t"));
+    (void)str.Replace(_T("\n"), _T("\\n"));
+    (void)str.Replace(_T("\r"), _T("\\r"));
+
+    return str;
+}
+
+static void TestStringTokenizer()
+{
+    puts("*** Testing wxStringTokenizer ***");
+
+    static const wxChar *modeNames[] =
+    {
+        _T("default"),
+        _T("return empty"),
+        _T("return all empty"),
+        _T("with delims"),
+        _T("like strtok"),
+    };
+
+    static const struct StringTokenizerTest
+    {
+        const wxChar *str;              // string to tokenize
+        const wxChar *delims;           // delimiters to use
+        size_t        count;            // count of token
+        wxStringTokenizerMode mode;     // how should we tokenize it
+    } tokenizerTestData[] =
+    {
+        { _T(""), _T(" "), 0 },
+        { _T("Hello, world"), _T(" "), 2 },
+        { _T("Hello,   world  "), _T(" "), 2 },
+        { _T("Hello, world"), _T(","), 2 },
+        { _T("Hello, world!"), _T(",!"), 2 },
+        { _T("Hello,, world!"), _T(",!"), 3 },
+        { _T("Hello, world!"), _T(",!"), 3, wxTOKEN_RET_EMPTY_ALL },
+        { _T("username:password:uid:gid:gecos:home:shell"), _T(":"), 7 },
+        { _T("1 \t3\t4  6   "), wxDEFAULT_DELIMITERS, 4 },
+        { _T("1 \t3\t4  6   "), wxDEFAULT_DELIMITERS, 6, wxTOKEN_RET_EMPTY },
+        { _T("1 \t3\t4  6   "), wxDEFAULT_DELIMITERS, 9, wxTOKEN_RET_EMPTY_ALL },
+        { _T("01/02/99"), _T("/-"), 3 },
+        { _T("01-02/99"), _T("/-"), 3, wxTOKEN_RET_DELIMS },
+    };
+
+    for ( size_t n = 0; n < WXSIZEOF(tokenizerTestData); n++ )
+    {
+        const StringTokenizerTest& tt = tokenizerTestData[n];
+        wxStringTokenizer tkz(tt.str, tt.delims, tt.mode);
+
+        size_t count = tkz.CountTokens();
+        printf(_T("String '%s' has %u tokens delimited by '%s' (mode = %s) "),
+               MakePrintable(tt.str).c_str(),
+               count,
+               MakePrintable(tt.delims).c_str(),
+               modeNames[tkz.GetMode()]);
+        if ( count == tt.count )
+        {
+            puts(_T("(ok)"));
+        }
+        else
+        {
+            printf(_T("(ERROR: should be %u)\n"), tt.count);
+
+            continue;
+        }
+
+        // if we emulate strtok(), check that we do it correctly
+        wxChar *buf, *s, *last;
+
+        if ( tkz.GetMode() == wxTOKEN_STRTOK )
+        {
+            buf = new wxChar[wxStrlen(tt.str) + 1];
+            wxStrcpy(buf, tt.str);
+
+            s = wxStrtok(buf, tt.delims, &last);
+        }
+        else
+        {
+            buf = NULL;
+        }
+
+        // now show the tokens themselves
+        size_t count2 = 0;
+        while ( tkz.HasMoreTokens() )
+        {
+            wxString token = tkz.GetNextToken();
+
+            printf(_T("\ttoken %u: '%s'"),
+                   ++count2,
+                   MakePrintable(token).c_str());
+
+            if ( buf )
+            {
+                if ( token == s )
+                {
+                    puts(" (ok)");
+                }
+                else
+                {
+                    printf(" (ERROR: should be %s)\n", s);
+                }
+
+                s = wxStrtok(NULL, tt.delims, &last);
+            }
+            else
+            {
+                // nothing to compare with
+                puts("");
+            }
+        }
+
+        if ( count2 != count )
+        {
+            puts(_T("\tERROR: token count mismatch"));
+        }
+
+        delete [] buf;
+    }
+
+    puts("");
+}
+
 #endif // TEST_STRINGS
 
 // ----------------------------------------------------------------------------
@@ -1810,9 +2325,12 @@ int main(int argc, char **argv)
     }
     if ( 0 )
     {
+        TestStringConstruction();
         TestStringSub();
+        TestStringFormat();
+        TestStringFind();
+        TestStringTokenizer();
     }
-    TestStringFormat();
 #endif // TEST_STRINGS
 
 #ifdef TEST_ARRAYS
@@ -1851,6 +2369,14 @@ int main(int argc, char **argv)
     TestDirEnum();
 #endif // TEST_DIR
 
+#ifdef TEST_EXECUTE
+    TestExecute();
+#endif // TEST_EXECUTE
+
+#ifdef TEST_FILECONF
+    TestFileConfRead();
+#endif // TEST_FILECONF
+
 #ifdef TEST_LOG
     wxString s;
     for ( size_t n = 0; n < 8000; n++ )
@@ -1908,11 +2434,23 @@ int main(int argc, char **argv)
     }
 #endif // TEST_LONGLONG
 
+#ifdef TEST_HASH
+    TestHash();
+#endif // TEST_HASH
+
 #ifdef TEST_MIME
     TestMimeEnum();
 #endif // TEST_MIME
 
-#ifdef TEST_TIME
+#ifdef TEST_SOCKETS
+    TestSocketClient();
+#endif // TEST_SOCKETS
+
+#ifdef TEST_TIMER
+    TestStopWatch();
+#endif // TEST_TIMER
+
+#ifdef TEST_DATETIME
     if ( 0 )
     {
         TestTimeSet();
@@ -1931,7 +2469,7 @@ int main(int argc, char **argv)
     TestTimeHolidays();
     if ( 0 )
         TestInteractive();
-#endif // TEST_TIME
+#endif // TEST_DATETIME
 
     wxUninitialize();