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 // Information about the last not yet handled assertion.
91 static wxString s_lastAssertMessage
;
93 static wxString
FormatAssertMessage(const wxString
& file
,
100 str
<< "wxWidgets assert: " << cond
<< " failed "
101 "at " << file
<< ":" << line
<< " in " << func
102 << " with message '" << msg
<< "'";
106 static void TestAssertHandler(const wxString
& file
,
108 const wxString
& func
,
109 const wxString
& cond
,
112 // Determine whether we can safely throw an exception to just make the test
113 // fail or whether we need to abort (in this case "msg" will contain the
114 // explanation why did we decide to do it).
115 wxString abortReason
;
118 assertMessage
= FormatAssertMessage(file
, line
, func
, cond
, msg
);
120 if ( !wxIsMainThread() )
122 // Exceptions thrown from worker threads are not caught currently and
123 // so we'd just die without any useful information -- abort instead.
124 abortReason
<< assertMessage
<< "in a worker thread.";
126 else if ( uncaught_exception() )
128 // Throwing while already handling an exception would result in
129 // terminate() being called and we wouldn't get any useful information
130 // about why the test failed then.
131 if ( s_lastAssertMessage
.empty() )
133 abortReason
<< assertMessage
<< "while handling an exception";
135 else // In this case the exception is due to a previous assert.
137 abortReason
<< s_lastAssertMessage
<< "\n and another "
138 << assertMessage
<< " while handling it.";
141 else // Can "safely" throw from here.
143 // Remember this in case another assert happens while handling this
144 // exception: we want to show the original assert as it's usually more
145 // useful to determine the real root of the problem.
146 s_lastAssertMessage
= assertMessage
;
148 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
151 wxFputs(abortReason
, stderr
);
156 #endif // wxDEBUG_LEVEL
158 // this function should only be called from a catch clause
159 static string
GetExceptionMessage()
168 catch ( TestAssertFailure
& )
170 msg
= s_lastAssertMessage
;
171 s_lastAssertMessage
.clear();
173 #endif // wxDEBUG_LEVEL
174 #ifdef wxUSE_VC_CRTDBG
175 catch ( CrtAssertFailure
& e
)
177 msg
<< "CRT assert failure: " << e
.m_msg
;
179 #endif // wxUSE_VC_CRTDBG
180 catch ( std::exception
& e
)
182 msg
<< "std::exception: " << e
.what();
186 msg
= "Unknown exception caught.";
189 return string(msg
.mb_str());
192 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
193 // this context) exceptions
194 class wxUnitTestProtector
: public CppUnit::Protector
197 virtual bool protect(const CppUnit::Functor
&functor
,
198 const CppUnit::ProtectorContext
& context
)
204 catch ( std::exception
& )
206 // cppunit deals with the standard exceptions itself, let it do as
207 // it output more details (especially for std::exception-derived
208 // CppUnit::Exception) than we do
213 reportError(context
, CppUnit::Message("Uncaught exception",
214 GetExceptionMessage()));
221 // Displays the test name before starting to execute it: this helps with
222 // diagnosing where exactly does a test crash or hang when/if it does.
223 class DetailListener
: public CppUnit::TestListener
226 DetailListener(bool doTiming
= false):
227 CppUnit::TestListener(),
232 virtual void startTest(CppUnit::Test
*test
)
234 printf(" %-60s ", test
->getName().c_str());
235 m_result
= RESULT_OK
;
239 virtual void addFailure(const CppUnit::TestFailure
& failure
)
241 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
244 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
247 printf("%s", GetResultStr(m_result
));
249 printf(" %6ld ms", m_watch
.Time());
262 const char* GetResultStr(ResultType type
) const
264 static const char *resultTypeNames
[] =
271 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
272 ResultTypeNamesMismatch
);
274 return resultTypeNames
[type
];
283 typedef wxApp TestAppBase
;
285 typedef wxAppConsole TestAppBase
;
288 // The application class
290 class TestApp
: public TestAppBase
295 // standard overrides
296 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
297 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
298 virtual bool OnInit();
300 virtual int OnExit();
302 // used by events propagation test
303 virtual int FilterEvent(wxEvent
& event
);
304 virtual bool ProcessEvent(wxEvent
& event
);
306 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
307 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
310 void List(Test
*test
, const string
& parent
= "") const;
312 // call List() if m_list or runner.addTest() otherwise
313 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
318 runner
.addTest(test
);
321 // command lines options/parameters
326 wxArrayString m_registries
;
329 // event loop for GUI tests
330 wxEventLoop
* m_eventloop
;
332 // event handling hooks
333 FilterEventFunc m_filterEventFunc
;
334 ProcessEventFunc m_processEventFunc
;
337 IMPLEMENT_APP_NO_MAIN(TestApp
)
340 // ----------------------------------------------------------------------------
342 // ----------------------------------------------------------------------------
344 #ifdef wxUSE_VC_CRTDBG
346 static int TestCrtReportHook(int reportType
, char *message
, int *)
348 if ( reportType
!= _CRT_ASSERT
)
351 throw CrtAssertFailure(message
);
354 #endif // wxUSE_VC_CRTDBG
356 int main(int argc
, char **argv
)
358 // tests can be ran non-interactively so make sure we don't show any assert
359 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
360 // prevent them from completing
363 wxSetAssertHandler(TestAssertHandler
);
364 #endif // wxDEBUG_LEVEL
366 #ifdef wxUSE_VC_CRTDBG
367 _CrtSetReportHook(TestCrtReportHook
);
368 #endif // wxUSE_VC_CRTDBG
372 return wxEntry(argc
, argv
);
376 cerr
<< "\n" << GetExceptionMessage() << endl
;
382 extern void SetFilterEventFunc(FilterEventFunc func
)
384 wxGetApp().SetFilterEventFunc(func
);
387 extern void SetProcessEventFunc(ProcessEventFunc func
)
389 wxGetApp().SetProcessEventFunc(func
);
392 extern bool IsNetworkAvailable()
394 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
395 // wxCore we use a simple rough test:
397 wxSocketBase::Initialize();
400 if (!addr
.Hostname("www.google.com") || !addr
.Service("www"))
402 wxSocketBase::Shutdown();
407 sock
.SetTimeout(10); // 10 secs
408 bool online
= sock
.Connect(addr
);
410 wxSocketBase::Shutdown();
415 extern bool IsAutomaticTest()
417 static int s_isAutomatic
= -1;
418 if ( s_isAutomatic
== -1 )
420 // Allow setting an environment variable to emulate buildslave user for
423 if ( !wxGetEnv("WX_TEST_USER", &username
) )
424 username
= wxGetUserId();
426 s_isAutomatic
= username
.Lower().Matches("buildslave*");
429 return s_isAutomatic
== 1;
432 // helper of OnRun(): gets the test with the given name, returning NULL (and
433 // not an empty test suite) if there is no such test
434 static Test
*GetTestByName(const wxString
& name
)
437 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
440 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
441 if ( !suite
|| !suite
->countTestCases() )
443 // it's a bogus test, don't use it
453 // ----------------------------------------------------------------------------
455 // ----------------------------------------------------------------------------
461 m_filterEventFunc
= NULL
;
462 m_processEventFunc
= NULL
;
470 bool TestApp::OnInit()
472 if ( !TestAppBase::OnInit() )
478 cout
<< "Test program for wxWidgets GUI features\n"
480 cout
<< "Test program for wxWidgets non-GUI features\n"
482 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
486 // Output some important information about the test environment.
487 cout
<< "Running under " << wxGetOsDescription() << ", "
488 "locale is " << setlocale(LC_ALL
, NULL
) << std::endl
;
492 // create a hidden parent window to be used as parent for the GUI controls
493 wxTestableFrame
* frame
= new wxTestableFrame();
496 m_eventloop
= new wxEventLoop
;
497 wxEventLoop::SetActive(m_eventloop
);
503 // The table of command line options
505 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
507 TestAppBase::OnInitCmdLine(parser
);
509 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
510 { wxCMD_LINE_SWITCH
, "l", "list",
511 "list the test suites, do not run them",
512 wxCMD_LINE_VAL_NONE
, 0 },
513 { wxCMD_LINE_SWITCH
, "L", "longlist",
514 "list the test cases, do not run them",
515 wxCMD_LINE_VAL_NONE
, 0 },
516 { wxCMD_LINE_SWITCH
, "d", "detail",
517 "print the test case names, run them",
518 wxCMD_LINE_VAL_NONE
, 0 },
519 { wxCMD_LINE_SWITCH
, "t", "timing",
520 "print names and measure running time of individual test, run them",
521 wxCMD_LINE_VAL_NONE
, 0 },
522 { wxCMD_LINE_OPTION
, "", "locale",
523 "locale to use when running the program",
524 wxCMD_LINE_VAL_STRING
, 0 },
525 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
526 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
530 parser
.SetDesc(cmdLineDesc
);
533 // Handle command line options
535 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
537 if (parser
.GetParamCount())
539 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
540 m_registries
.push_back(parser
.GetParam(i
));
543 m_longlist
= parser
.Found("longlist");
544 m_list
= m_longlist
|| parser
.Found("list");
545 m_timing
= parser
.Found("timing");
546 m_detail
= !m_timing
&& parser
.Found("detail");
549 if ( parser
.Found("locale", &loc
) )
551 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
554 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
558 m_locale
= new wxLocale(info
->Language
);
559 if ( !m_locale
->IsOk() )
561 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
566 return TestAppBase::OnCmdLineParsed(parser
);
570 int TestApp::FilterEvent(wxEvent
& event
)
572 if ( m_filterEventFunc
)
573 return (*m_filterEventFunc
)(event
);
575 return TestAppBase::FilterEvent(event
);
578 bool TestApp::ProcessEvent(wxEvent
& event
)
580 if ( m_processEventFunc
)
581 return (*m_processEventFunc
)(event
);
583 return TestAppBase::ProcessEvent(event
);
592 // make sure there's always an autorelease pool ready
593 wxMacAutoreleasePool autoreleasepool
;
598 // Switch off logging unless --verbose
599 bool verbose
= wxLog::GetVerbose();
600 wxLog::EnableLogging(verbose
);
602 bool verbose
= false;
605 CppUnit::TextTestRunner runner
;
607 if ( m_registries
.empty() )
609 // run or list all tests which use the CPPUNIT_TEST_SUITE_REGISTRATION() macro
610 // (i.e. those registered in the "All tests" registry); if there are other
611 // tests not registered with the CPPUNIT_TEST_SUITE_REGISTRATION() macro
612 // then they won't be listed/run!
613 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
617 cout
<< "\nNote that the list above is not complete as it doesn't include the \n";
618 cout
<< "tests disabled by default.\n";
621 else // run only the selected tests
623 for (size_t i
= 0; i
< m_registries
.size(); i
++)
625 const wxString reg
= m_registries
[i
];
626 Test
*test
= GetTestByName(reg
);
628 if ( !test
&& !reg
.EndsWith("TestCase") )
630 test
= GetTestByName(reg
+ "TestCase");
635 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
639 AddTest(runner
, test
);
646 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
649 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
650 // in some versions of cppunit: they write progress dots to cout (and not
651 // cerr) and don't flush it so all the dots appear at once at the end which
652 // is not very useful so unbuffer cout to work around this
653 cout
.setf(ios::unitbuf
);
655 // add detail listener if needed
656 DetailListener
detailListener(m_timing
);
657 if ( m_detail
|| m_timing
)
658 runner
.eventManager().addListener(&detailListener
);
660 // finally ensure that we report our own exceptions nicely instead of
661 // giving "uncaught exception of unknown type" messages
662 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
664 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
665 runner
.run("", false, true, printProgress
);
667 return runner
.result().testFailures() == 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
670 int TestApp::OnExit()
675 delete GetTopWindow();
676 wxEventLoop::SetActive(NULL
);
685 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
687 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
691 // take the last component of the name and append to the parent
692 name
= test
->getName();
693 string::size_type i
= name
.find_last_of(".:");
694 if (i
!= string::npos
)
695 name
= name
.substr(i
+ 1);
696 name
= parent
+ "." + name
;
698 // drop the 1st component from the display and indent
700 string::size_type j
= i
= name
.find('.', 1);
701 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
703 cout
<< " " << name
.substr(i
+ 1) << "\n";
706 typedef vector
<Test
*> Tests
;
707 typedef Tests::const_iterator Iter
;
709 const Tests
& tests
= suite
->getTests();
711 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
714 else if (m_longlist
) {
715 string::size_type i
= 0;
716 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
718 cout
<< " " << test
->getName() << "\n";