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)
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"
54 #include "wx/socket.h"
59 using CppUnit::TestSuite
;
60 using CppUnit::TestFactoryRegistry
;
63 // ----------------------------------------------------------------------------
65 // ----------------------------------------------------------------------------
67 // exception class for MSVC debug CRT assertion failures
68 #ifdef wxUSE_VC_CRTDBG
70 struct CrtAssertFailure
72 CrtAssertFailure(const char *message
) : m_msg(message
) { }
76 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure
);
79 #endif // wxUSE_VC_CRTDBG
81 // this function should only be called from a catch clause
82 static string
GetExceptionMessage()
91 catch ( TestAssertFailure
& e
)
93 msg
<< "wxWidgets assert: " << e
.m_cond
<< " failed "
94 "at " << e
.m_file
<< ":" << e
.m_line
<< " in " << e
.m_func
95 << " with message '" << e
.m_msg
<< "'";
97 #endif // wxDEBUG_LEVEL
98 #ifdef wxUSE_VC_CRTDBG
99 catch ( CrtAssertFailure
& e
)
101 msg
<< "CRT assert failure: " << e
.m_msg
;
103 #endif // wxUSE_VC_CRTDBG
104 catch ( std::exception
& e
)
106 msg
<< "std::exception: " << e
.what();
110 msg
= "Unknown exception caught.";
113 return string(msg
.mb_str());
116 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
117 // this context) exceptions
118 class wxUnitTestProtector
: public CppUnit::Protector
121 virtual bool protect(const CppUnit::Functor
&functor
,
122 const CppUnit::ProtectorContext
& context
)
128 catch ( std::exception
& )
130 // cppunit deals with the standard exceptions itself, let it do as
131 // it output more details (especially for std::exception-derived
132 // CppUnit::Exception) than we do
137 reportError(context
, CppUnit::Message("Uncaught exception",
138 GetExceptionMessage()));
145 // Displays the test name before starting to execute it: this helps with
146 // diagnosing where exactly does a test crash or hang when/if it does.
147 class DetailListener
: public CppUnit::TestListener
150 DetailListener(bool doTiming
= false):
151 CppUnit::TestListener(),
156 virtual void startTest(CppUnit::Test
*test
)
158 wxPrintf(" %-60s ", test
->getName());
159 m_result
= RESULT_OK
;
163 virtual void addFailure(const CppUnit::TestFailure
& failure
)
165 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
168 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
171 wxPrintf(GetResultStr(m_result
));
173 wxPrintf(" %6d ms", m_watch
.Time());
186 wxString
GetResultStr(ResultType type
) const
188 static const char *resultTypeNames
[] =
195 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
196 ResultTypeNamesMismatch
);
198 return resultTypeNames
[type
];
207 typedef wxApp TestAppBase
;
209 typedef wxAppConsole TestAppBase
;
212 // The application class
214 class TestApp
: public TestAppBase
219 // standard overrides
220 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
221 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
222 virtual bool OnInit();
224 virtual int OnExit();
226 // used by events propagation test
227 virtual int FilterEvent(wxEvent
& event
);
228 virtual bool ProcessEvent(wxEvent
& event
);
230 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
231 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
234 void List(Test
*test
, const string
& parent
= "") const;
236 // call List() if m_list or runner.addTest() otherwise
237 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
242 runner
.addTest(test
);
245 // command lines options/parameters
250 wxArrayString m_registries
;
253 // event handling hooks
254 FilterEventFunc m_filterEventFunc
;
255 ProcessEventFunc m_processEventFunc
;
258 IMPLEMENT_APP_NO_MAIN(TestApp
)
261 // ----------------------------------------------------------------------------
263 // ----------------------------------------------------------------------------
265 #ifdef wxUSE_VC_CRTDBG
267 static int TestCrtReportHook(int reportType
, char *message
, int *)
269 if ( reportType
!= _CRT_ASSERT
)
272 throw CrtAssertFailure(message
);
275 #endif // wxUSE_VC_CRTDBG
279 static void TestAssertHandler(const wxString
& file
,
281 const wxString
& func
,
282 const wxString
& cond
,
285 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
288 #endif // wxDEBUG_LEVEL
290 int main(int argc
, char **argv
)
292 // tests can be ran non-interactively so make sure we don't show any assert
293 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
294 // prevent them from completing
297 wxSetAssertHandler(TestAssertHandler
);
298 #endif // wxDEBUG_LEVEL
300 #ifdef wxUSE_VC_CRTDBG
301 _CrtSetReportHook(TestCrtReportHook
);
302 #endif // wxUSE_VC_CRTDBG
306 return wxEntry(argc
, argv
);
310 cerr
<< "\n" << GetExceptionMessage() << endl
;
316 extern void SetFilterEventFunc(FilterEventFunc func
)
318 wxGetApp().SetFilterEventFunc(func
);
321 extern void SetProcessEventFunc(ProcessEventFunc func
)
323 wxGetApp().SetProcessEventFunc(func
);
326 extern bool IsNetworkAvailable()
328 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
329 // wxCore we use a simple rough test:
331 wxSocketBase::Initialize();
334 if (!addr
.Hostname("www.google.com") || !addr
.Service("www"))
336 wxSocketBase::Shutdown();
341 sock
.SetTimeout(10); // 10 secs
342 bool online
= sock
.Connect(addr
);
344 wxSocketBase::Shutdown();
349 // helper of OnRun(): gets the test with the given name, returning NULL (and
350 // not an empty test suite) if there is no such test
351 static Test
*GetTestByName(const wxString
& name
)
354 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
357 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
358 if ( !suite
|| !suite
->countTestCases() )
360 // it's a bogus test, don't use it
370 // ----------------------------------------------------------------------------
372 // ----------------------------------------------------------------------------
378 m_filterEventFunc
= NULL
;
379 m_processEventFunc
= NULL
;
386 bool TestApp::OnInit()
388 if ( !TestAppBase::OnInit() )
392 cout
<< "Test program for wxWidgets GUI features\n"
394 cout
<< "Test program for wxWidgets non-GUI features\n"
396 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
399 // create a hidden parent window to be used as parent for the GUI controls
400 new wxFrame(NULL
, wxID_ANY
, "Hidden wx test frame");
406 // The table of command line options
408 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
410 TestAppBase::OnInitCmdLine(parser
);
412 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
413 { wxCMD_LINE_SWITCH
, "l", "list",
414 "list the test suites, do not run them",
415 wxCMD_LINE_VAL_NONE
, 0 },
416 { wxCMD_LINE_SWITCH
, "L", "longlist",
417 "list the test cases, do not run them",
418 wxCMD_LINE_VAL_NONE
, 0 },
419 { wxCMD_LINE_SWITCH
, "d", "detail",
420 "print the test case names, run them",
421 wxCMD_LINE_VAL_NONE
, 0 },
422 { wxCMD_LINE_SWITCH
, "t", "timing",
423 "print names and mesure running time of individual test, run them",
424 wxCMD_LINE_VAL_NONE
, 0 },
425 { wxCMD_LINE_OPTION
, "", "locale",
426 "locale to use when running the program",
427 wxCMD_LINE_VAL_STRING
, 0 },
428 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
429 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
433 parser
.SetDesc(cmdLineDesc
);
436 // Handle command line options
438 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
440 if (parser
.GetParamCount())
442 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
443 m_registries
.push_back(parser
.GetParam(i
));
446 m_longlist
= parser
.Found("longlist");
447 m_list
= m_longlist
|| parser
.Found("list");
448 m_timing
= parser
.Found("timing");
449 m_detail
= !m_timing
&& parser
.Found("detail");
452 if ( parser
.Found("locale", &loc
) )
454 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
457 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
461 m_locale
= new wxLocale(info
->Language
);
462 if ( !m_locale
->IsOk() )
464 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
469 return TestAppBase::OnCmdLineParsed(parser
);
473 int TestApp::FilterEvent(wxEvent
& event
)
475 if ( m_filterEventFunc
)
476 return (*m_filterEventFunc
)(event
);
478 return TestAppBase::FilterEvent(event
);
481 bool TestApp::ProcessEvent(wxEvent
& event
)
483 if ( m_processEventFunc
)
484 return (*m_processEventFunc
)(event
);
486 return TestAppBase::ProcessEvent(event
);
495 // make sure there's always an autorelease pool ready
496 wxMacAutoreleasePool autoreleasepool
;
501 // Switch off logging unless --verbose
502 bool verbose
= wxLog::GetVerbose();
503 wxLog::EnableLogging(verbose
);
505 bool verbose
= false;
508 CppUnit::TextTestRunner runner
;
510 if ( m_registries
.empty() )
512 // run or list all tests
513 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
515 else // run only the selected tests
517 for (size_t i
= 0; i
< m_registries
.size(); i
++)
519 const wxString reg
= m_registries
[i
];
520 Test
*test
= GetTestByName(reg
);
522 if ( !test
&& !reg
.EndsWith("TestCase") )
524 test
= GetTestByName(reg
+ "TestCase");
529 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
533 AddTest(runner
, test
);
540 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
543 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
544 // in some versions of cppunit: they write progress dots to cout (and not
545 // cerr) and don't flush it so all the dots appear at once at the end which
546 // is not very useful so unbuffer cout to work around this
547 cout
.setf(ios::unitbuf
);
549 // add detail listener if needed
550 DetailListener
detailListener(m_timing
);
551 if ( m_detail
|| m_timing
)
552 runner
.eventManager().addListener(&detailListener
);
554 // finally ensure that we report our own exceptions nicely instead of
555 // giving "uncaught exception of unknown type" messages
556 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
558 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
559 return runner
.run("", false, true, printProgress
) ? EXIT_SUCCESS
: EXIT_FAILURE
;
562 int TestApp::OnExit()
567 delete GetTopWindow();
575 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
577 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
581 // take the last component of the name and append to the parent
582 name
= test
->getName();
583 string::size_type i
= name
.find_last_of(".:");
584 if (i
!= string::npos
)
585 name
= name
.substr(i
+ 1);
586 name
= parent
+ "." + name
;
588 // drop the 1st component from the display and indent
590 string::size_type j
= i
= name
.find('.', 1);
591 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
593 cout
<< " " << name
.substr(i
+ 1) << "\n";
596 typedef vector
<Test
*> Tests
;
597 typedef Tests::const_iterator Iter
;
599 const Tests
& tests
= suite
->getTests();
601 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
604 else if (m_longlist
) {
605 string::size_type i
= 0;
606 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
608 cout
<< " " << test
->getName() << "\n";