1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Test program for wxWidgets
4 // Author: Mike Wetherell
6 // Copyright: (c) 2004 Mike Wetherell
7 // Licence: wxWidgets licence
8 ///////////////////////////////////////////////////////////////////////////////
10 // For compilers that support precompilation, includes "wx/wx.h"
18 // for all others, include the necessary headers
23 #include "wx/beforestd.h"
25 #pragma warning(disable:4100)
27 #include <cppunit/TestListener.h>
29 #pragma warning(default:4100)
31 #include <cppunit/Protector.h>
32 #include <cppunit/Test.h>
33 #include <cppunit/TestResult.h>
34 #include <cppunit/TestFailure.h>
35 #include "wx/afterstd.h"
37 #include "wx/cmdline.h"
41 #include "wx/msw/msvcrt.h"
45 #include "wx/osx/private.h"
51 using CppUnit::TestSuite
;
52 using CppUnit::TestFactoryRegistry
;
54 // exception class for MSVC debug CRT assertion failures
55 #ifdef wxUSE_VC_CRTDBG
57 struct CrtAssertFailure
59 CrtAssertFailure(const char *message
) : m_msg(message
) { }
63 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure
);
66 #endif // wxUSE_VC_CRTDBG
68 // this function should only be called from a catch clause
69 static string
GetExceptionMessage()
78 catch ( TestAssertFailure
& e
)
80 msg
<< "wxWidgets assert: " << e
.m_cond
<< " failed "
81 "at " << e
.m_file
<< ":" << e
.m_line
<< " in " << e
.m_func
82 << " with message " << e
.m_msg
;
84 #endif // wxDEBUG_LEVEL
85 #ifdef wxUSE_VC_CRTDBG
86 catch ( CrtAssertFailure
& e
)
88 msg
<< "CRT assert failure: " << e
.m_msg
;
90 #endif // wxUSE_VC_CRTDBG
91 catch ( std::exception
& e
)
93 msg
<< "std::exception: " << e
.what();
97 msg
= "Unknown exception caught.";
100 return string(msg
.mb_str());
103 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
104 // this context) exceptions
105 class wxUnitTestProtector
: public CppUnit::Protector
108 virtual bool protect(const CppUnit::Functor
&functor
,
109 const CppUnit::ProtectorContext
& context
)
115 catch ( std::exception
& )
117 // cppunit deals with the standard exceptions itself, let it do as
118 // it output more details (especially for std::exception-derived
119 // CppUnit::Exception) than we do
124 reportError(context
, CppUnit::Message("Uncaught exception",
125 GetExceptionMessage()));
132 // Displays the test name before starting to execute it: this helps with
133 // diagnosing where exactly does a test crash or hang when/if it does.
134 class DetailListener
: public CppUnit::TestListener
137 DetailListener(bool doTiming
= false):
138 CppUnit::TestListener(),
143 virtual void startTest(CppUnit::Test
*test
)
145 wxPrintf(" %-60s ", test
->getName());
146 m_result
= RESULT_OK
;
150 virtual void addFailure(const CppUnit::TestFailure
& failure
)
152 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
155 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
158 wxPrintf(GetResultStr(m_result
));
160 wxPrintf(" %6d ms", m_watch
.Time());
173 wxString
GetResultStr(ResultType type
) const
175 static const char *resultTypeNames
[] =
182 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
183 ResultTypeNamesMismatch
);
185 return resultTypeNames
[type
];
194 typedef wxApp TestAppBase
;
196 typedef wxAppConsole TestAppBase
;
199 // The application class
201 class TestApp
: public TestAppBase
206 // standard overrides
207 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
208 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
209 virtual bool OnInit();
211 virtual int OnExit();
213 // used by events propagation test
214 virtual int FilterEvent(wxEvent
& event
);
215 virtual bool ProcessEvent(wxEvent
& event
);
217 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
218 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
221 void List(Test
*test
, const string
& parent
= "") const;
223 // call List() if m_list or runner.addTest() otherwise
224 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
229 runner
.addTest(test
);
232 // command lines options/parameters
237 wxArrayString m_registries
;
240 // event handling hooks
241 FilterEventFunc m_filterEventFunc
;
242 ProcessEventFunc m_processEventFunc
;
245 IMPLEMENT_APP_NO_MAIN(TestApp
)
247 #ifdef wxUSE_VC_CRTDBG
249 static int TestCrtReportHook(int reportType
, char *message
, int *)
251 if ( reportType
!= _CRT_ASSERT
)
254 throw CrtAssertFailure(message
);
257 #endif // wxUSE_VC_CRTDBG
261 static void TestAssertHandler(const wxString
& file
,
263 const wxString
& func
,
264 const wxString
& cond
,
267 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
270 #endif // wxDEBUG_LEVEL
272 int main(int argc
, char **argv
)
274 // tests can be ran non-interactively so make sure we don't show any assert
275 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
276 // prevent them from completing
279 wxSetAssertHandler(TestAssertHandler
);
280 #endif // wxDEBUG_LEVEL
282 #ifdef wxUSE_VC_CRTDBG
283 _CrtSetReportHook(TestCrtReportHook
);
284 #endif // wxUSE_VC_CRTDBG
288 return wxEntry(argc
, argv
);
292 cerr
<< "\n" << GetExceptionMessage() << endl
;
302 m_filterEventFunc
= NULL
;
303 m_processEventFunc
= NULL
;
310 bool TestApp::OnInit()
312 if ( !TestAppBase::OnInit() )
315 cout
<< "Test program for wxWidgets\n"
316 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
319 // create a hidden parent window to be used as parent for the GUI controls
320 new wxFrame(NULL
, wxID_ANY
, "Hidden wx test frame");
326 // The table of command line options
328 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
330 TestAppBase::OnInitCmdLine(parser
);
332 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
333 { wxCMD_LINE_SWITCH
, "l", "list",
334 "list the test suites, do not run them",
335 wxCMD_LINE_VAL_NONE
, 0 },
336 { wxCMD_LINE_SWITCH
, "L", "longlist",
337 "list the test cases, do not run them",
338 wxCMD_LINE_VAL_NONE
, 0 },
339 { wxCMD_LINE_SWITCH
, "d", "detail",
340 "print the test case names, run them",
341 wxCMD_LINE_VAL_NONE
, 0 },
342 { wxCMD_LINE_SWITCH
, "t", "timing",
343 "print names and mesure running time of individual test, run them",
344 wxCMD_LINE_VAL_NONE
, 0 },
345 { wxCMD_LINE_OPTION
, "", "locale",
346 "locale to use when running the program",
347 wxCMD_LINE_VAL_STRING
, 0 },
348 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
349 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
353 parser
.SetDesc(cmdLineDesc
);
356 // Handle command line options
358 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
360 if (parser
.GetParamCount())
362 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
363 m_registries
.push_back(parser
.GetParam(i
));
366 m_longlist
= parser
.Found("longlist");
367 m_list
= m_longlist
|| parser
.Found("list");
368 m_timing
= parser
.Found("timing");
369 m_detail
= !m_timing
&& parser
.Found("detail");
372 if ( parser
.Found("locale", &loc
) )
374 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
377 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
381 m_locale
= new wxLocale(info
->Language
);
382 if ( !m_locale
->IsOk() )
384 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
389 return TestAppBase::OnCmdLineParsed(parser
);
393 int TestApp::FilterEvent(wxEvent
& event
)
395 if ( m_filterEventFunc
)
396 return (*m_filterEventFunc
)(event
);
398 return TestAppBase::FilterEvent(event
);
401 bool TestApp::ProcessEvent(wxEvent
& event
)
403 if ( m_processEventFunc
)
404 return (*m_processEventFunc
)(event
);
406 return TestAppBase::ProcessEvent(event
);
409 extern void SetFilterEventFunc(FilterEventFunc func
)
411 wxGetApp().SetFilterEventFunc(func
);
414 extern void SetProcessEventFunc(ProcessEventFunc func
)
416 wxGetApp().SetProcessEventFunc(func
);
419 // helper of OnRun(): gets the test with the given name, returning NULL (and
420 // not an empty test suite) if there is no such test
421 static Test
*GetTestByName(const wxString
& name
)
424 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
427 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
428 if ( !suite
|| !suite
->countTestCases() )
430 // it's a bogus test, don't use it
445 // make sure there's always an autorelease pool ready
446 wxMacAutoreleasePool autoreleasepool
;
451 // Switch off logging unless --verbose
452 bool verbose
= wxLog::GetVerbose();
453 wxLog::EnableLogging(verbose
);
455 bool verbose
= false;
458 CppUnit::TextTestRunner runner
;
460 if ( m_registries
.empty() )
462 // run or list all tests
463 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
465 else // run only the selected tests
467 for (size_t i
= 0; i
< m_registries
.size(); i
++)
469 const wxString reg
= m_registries
[i
];
470 Test
*test
= GetTestByName(reg
);
472 if ( !test
&& !reg
.EndsWith("TestCase") )
474 test
= GetTestByName(reg
+ "TestCase");
479 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
483 AddTest(runner
, test
);
490 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
493 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
494 // in some versions of cppunit: they write progress dots to cout (and not
495 // cerr) and don't flush it so all the dots appear at once at the end which
496 // is not very useful so unbuffer cout to work around this
497 cout
.setf(ios::unitbuf
);
499 // add detail listener if needed
500 DetailListener
detailListener(m_timing
);
501 if ( m_detail
|| m_timing
)
502 runner
.eventManager().addListener(&detailListener
);
504 // finally ensure that we report our own exceptions nicely instead of
505 // giving "uncaught exception of unknown type" messages
506 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
508 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
509 return runner
.run("", false, true, printProgress
) ? EXIT_SUCCESS
: EXIT_FAILURE
;
512 int TestApp::OnExit()
517 delete GetTopWindow();
525 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
527 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
531 // take the last component of the name and append to the parent
532 name
= test
->getName();
533 string::size_type i
= name
.find_last_of(".:");
534 if (i
!= string::npos
)
535 name
= name
.substr(i
+ 1);
536 name
= parent
+ "." + name
;
538 // drop the 1st component from the display and indent
540 string::size_type j
= i
= name
.find('.', 1);
541 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
543 cout
<< " " << name
.substr(i
+ 1) << "\n";
546 typedef vector
<Test
*> Tests
;
547 typedef Tests::const_iterator Iter
;
549 const Tests
& tests
= suite
->getTests();
551 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
554 else if (m_longlist
) {
555 string::size_type i
= 0;
556 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
558 cout
<< " " << test
->getName() << "\n";