1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Test program for wxWidgets
4 // Author: Mike Wetherell
6 // Copyright: (c) 2004 Mike Wetherell
7 // Licence: wxWindows licence
8 ///////////////////////////////////////////////////////////////////////////////
10 // ----------------------------------------------------------------------------
12 // ----------------------------------------------------------------------------
14 // For compilers that support precompilation, includes "wx/wx.h"
22 // for all others, include the necessary headers
27 #include "wx/beforestd.h"
29 #pragma warning(disable:4100)
32 #include <cppunit/TestListener.h>
33 #include <cppunit/Protector.h>
34 #include <cppunit/Test.h>
35 #include <cppunit/TestResult.h>
36 #include <cppunit/TestFailure.h>
39 #pragma warning(default:4100)
41 #include "wx/afterstd.h"
43 #include "wx/cmdline.h"
47 #include "wx/msw/msvcrt.h"
51 #include "wx/osx/private.h"
55 #include "testableframe.h"
58 #include "wx/socket.h"
59 #include "wx/evtloop.h"
64 using CppUnit::TestSuite
;
65 using CppUnit::TestFactoryRegistry
;
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // exception class for MSVC debug CRT assertion failures
73 #ifdef wxUSE_VC_CRTDBG
75 struct CrtAssertFailure
77 CrtAssertFailure(const char *message
) : m_msg(message
) { }
81 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure
);
84 #endif // wxUSE_VC_CRTDBG
88 static wxString
FormatAssertMessage(const wxString
& file
,
95 str
<< "wxWidgets assert: " << cond
<< " failed "
96 "at " << file
<< ":" << line
<< " in " << func
97 << " with message '" << msg
<< "'";
101 static void TestAssertHandler(const wxString
& file
,
103 const wxString
& func
,
104 const wxString
& cond
,
107 // can't throw from other threads, die immediately
108 if ( !wxIsMainThread() )
110 wxPrintf("%s in a worker thread -- aborting.",
111 FormatAssertMessage(file
, line
, func
, cond
, msg
));
116 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
119 #endif // wxDEBUG_LEVEL
121 // this function should only be called from a catch clause
122 static string
GetExceptionMessage()
131 catch ( TestAssertFailure
& e
)
133 msg
<< FormatAssertMessage(e
.m_file
, e
.m_line
, e
.m_func
,
136 #endif // wxDEBUG_LEVEL
137 #ifdef wxUSE_VC_CRTDBG
138 catch ( CrtAssertFailure
& e
)
140 msg
<< "CRT assert failure: " << e
.m_msg
;
142 #endif // wxUSE_VC_CRTDBG
143 catch ( std::exception
& e
)
145 msg
<< "std::exception: " << e
.what();
149 msg
= "Unknown exception caught.";
152 return string(msg
.mb_str());
155 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
156 // this context) exceptions
157 class wxUnitTestProtector
: public CppUnit::Protector
160 virtual bool protect(const CppUnit::Functor
&functor
,
161 const CppUnit::ProtectorContext
& context
)
167 catch ( std::exception
& )
169 // cppunit deals with the standard exceptions itself, let it do as
170 // it output more details (especially for std::exception-derived
171 // CppUnit::Exception) than we do
176 reportError(context
, CppUnit::Message("Uncaught exception",
177 GetExceptionMessage()));
184 // Displays the test name before starting to execute it: this helps with
185 // diagnosing where exactly does a test crash or hang when/if it does.
186 class DetailListener
: public CppUnit::TestListener
189 DetailListener(bool doTiming
= false):
190 CppUnit::TestListener(),
195 virtual void startTest(CppUnit::Test
*test
)
197 wxPrintf(" %-60s ", test
->getName());
198 m_result
= RESULT_OK
;
202 virtual void addFailure(const CppUnit::TestFailure
& failure
)
204 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
207 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
210 wxPrintf(GetResultStr(m_result
));
212 wxPrintf(" %6d ms", m_watch
.Time());
225 wxString
GetResultStr(ResultType type
) const
227 static const char *resultTypeNames
[] =
234 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
235 ResultTypeNamesMismatch
);
237 return resultTypeNames
[type
];
246 typedef wxApp TestAppBase
;
248 typedef wxAppConsole TestAppBase
;
251 // The application class
253 class TestApp
: public TestAppBase
258 // standard overrides
259 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
260 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
261 virtual bool OnInit();
263 virtual int OnExit();
265 // used by events propagation test
266 virtual int FilterEvent(wxEvent
& event
);
267 virtual bool ProcessEvent(wxEvent
& event
);
269 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
270 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
273 void List(Test
*test
, const string
& parent
= "") const;
275 // call List() if m_list or runner.addTest() otherwise
276 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
281 runner
.addTest(test
);
284 // command lines options/parameters
289 wxArrayString m_registries
;
292 // event loop for GUI tests
293 wxEventLoop
* m_eventloop
;
295 // event handling hooks
296 FilterEventFunc m_filterEventFunc
;
297 ProcessEventFunc m_processEventFunc
;
300 IMPLEMENT_APP_NO_MAIN(TestApp
)
303 // ----------------------------------------------------------------------------
305 // ----------------------------------------------------------------------------
307 #ifdef wxUSE_VC_CRTDBG
309 static int TestCrtReportHook(int reportType
, char *message
, int *)
311 if ( reportType
!= _CRT_ASSERT
)
314 throw CrtAssertFailure(message
);
317 #endif // wxUSE_VC_CRTDBG
319 int main(int argc
, char **argv
)
321 // tests can be ran non-interactively so make sure we don't show any assert
322 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
323 // prevent them from completing
326 wxSetAssertHandler(TestAssertHandler
);
327 #endif // wxDEBUG_LEVEL
329 #ifdef wxUSE_VC_CRTDBG
330 _CrtSetReportHook(TestCrtReportHook
);
331 #endif // wxUSE_VC_CRTDBG
335 return wxEntry(argc
, argv
);
339 cerr
<< "\n" << GetExceptionMessage() << endl
;
345 extern void SetFilterEventFunc(FilterEventFunc func
)
347 wxGetApp().SetFilterEventFunc(func
);
350 extern void SetProcessEventFunc(ProcessEventFunc func
)
352 wxGetApp().SetProcessEventFunc(func
);
355 extern bool IsNetworkAvailable()
357 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
358 // wxCore we use a simple rough test:
360 wxSocketBase::Initialize();
363 if (!addr
.Hostname("www.google.com") || !addr
.Service("www"))
365 wxSocketBase::Shutdown();
370 sock
.SetTimeout(10); // 10 secs
371 bool online
= sock
.Connect(addr
);
373 wxSocketBase::Shutdown();
378 // helper of OnRun(): gets the test with the given name, returning NULL (and
379 // not an empty test suite) if there is no such test
380 static Test
*GetTestByName(const wxString
& name
)
383 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
386 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
387 if ( !suite
|| !suite
->countTestCases() )
389 // it's a bogus test, don't use it
399 // ----------------------------------------------------------------------------
401 // ----------------------------------------------------------------------------
407 m_filterEventFunc
= NULL
;
408 m_processEventFunc
= NULL
;
416 bool TestApp::OnInit()
418 if ( !TestAppBase::OnInit() )
422 cout
<< "Test program for wxWidgets GUI features\n"
424 cout
<< "Test program for wxWidgets non-GUI features\n"
426 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
429 // create a hidden parent window to be used as parent for the GUI controls
430 wxTestableFrame
* frame
= new wxTestableFrame();
433 m_eventloop
= new wxEventLoop
;
434 wxEventLoop::SetActive(m_eventloop
);
440 // The table of command line options
442 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
444 TestAppBase::OnInitCmdLine(parser
);
446 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
447 { wxCMD_LINE_SWITCH
, "l", "list",
448 "list the test suites, do not run them",
449 wxCMD_LINE_VAL_NONE
, 0 },
450 { wxCMD_LINE_SWITCH
, "L", "longlist",
451 "list the test cases, do not run them",
452 wxCMD_LINE_VAL_NONE
, 0 },
453 { wxCMD_LINE_SWITCH
, "d", "detail",
454 "print the test case names, run them",
455 wxCMD_LINE_VAL_NONE
, 0 },
456 { wxCMD_LINE_SWITCH
, "t", "timing",
457 "print names and measure running time of individual test, run them",
458 wxCMD_LINE_VAL_NONE
, 0 },
459 { wxCMD_LINE_OPTION
, "", "locale",
460 "locale to use when running the program",
461 wxCMD_LINE_VAL_STRING
, 0 },
462 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
463 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
467 parser
.SetDesc(cmdLineDesc
);
470 // Handle command line options
472 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
474 if (parser
.GetParamCount())
476 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
477 m_registries
.push_back(parser
.GetParam(i
));
480 m_longlist
= parser
.Found("longlist");
481 m_list
= m_longlist
|| parser
.Found("list");
482 m_timing
= parser
.Found("timing");
483 m_detail
= !m_timing
&& parser
.Found("detail");
486 if ( parser
.Found("locale", &loc
) )
488 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
491 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
495 m_locale
= new wxLocale(info
->Language
);
496 if ( !m_locale
->IsOk() )
498 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
503 return TestAppBase::OnCmdLineParsed(parser
);
507 int TestApp::FilterEvent(wxEvent
& event
)
509 if ( m_filterEventFunc
)
510 return (*m_filterEventFunc
)(event
);
512 return TestAppBase::FilterEvent(event
);
515 bool TestApp::ProcessEvent(wxEvent
& event
)
517 if ( m_processEventFunc
)
518 return (*m_processEventFunc
)(event
);
520 return TestAppBase::ProcessEvent(event
);
529 // make sure there's always an autorelease pool ready
530 wxMacAutoreleasePool autoreleasepool
;
535 // Switch off logging unless --verbose
536 bool verbose
= wxLog::GetVerbose();
537 wxLog::EnableLogging(verbose
);
539 bool verbose
= false;
542 CppUnit::TextTestRunner runner
;
544 if ( m_registries
.empty() )
546 // run or list all tests which use the CPPUNIT_TEST_SUITE_REGISTRATION() macro
547 // (i.e. those registered in the "All tests" registry); if there are other
548 // tests not registered with the CPPUNIT_TEST_SUITE_REGISTRATION() macro
549 // then they won't be listed/run!
550 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
554 cout
<< "\nNote that the list above is not complete as it doesn't include the \n";
555 cout
<< "tests disabled by default.\n";
558 else // run only the selected tests
560 for (size_t i
= 0; i
< m_registries
.size(); i
++)
562 const wxString reg
= m_registries
[i
];
563 Test
*test
= GetTestByName(reg
);
565 if ( !test
&& !reg
.EndsWith("TestCase") )
567 test
= GetTestByName(reg
+ "TestCase");
572 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
576 AddTest(runner
, test
);
583 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
586 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
587 // in some versions of cppunit: they write progress dots to cout (and not
588 // cerr) and don't flush it so all the dots appear at once at the end which
589 // is not very useful so unbuffer cout to work around this
590 cout
.setf(ios::unitbuf
);
592 // add detail listener if needed
593 DetailListener
detailListener(m_timing
);
594 if ( m_detail
|| m_timing
)
595 runner
.eventManager().addListener(&detailListener
);
597 // finally ensure that we report our own exceptions nicely instead of
598 // giving "uncaught exception of unknown type" messages
599 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
601 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
602 return runner
.run("", false, true, printProgress
) ? EXIT_SUCCESS
: EXIT_FAILURE
;
605 int TestApp::OnExit()
610 delete GetTopWindow();
611 wxEventLoop::SetActive(NULL
);
620 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
622 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
626 // take the last component of the name and append to the parent
627 name
= test
->getName();
628 string::size_type i
= name
.find_last_of(".:");
629 if (i
!= string::npos
)
630 name
= name
.substr(i
+ 1);
631 name
= parent
+ "." + name
;
633 // drop the 1st component from the display and indent
635 string::size_type j
= i
= name
.find('.', 1);
636 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
638 cout
<< " " << name
.substr(i
+ 1) << "\n";
641 typedef vector
<Test
*> Tests
;
642 typedef Tests::const_iterator Iter
;
644 const Tests
& tests
= suite
->getTests();
646 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
649 else if (m_longlist
) {
650 string::size_type i
= 0;
651 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
653 cout
<< " " << test
->getName() << "\n";