1 ///////////////////////////////////////////////////////////////////////////////
3 // Purpose: Test program for wxWidgets
4 // Author: Mike Wetherell
5 // Copyright: (c) 2004 Mike Wetherell
6 // Licence: wxWindows licence
7 ///////////////////////////////////////////////////////////////////////////////
9 // ----------------------------------------------------------------------------
11 // ----------------------------------------------------------------------------
13 // For compilers that support precompilation, includes "wx/wx.h"
21 // for all others, include the necessary headers
26 #include "wx/beforestd.h"
28 #pragma warning(disable:4100)
31 #include <cppunit/TestListener.h>
32 #include <cppunit/Protector.h>
33 #include <cppunit/Test.h>
34 #include <cppunit/TestResult.h>
35 #include <cppunit/TestFailure.h>
36 #include <cppunit/TestResultCollector.h>
39 #pragma warning(default:4100)
41 #include "wx/afterstd.h"
43 #include "wx/cmdline.h"
48 #include "wx/msw/msvcrt.h"
52 #include "wx/osx/private.h"
56 #include "testableframe.h"
59 #include "wx/socket.h"
60 #include "wx/evtloop.h"
65 using CppUnit::TestSuite
;
66 using CppUnit::TestFactoryRegistry
;
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // exception class for MSVC debug CRT assertion failures
74 #ifdef wxUSE_VC_CRTDBG
76 struct CrtAssertFailure
78 CrtAssertFailure(const char *message
) : m_msg(message
) { }
82 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure
);
85 #endif // wxUSE_VC_CRTDBG
89 // Information about the last not yet handled assertion.
90 static wxString s_lastAssertMessage
;
92 static wxString
FormatAssertMessage(const wxString
& file
,
99 str
<< "wxWidgets assert: " << cond
<< " failed "
100 "at " << file
<< ":" << line
<< " in " << func
101 << " with message '" << msg
<< "'";
105 static void TestAssertHandler(const wxString
& file
,
107 const wxString
& func
,
108 const wxString
& cond
,
111 // Determine whether we can safely throw an exception to just make the test
112 // fail or whether we need to abort (in this case "msg" will contain the
113 // explanation why did we decide to do it).
114 wxString abortReason
;
117 assertMessage
= FormatAssertMessage(file
, line
, func
, cond
, msg
);
119 if ( !wxIsMainThread() )
121 // Exceptions thrown from worker threads are not caught currently and
122 // so we'd just die without any useful information -- abort instead.
123 abortReason
<< assertMessage
<< "in a worker thread.";
125 else if ( uncaught_exception() )
127 // Throwing while already handling an exception would result in
128 // terminate() being called and we wouldn't get any useful information
129 // about why the test failed then.
130 if ( s_lastAssertMessage
.empty() )
132 abortReason
<< assertMessage
<< "while handling an exception";
134 else // In this case the exception is due to a previous assert.
136 abortReason
<< s_lastAssertMessage
<< "\n and another "
137 << assertMessage
<< " while handling it.";
140 else // Can "safely" throw from here.
142 // Remember this in case another assert happens while handling this
143 // exception: we want to show the original assert as it's usually more
144 // useful to determine the real root of the problem.
145 s_lastAssertMessage
= assertMessage
;
147 throw TestAssertFailure(file
, line
, func
, cond
, msg
);
150 wxFputs(abortReason
, stderr
);
155 #endif // wxDEBUG_LEVEL
157 // this function should only be called from a catch clause
158 static string
GetExceptionMessage()
167 catch ( TestAssertFailure
& )
169 msg
= s_lastAssertMessage
;
170 s_lastAssertMessage
.clear();
172 #endif // wxDEBUG_LEVEL
173 #ifdef wxUSE_VC_CRTDBG
174 catch ( CrtAssertFailure
& e
)
176 msg
<< "CRT assert failure: " << e
.m_msg
;
178 #endif // wxUSE_VC_CRTDBG
179 catch ( std::exception
& e
)
181 msg
<< "std::exception: " << e
.what();
185 msg
= "Unknown exception caught.";
188 return string(msg
.mb_str());
191 // Protector adding handling of wx-specific (this includes MSVC debug CRT in
192 // this context) exceptions
193 class wxUnitTestProtector
: public CppUnit::Protector
196 virtual bool protect(const CppUnit::Functor
&functor
,
197 const CppUnit::ProtectorContext
& context
)
203 catch ( std::exception
& )
205 // cppunit deals with the standard exceptions itself, let it do as
206 // it output more details (especially for std::exception-derived
207 // CppUnit::Exception) than we do
212 reportError(context
, CppUnit::Message("Uncaught exception",
213 GetExceptionMessage()));
220 // Displays the test name before starting to execute it: this helps with
221 // diagnosing where exactly does a test crash or hang when/if it does.
222 class DetailListener
: public CppUnit::TestListener
225 DetailListener(bool doTiming
= false):
226 CppUnit::TestListener(),
231 virtual void startTest(CppUnit::Test
*test
)
233 printf(" %-60s ", test
->getName().c_str());
234 m_result
= RESULT_OK
;
238 virtual void addFailure(const CppUnit::TestFailure
& failure
)
240 m_result
= failure
.isError() ? RESULT_ERROR
: RESULT_FAIL
;
243 virtual void endTest(CppUnit::Test
* WXUNUSED(test
))
246 printf("%s", GetResultStr(m_result
));
248 printf(" %6ld ms", m_watch
.Time());
261 const char* GetResultStr(ResultType type
) const
263 static const char *resultTypeNames
[] =
270 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames
) == RESULT_MAX
,
271 ResultTypeNamesMismatch
);
273 return resultTypeNames
[type
];
282 typedef wxApp TestAppBase
;
284 typedef wxAppConsole TestAppBase
;
287 // The application class
289 class TestApp
: public TestAppBase
294 // standard overrides
295 virtual void OnInitCmdLine(wxCmdLineParser
& parser
);
296 virtual bool OnCmdLineParsed(wxCmdLineParser
& parser
);
297 virtual bool OnInit();
298 virtual int OnExit();
300 // used by events propagation test
301 virtual int FilterEvent(wxEvent
& event
);
302 virtual bool ProcessEvent(wxEvent
& event
);
304 void SetFilterEventFunc(FilterEventFunc f
) { m_filterEventFunc
= f
; }
305 void SetProcessEventFunc(ProcessEventFunc f
) { m_processEventFunc
= f
; }
307 // In console applications we run the tests directly from the overridden
308 // OnRun(), but in the GUI ones we run them when we get the first call to
309 // our EVT_IDLE handler to ensure that we do everything from inside the
310 // main event loop. This is especially important under wxOSX/Cocoa where
311 // the main event loop is different from the others but it's also safer to
312 // do it like this in the other ports as we test the GUI code in the same
313 // context as it's used usually, in normal programs, and it might behave
314 // differently without the event loop.
316 void OnIdle(wxIdleEvent
& event
)
323 // we need to wait until the window is activated and fully ready
324 // otherwise no events can be posted
325 wxEventLoopBase
* const loop
= wxEventLoop::GetActive();
328 loop
->DispatchTimeout(1000);
333 m_exitcode
= RunTests();
342 m_exitcode
= RunTests();
345 #endif // wxUSE_GUI/!wxUSE_GUI
348 void List(Test
*test
, const string
& parent
= "") const;
350 // call List() if m_list or runner.addTest() otherwise
351 void AddTest(CppUnit::TestRunner
& runner
, Test
*test
)
356 runner
.addTest(test
);
361 // flag telling us whether we should run tests from our EVT_IDLE handler
364 // command lines options/parameters
369 wxArrayString m_registries
;
372 // event handling hooks
373 FilterEventFunc m_filterEventFunc
;
374 ProcessEventFunc m_processEventFunc
;
376 // the program exit code
380 IMPLEMENT_APP_NO_MAIN(TestApp
)
383 // ----------------------------------------------------------------------------
385 // ----------------------------------------------------------------------------
387 #ifdef wxUSE_VC_CRTDBG
389 static int TestCrtReportHook(int reportType
, char *message
, int *)
391 if ( reportType
!= _CRT_ASSERT
)
394 throw CrtAssertFailure(message
);
397 #endif // wxUSE_VC_CRTDBG
399 int main(int argc
, char **argv
)
401 // tests can be ran non-interactively so make sure we don't show any assert
402 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
403 // prevent them from completing
406 wxSetAssertHandler(TestAssertHandler
);
407 #endif // wxDEBUG_LEVEL
409 #ifdef wxUSE_VC_CRTDBG
410 _CrtSetReportHook(TestCrtReportHook
);
411 #endif // wxUSE_VC_CRTDBG
415 return wxEntry(argc
, argv
);
419 cerr
<< "\n" << GetExceptionMessage() << endl
;
425 extern void SetFilterEventFunc(FilterEventFunc func
)
427 wxGetApp().SetFilterEventFunc(func
);
430 extern void SetProcessEventFunc(ProcessEventFunc func
)
432 wxGetApp().SetProcessEventFunc(func
);
435 extern bool IsNetworkAvailable()
437 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
438 // wxCore we use a simple rough test:
440 wxSocketBase::Initialize();
443 if (!addr
.Hostname("www.google.com") || !addr
.Service("www"))
445 wxSocketBase::Shutdown();
450 sock
.SetTimeout(10); // 10 secs
451 bool online
= sock
.Connect(addr
);
453 wxSocketBase::Shutdown();
458 extern bool IsAutomaticTest()
460 static int s_isAutomatic
= -1;
461 if ( s_isAutomatic
== -1 )
463 // Allow setting an environment variable to emulate buildslave user for
466 if ( !wxGetEnv("WX_TEST_USER", &username
) )
467 username
= wxGetUserId();
469 username
.MakeLower();
470 s_isAutomatic
= username
.Matches("buildslave*") ||
471 username
.Matches("sandbox*");
474 return s_isAutomatic
== 1;
477 // helper of RunTests(): gets the test with the given name, returning NULL (and
478 // not an empty test suite) if there is no such test
479 static Test
*GetTestByName(const wxString
& name
)
482 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
485 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
486 if ( !suite
|| !suite
->countTestCases() )
488 // it's a bogus test, don't use it
498 // ----------------------------------------------------------------------------
500 // ----------------------------------------------------------------------------
508 m_filterEventFunc
= NULL
;
509 m_processEventFunc
= NULL
;
513 m_exitcode
= EXIT_SUCCESS
;
518 bool TestApp::OnInit()
520 if ( !TestAppBase::OnInit() )
524 cout
<< "Test program for wxWidgets GUI features\n"
526 cout
<< "Test program for wxWidgets non-GUI features\n"
528 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< "\n"
529 << "running under " << wxGetOsDescription()
530 << " as " << wxGetUserId() << std::endl
;
534 // Output some important information about the test environment.
535 cout
<< "Running under " << wxGetOsDescription() << ", "
536 "locale is " << setlocale(LC_ALL
, NULL
) << std::endl
;
540 // create a hidden parent window to be used as parent for the GUI controls
541 wxTestableFrame
* frame
= new wxTestableFrame();
544 Connect(wxEVT_IDLE
, wxIdleEventHandler(TestApp::OnIdle
));
550 // The table of command line options
552 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
554 TestAppBase::OnInitCmdLine(parser
);
556 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
557 { wxCMD_LINE_SWITCH
, "l", "list",
558 "list the test suites, do not run them",
559 wxCMD_LINE_VAL_NONE
, 0 },
560 { wxCMD_LINE_SWITCH
, "L", "longlist",
561 "list the test cases, do not run them",
562 wxCMD_LINE_VAL_NONE
, 0 },
563 { wxCMD_LINE_SWITCH
, "d", "detail",
564 "print the test case names, run them",
565 wxCMD_LINE_VAL_NONE
, 0 },
566 { wxCMD_LINE_SWITCH
, "t", "timing",
567 "print names and measure running time of individual test, run them",
568 wxCMD_LINE_VAL_NONE
, 0 },
569 { wxCMD_LINE_OPTION
, "", "locale",
570 "locale to use when running the program",
571 wxCMD_LINE_VAL_STRING
, 0 },
572 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
573 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
577 parser
.SetDesc(cmdLineDesc
);
580 // Handle command line options
582 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
584 if (parser
.GetParamCount())
586 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
587 m_registries
.push_back(parser
.GetParam(i
));
590 m_longlist
= parser
.Found("longlist");
591 m_list
= m_longlist
|| parser
.Found("list");
592 m_timing
= parser
.Found("timing");
593 m_detail
= !m_timing
&& parser
.Found("detail");
596 if ( parser
.Found("locale", &loc
) )
598 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
601 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
605 m_locale
= new wxLocale(info
->Language
);
606 if ( !m_locale
->IsOk() )
608 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
613 return TestAppBase::OnCmdLineParsed(parser
);
617 int TestApp::FilterEvent(wxEvent
& event
)
619 if ( m_filterEventFunc
)
620 return (*m_filterEventFunc
)(event
);
622 return TestAppBase::FilterEvent(event
);
625 bool TestApp::ProcessEvent(wxEvent
& event
)
627 if ( m_processEventFunc
)
628 return (*m_processEventFunc
)(event
);
630 return TestAppBase::ProcessEvent(event
);
635 int TestApp::RunTests()
638 // Switch off logging unless --verbose
639 bool verbose
= wxLog::GetVerbose();
640 wxLog::EnableLogging(verbose
);
642 bool verbose
= false;
645 CppUnit::TextTestRunner runner
;
647 if ( m_registries
.empty() )
649 // run or list all tests which use the CPPUNIT_TEST_SUITE_REGISTRATION() macro
650 // (i.e. those registered in the "All tests" registry); if there are other
651 // tests not registered with the CPPUNIT_TEST_SUITE_REGISTRATION() macro
652 // then they won't be listed/run!
653 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
657 cout
<< "\nNote that the list above is not complete as it doesn't include the \n";
658 cout
<< "tests disabled by default.\n";
661 else // run only the selected tests
663 for (size_t i
= 0; i
< m_registries
.size(); i
++)
665 const wxString reg
= m_registries
[i
];
666 Test
*test
= GetTestByName(reg
);
668 if ( !test
&& !reg
.EndsWith("TestCase") )
670 test
= GetTestByName(reg
+ "TestCase");
675 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
679 AddTest(runner
, test
);
686 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
689 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
690 // in some versions of cppunit: they write progress dots to cout (and not
691 // cerr) and don't flush it so all the dots appear at once at the end which
692 // is not very useful so unbuffer cout to work around this
693 cout
.setf(ios::unitbuf
);
695 // add detail listener if needed
696 DetailListener
detailListener(m_timing
);
697 if ( m_detail
|| m_timing
)
698 runner
.eventManager().addListener(&detailListener
);
700 // finally ensure that we report our own exceptions nicely instead of
701 // giving "uncaught exception of unknown type" messages
702 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
704 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
705 runner
.run("", false, true, printProgress
);
707 return runner
.result().testFailures() == 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
710 int TestApp::OnExit()
715 delete GetTopWindow();
723 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
725 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
729 // take the last component of the name and append to the parent
730 name
= test
->getName();
731 string::size_type i
= name
.find_last_of(".:");
732 if (i
!= string::npos
)
733 name
= name
.substr(i
+ 1);
734 name
= parent
+ "." + name
;
736 // drop the 1st component from the display and indent
738 string::size_type j
= i
= name
.find('.', 1);
739 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
741 cout
<< " " << name
.substr(i
+ 1) << "\n";
744 typedef vector
<Test
*> Tests
;
745 typedef Tests::const_iterator Iter
;
747 const Tests
& tests
= suite
->getTests();
749 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
752 else if (m_longlist
) {
753 string::size_type i
= 0;
754 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
756 cout
<< " " << test
->getName() << "\n";