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>
37 #include <cppunit/TestResultCollector.h>
40 #pragma warning(default:4100)
42 #include "wx/afterstd.h"
44 #include "wx/cmdline.h"
49 #include "wx/msw/msvcrt.h"
53 #include "wx/osx/private.h"
57 #include "testableframe.h"
60 #include "wx/socket.h"
61 #include "wx/evtloop.h"
66 using CppUnit::TestSuite
;
67 using CppUnit::TestFactoryRegistry
;
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
74 // exception class for MSVC debug CRT assertion failures
75 #ifdef wxUSE_VC_CRTDBG
77 struct CrtAssertFailure
79 CrtAssertFailure(const char *message
) : m_msg(message
) { }
83 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure
);
86 #endif // wxUSE_VC_CRTDBG
90 static wxString
FormatAssertMessage(const wxString
& file
,
97 str
<< "wxWidgets assert: " << cond
<< " failed "
98 "at " << file
<< ":" << line
<< " in " << func
99 << " with message '" << msg
<< "'";
103 static void TestAssertHandler(const wxString
& file
,
105 const wxString
& func
,
106 const wxString
& cond
,
109 // Determine whether we can safely throw an exception to just make the test
110 // fail or whether we need to abort (in this case "msg" will contain the
111 // explanation why did we decide to do it).
112 wxString abortReason
;
113 if ( !wxIsMainThread() )
115 // Exceptions thrown from worker threads are not caught currently and
116 // so we'd just die without any useful information -- abort instead.
117 abortReason
= "in a worker thread";
119 else if ( uncaught_exception() )
121 // Throwing while already handling an exception would result in
122 // terminate() being called and we wouldn't get any useful information
123 // about why the test failed then.
124 abortReason
= "while handling an exception";
126 else // Can "safely" throw from here.
128 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
131 wxFprintf(stderr
, "%s %s -- aborting.",
132 FormatAssertMessage(file
, line
, func
, cond
, msg
),
138 #endif // wxDEBUG_LEVEL
140 // this function should only be called from a catch clause
141 static string
GetExceptionMessage()
150 catch ( TestAssertFailure
& e
)
152 msg
<< FormatAssertMessage(e
.m_file
, e
.m_line
, e
.m_func
,
155 #endif // wxDEBUG_LEVEL
156 #ifdef wxUSE_VC_CRTDBG
157 catch ( CrtAssertFailure
& e
)
159 msg
<< "CRT assert failure: " << e
.m_msg
;
161 #endif // wxUSE_VC_CRTDBG
162 catch ( std::exception
& e
)
164 msg
<< "std::exception: " << e
.what();
168 msg
= "Unknown exception caught.";
171 return string(msg
.mb_str());
174 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
175 // this context) exceptions
176 class wxUnitTestProtector
: public CppUnit::Protector
179 virtual bool protect(const CppUnit::Functor
&functor
,
180 const CppUnit::ProtectorContext
& context
)
186 catch ( std::exception
& )
188 // cppunit deals with the standard exceptions itself, let it do as
189 // it output more details (especially for std::exception-derived
190 // CppUnit::Exception) than we do
195 reportError(context
, CppUnit::Message("Uncaught exception",
196 GetExceptionMessage()));
203 // Displays the test name before starting to execute it: this helps with
204 // diagnosing where exactly does a test crash or hang when/if it does.
205 class DetailListener
: public CppUnit::TestListener
208 DetailListener(bool doTiming
= false):
209 CppUnit::TestListener(),
214 virtual void startTest(CppUnit::Test
*test
)
216 wxPrintf(" %-60s ", test
->getName());
217 m_result
= RESULT_OK
;
221 virtual void addFailure(const CppUnit::TestFailure
& failure
)
223 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
226 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
229 wxPrintf(GetResultStr(m_result
));
231 wxPrintf(" %6ld ms", m_watch
.Time());
244 wxString
GetResultStr(ResultType type
) const
246 static const char *resultTypeNames
[] =
253 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
254 ResultTypeNamesMismatch
);
256 return resultTypeNames
[type
];
265 typedef wxApp TestAppBase
;
267 typedef wxAppConsole TestAppBase
;
270 // The application class
272 class TestApp
: public TestAppBase
277 // standard overrides
278 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
279 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
280 virtual bool OnInit();
282 virtual int OnExit();
284 // used by events propagation test
285 virtual int FilterEvent(wxEvent
& event
);
286 virtual bool ProcessEvent(wxEvent
& event
);
288 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
289 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
292 void List(Test
*test
, const string
& parent
= "") const;
294 // call List() if m_list or runner.addTest() otherwise
295 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
300 runner
.addTest(test
);
303 // command lines options/parameters
308 wxArrayString m_registries
;
311 // event loop for GUI tests
312 wxEventLoop
* m_eventloop
;
314 // event handling hooks
315 FilterEventFunc m_filterEventFunc
;
316 ProcessEventFunc m_processEventFunc
;
319 IMPLEMENT_APP_NO_MAIN(TestApp
)
322 // ----------------------------------------------------------------------------
324 // ----------------------------------------------------------------------------
326 #ifdef wxUSE_VC_CRTDBG
328 static int TestCrtReportHook(int reportType
, char *message
, int *)
330 if ( reportType
!= _CRT_ASSERT
)
333 throw CrtAssertFailure(message
);
336 #endif // wxUSE_VC_CRTDBG
338 int main(int argc
, char **argv
)
340 // tests can be ran non-interactively so make sure we don't show any assert
341 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
342 // prevent them from completing
345 wxSetAssertHandler(TestAssertHandler
);
346 #endif // wxDEBUG_LEVEL
348 #ifdef wxUSE_VC_CRTDBG
349 _CrtSetReportHook(TestCrtReportHook
);
350 #endif // wxUSE_VC_CRTDBG
354 return wxEntry(argc
, argv
);
358 cerr
<< "\n" << GetExceptionMessage() << endl
;
364 extern void SetFilterEventFunc(FilterEventFunc func
)
366 wxGetApp().SetFilterEventFunc(func
);
369 extern void SetProcessEventFunc(ProcessEventFunc func
)
371 wxGetApp().SetProcessEventFunc(func
);
374 extern bool IsNetworkAvailable()
376 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
377 // wxCore we use a simple rough test:
379 wxSocketBase::Initialize();
382 if (!addr
.Hostname("www.google.com") || !addr
.Service("www"))
384 wxSocketBase::Shutdown();
389 sock
.SetTimeout(10); // 10 secs
390 bool online
= sock
.Connect(addr
);
392 wxSocketBase::Shutdown();
397 // helper of OnRun(): gets the test with the given name, returning NULL (and
398 // not an empty test suite) if there is no such test
399 static Test
*GetTestByName(const wxString
& name
)
402 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
405 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
406 if ( !suite
|| !suite
->countTestCases() )
408 // it's a bogus test, don't use it
418 // ----------------------------------------------------------------------------
420 // ----------------------------------------------------------------------------
426 m_filterEventFunc
= NULL
;
427 m_processEventFunc
= NULL
;
435 bool TestApp::OnInit()
437 if ( !TestAppBase::OnInit() )
441 cout
<< "Test program for wxWidgets GUI features\n"
443 cout
<< "Test program for wxWidgets non-GUI features\n"
445 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
448 // create a hidden parent window to be used as parent for the GUI controls
449 wxTestableFrame
* frame
= new wxTestableFrame();
452 m_eventloop
= new wxEventLoop
;
453 wxEventLoop::SetActive(m_eventloop
);
459 // The table of command line options
461 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
463 TestAppBase::OnInitCmdLine(parser
);
465 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
466 { wxCMD_LINE_SWITCH
, "l", "list",
467 "list the test suites, do not run them",
468 wxCMD_LINE_VAL_NONE
, 0 },
469 { wxCMD_LINE_SWITCH
, "L", "longlist",
470 "list the test cases, do not run them",
471 wxCMD_LINE_VAL_NONE
, 0 },
472 { wxCMD_LINE_SWITCH
, "d", "detail",
473 "print the test case names, run them",
474 wxCMD_LINE_VAL_NONE
, 0 },
475 { wxCMD_LINE_SWITCH
, "t", "timing",
476 "print names and measure running time of individual test, run them",
477 wxCMD_LINE_VAL_NONE
, 0 },
478 { wxCMD_LINE_OPTION
, "", "locale",
479 "locale to use when running the program",
480 wxCMD_LINE_VAL_STRING
, 0 },
481 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
482 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
486 parser
.SetDesc(cmdLineDesc
);
489 // Handle command line options
491 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
493 if (parser
.GetParamCount())
495 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
496 m_registries
.push_back(parser
.GetParam(i
));
499 m_longlist
= parser
.Found("longlist");
500 m_list
= m_longlist
|| parser
.Found("list");
501 m_timing
= parser
.Found("timing");
502 m_detail
= !m_timing
&& parser
.Found("detail");
505 if ( parser
.Found("locale", &loc
) )
507 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
510 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
514 m_locale
= new wxLocale(info
->Language
);
515 if ( !m_locale
->IsOk() )
517 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
522 return TestAppBase::OnCmdLineParsed(parser
);
526 int TestApp::FilterEvent(wxEvent
& event
)
528 if ( m_filterEventFunc
)
529 return (*m_filterEventFunc
)(event
);
531 return TestAppBase::FilterEvent(event
);
534 bool TestApp::ProcessEvent(wxEvent
& event
)
536 if ( m_processEventFunc
)
537 return (*m_processEventFunc
)(event
);
539 return TestAppBase::ProcessEvent(event
);
548 // make sure there's always an autorelease pool ready
549 wxMacAutoreleasePool autoreleasepool
;
554 // Switch off logging unless --verbose
555 bool verbose
= wxLog::GetVerbose();
556 wxLog::EnableLogging(verbose
);
558 bool verbose
= false;
561 CppUnit::TextTestRunner runner
;
563 if ( m_registries
.empty() )
565 // run or list all tests which use the CPPUNIT_TEST_SUITE_REGISTRATION() macro
566 // (i.e. those registered in the "All tests" registry); if there are other
567 // tests not registered with the CPPUNIT_TEST_SUITE_REGISTRATION() macro
568 // then they won't be listed/run!
569 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
573 cout
<< "\nNote that the list above is not complete as it doesn't include the \n";
574 cout
<< "tests disabled by default.\n";
577 else // run only the selected tests
579 for (size_t i
= 0; i
< m_registries
.size(); i
++)
581 const wxString reg
= m_registries
[i
];
582 Test
*test
= GetTestByName(reg
);
584 if ( !test
&& !reg
.EndsWith("TestCase") )
586 test
= GetTestByName(reg
+ "TestCase");
591 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
595 AddTest(runner
, test
);
602 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
605 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
606 // in some versions of cppunit: they write progress dots to cout (and not
607 // cerr) and don't flush it so all the dots appear at once at the end which
608 // is not very useful so unbuffer cout to work around this
609 cout
.setf(ios::unitbuf
);
611 // add detail listener if needed
612 DetailListener
detailListener(m_timing
);
613 if ( m_detail
|| m_timing
)
614 runner
.eventManager().addListener(&detailListener
);
616 // finally ensure that we report our own exceptions nicely instead of
617 // giving "uncaught exception of unknown type" messages
618 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
620 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
621 runner
.run("", false, true, printProgress
);
623 return runner
.result().testFailures() == 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
626 int TestApp::OnExit()
631 delete GetTopWindow();
632 wxEventLoop::SetActive(NULL
);
641 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
643 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
647 // take the last component of the name and append to the parent
648 name
= test
->getName();
649 string::size_type i
= name
.find_last_of(".:");
650 if (i
!= string::npos
)
651 name
= name
.substr(i
+ 1);
652 name
= parent
+ "." + name
;
654 // drop the 1st component from the display and indent
656 string::size_type j
= i
= name
.find('.', 1);
657 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
659 cout
<< " " << name
.substr(i
+ 1) << "\n";
662 typedef vector
<Test
*> Tests
;
663 typedef Tests::const_iterator Iter
;
665 const Tests
& tests
= suite
->getTests();
667 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
670 else if (m_longlist
) {
671 string::size_type i
= 0;
672 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
674 cout
<< " " << test
->getName() << "\n";