1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Test program for wxWidgets
4 // Author: Mike Wetherell
6 // Copyright: (c) 2004 Mike Wetherell
7 // Licence: wxWidgets 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)
31 #include <cppunit/TestListener.h>
33 #pragma warning(default:4100)
35 #include <cppunit/Protector.h>
36 #include <cppunit/Test.h>
37 #include <cppunit/TestResult.h>
38 #include <cppunit/TestFailure.h>
39 #include "wx/afterstd.h"
41 #include "wx/cmdline.h"
45 #include "wx/msw/msvcrt.h"
49 #include "wx/osx/private.h"
52 #include "wx/socket.h"
57 using CppUnit::TestSuite
;
58 using CppUnit::TestFactoryRegistry
;
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
65 // exception class for MSVC debug CRT assertion failures
66 #ifdef wxUSE_VC_CRTDBG
68 struct CrtAssertFailure
70 CrtAssertFailure(const char *message
) : m_msg(message
) { }
74 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure
);
77 #endif // wxUSE_VC_CRTDBG
79 // this function should only be called from a catch clause
80 static string
GetExceptionMessage()
89 catch ( TestAssertFailure
& e
)
91 msg
<< "wxWidgets assert: " << e
.m_cond
<< " failed "
92 "at " << e
.m_file
<< ":" << e
.m_line
<< " in " << e
.m_func
93 << " with message '" << e
.m_msg
<< "'";
95 #endif // wxDEBUG_LEVEL
96 #ifdef wxUSE_VC_CRTDBG
97 catch ( CrtAssertFailure
& e
)
99 msg
<< "CRT assert failure: " << e
.m_msg
;
101 #endif // wxUSE_VC_CRTDBG
102 catch ( std::exception
& e
)
104 msg
<< "std::exception: " << e
.what();
108 msg
= "Unknown exception caught.";
111 return string(msg
.mb_str());
114 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
115 // this context) exceptions
116 class wxUnitTestProtector
: public CppUnit::Protector
119 virtual bool protect(const CppUnit::Functor
&functor
,
120 const CppUnit::ProtectorContext
& context
)
126 catch ( std::exception
& )
128 // cppunit deals with the standard exceptions itself, let it do as
129 // it output more details (especially for std::exception-derived
130 // CppUnit::Exception) than we do
135 reportError(context
, CppUnit::Message("Uncaught exception",
136 GetExceptionMessage()));
143 // Displays the test name before starting to execute it: this helps with
144 // diagnosing where exactly does a test crash or hang when/if it does.
145 class DetailListener
: public CppUnit::TestListener
148 DetailListener(bool doTiming
= false):
149 CppUnit::TestListener(),
154 virtual void startTest(CppUnit::Test
*test
)
156 wxPrintf(" %-60s ", test
->getName());
157 m_result
= RESULT_OK
;
161 virtual void addFailure(const CppUnit::TestFailure
& failure
)
163 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
166 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
169 wxPrintf(GetResultStr(m_result
));
171 wxPrintf(" %6d ms", m_watch
.Time());
184 wxString
GetResultStr(ResultType type
) const
186 static const char *resultTypeNames
[] =
193 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
194 ResultTypeNamesMismatch
);
196 return resultTypeNames
[type
];
205 typedef wxApp TestAppBase
;
207 typedef wxAppConsole TestAppBase
;
210 // The application class
212 class TestApp
: public TestAppBase
217 // standard overrides
218 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
219 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
220 virtual bool OnInit();
222 virtual int OnExit();
224 // used by events propagation test
225 virtual int FilterEvent(wxEvent
& event
);
226 virtual bool ProcessEvent(wxEvent
& event
);
228 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
229 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
232 void List(Test
*test
, const string
& parent
= "") const;
234 // call List() if m_list or runner.addTest() otherwise
235 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
240 runner
.addTest(test
);
243 // command lines options/parameters
248 wxArrayString m_registries
;
251 // event handling hooks
252 FilterEventFunc m_filterEventFunc
;
253 ProcessEventFunc m_processEventFunc
;
256 IMPLEMENT_APP_NO_MAIN(TestApp
)
259 // ----------------------------------------------------------------------------
261 // ----------------------------------------------------------------------------
263 #ifdef wxUSE_VC_CRTDBG
265 static int TestCrtReportHook(int reportType
, char *message
, int *)
267 if ( reportType
!= _CRT_ASSERT
)
270 throw CrtAssertFailure(message
);
273 #endif // wxUSE_VC_CRTDBG
277 static void TestAssertHandler(const wxString
& file
,
279 const wxString
& func
,
280 const wxString
& cond
,
283 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
286 #endif // wxDEBUG_LEVEL
288 int main(int argc
, char **argv
)
290 // tests can be ran non-interactively so make sure we don't show any assert
291 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
292 // prevent them from completing
295 wxSetAssertHandler(TestAssertHandler
);
296 #endif // wxDEBUG_LEVEL
298 #ifdef wxUSE_VC_CRTDBG
299 _CrtSetReportHook(TestCrtReportHook
);
300 #endif // wxUSE_VC_CRTDBG
304 return wxEntry(argc
, argv
);
308 cerr
<< "\n" << GetExceptionMessage() << endl
;
314 extern void SetFilterEventFunc(FilterEventFunc func
)
316 wxGetApp().SetFilterEventFunc(func
);
319 extern void SetProcessEventFunc(ProcessEventFunc func
)
321 wxGetApp().SetProcessEventFunc(func
);
324 extern bool IsNetworkAvailable()
326 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
327 // wxCore we use a simple rough test:
329 wxSocketBase::Initialize();
332 if (!addr
.Hostname("www.google.com") || !addr
.Service("www"))
334 wxSocketBase::Shutdown();
339 bool online
= sock
.Connect(addr
);
341 wxSocketBase::Shutdown();
346 // helper of OnRun(): gets the test with the given name, returning NULL (and
347 // not an empty test suite) if there is no such test
348 static Test
*GetTestByName(const wxString
& name
)
351 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
354 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
355 if ( !suite
|| !suite
->countTestCases() )
357 // it's a bogus test, don't use it
367 // ----------------------------------------------------------------------------
369 // ----------------------------------------------------------------------------
375 m_filterEventFunc
= NULL
;
376 m_processEventFunc
= NULL
;
383 bool TestApp::OnInit()
385 if ( !TestAppBase::OnInit() )
388 cout
<< "Test program for wxWidgets\n"
389 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
392 // create a hidden parent window to be used as parent for the GUI controls
393 new wxFrame(NULL
, wxID_ANY
, "Hidden wx test frame");
399 // The table of command line options
401 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
403 TestAppBase::OnInitCmdLine(parser
);
405 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
406 { wxCMD_LINE_SWITCH
, "l", "list",
407 "list the test suites, do not run them",
408 wxCMD_LINE_VAL_NONE
, 0 },
409 { wxCMD_LINE_SWITCH
, "L", "longlist",
410 "list the test cases, do not run them",
411 wxCMD_LINE_VAL_NONE
, 0 },
412 { wxCMD_LINE_SWITCH
, "d", "detail",
413 "print the test case names, run them",
414 wxCMD_LINE_VAL_NONE
, 0 },
415 { wxCMD_LINE_SWITCH
, "t", "timing",
416 "print names and mesure running time of individual test, run them",
417 wxCMD_LINE_VAL_NONE
, 0 },
418 { wxCMD_LINE_OPTION
, "", "locale",
419 "locale to use when running the program",
420 wxCMD_LINE_VAL_STRING
, 0 },
421 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
422 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
426 parser
.SetDesc(cmdLineDesc
);
429 // Handle command line options
431 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
433 if (parser
.GetParamCount())
435 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
436 m_registries
.push_back(parser
.GetParam(i
));
439 m_longlist
= parser
.Found("longlist");
440 m_list
= m_longlist
|| parser
.Found("list");
441 m_timing
= parser
.Found("timing");
442 m_detail
= !m_timing
&& parser
.Found("detail");
445 if ( parser
.Found("locale", &loc
) )
447 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
450 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
454 m_locale
= new wxLocale(info
->Language
);
455 if ( !m_locale
->IsOk() )
457 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
462 return TestAppBase::OnCmdLineParsed(parser
);
466 int TestApp::FilterEvent(wxEvent
& event
)
468 if ( m_filterEventFunc
)
469 return (*m_filterEventFunc
)(event
);
471 return TestAppBase::FilterEvent(event
);
474 bool TestApp::ProcessEvent(wxEvent
& event
)
476 if ( m_processEventFunc
)
477 return (*m_processEventFunc
)(event
);
479 return TestAppBase::ProcessEvent(event
);
488 // make sure there's always an autorelease pool ready
489 wxMacAutoreleasePool autoreleasepool
;
494 // Switch off logging unless --verbose
495 bool verbose
= wxLog::GetVerbose();
496 wxLog::EnableLogging(verbose
);
498 bool verbose
= false;
501 CppUnit::TextTestRunner runner
;
503 if ( m_registries
.empty() )
505 // run or list all tests
506 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
508 else // run only the selected tests
510 for (size_t i
= 0; i
< m_registries
.size(); i
++)
512 const wxString reg
= m_registries
[i
];
513 Test
*test
= GetTestByName(reg
);
515 if ( !test
&& !reg
.EndsWith("TestCase") )
517 test
= GetTestByName(reg
+ "TestCase");
522 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
526 AddTest(runner
, test
);
533 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
536 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
537 // in some versions of cppunit: they write progress dots to cout (and not
538 // cerr) and don't flush it so all the dots appear at once at the end which
539 // is not very useful so unbuffer cout to work around this
540 cout
.setf(ios::unitbuf
);
542 // add detail listener if needed
543 DetailListener
detailListener(m_timing
);
544 if ( m_detail
|| m_timing
)
545 runner
.eventManager().addListener(&detailListener
);
547 // finally ensure that we report our own exceptions nicely instead of
548 // giving "uncaught exception of unknown type" messages
549 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
551 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
552 return runner
.run("", false, true, printProgress
) ? EXIT_SUCCESS
: EXIT_FAILURE
;
555 int TestApp::OnExit()
560 delete GetTopWindow();
568 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
570 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
574 // take the last component of the name and append to the parent
575 name
= test
->getName();
576 string::size_type i
= name
.find_last_of(".:");
577 if (i
!= string::npos
)
578 name
= name
.substr(i
+ 1);
579 name
= parent
+ "." + name
;
581 // drop the 1st component from the display and indent
583 string::size_type j
= i
= name
.find('.', 1);
584 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
586 cout
<< " " << name
.substr(i
+ 1) << "\n";
589 typedef vector
<Test
*> Tests
;
590 typedef Tests::const_iterator Iter
;
592 const Tests
& tests
= suite
->getTests();
594 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
597 else if (m_longlist
) {
598 string::size_type i
= 0;
599 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
601 cout
<< " " << test
->getName() << "\n";