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 sock
.SetTimeout(10); // 10 secs
340 bool online
= sock
.Connect(addr
);
342 wxSocketBase::Shutdown();
347 // helper of OnRun(): gets the test with the given name, returning NULL (and
348 // not an empty test suite) if there is no such test
349 static Test
*GetTestByName(const wxString
& name
)
352 test
= TestFactoryRegistry::getRegistry(string(name
.mb_str())).makeTest();
355 TestSuite
* const suite
= dynamic_cast<TestSuite
*>(test
);
356 if ( !suite
|| !suite
->countTestCases() )
358 // it's a bogus test, don't use it
368 // ----------------------------------------------------------------------------
370 // ----------------------------------------------------------------------------
376 m_filterEventFunc
= NULL
;
377 m_processEventFunc
= NULL
;
384 bool TestApp::OnInit()
386 if ( !TestAppBase::OnInit() )
390 cout
<< "Test program for wxWidgets GUI features\n"
392 cout
<< "Test program for wxWidgets non-GUI features\n"
394 << "build: " << WX_BUILD_OPTIONS_SIGNATURE
<< std::endl
;
397 // create a hidden parent window to be used as parent for the GUI controls
398 new wxFrame(NULL
, wxID_ANY
, "Hidden wx test frame");
404 // The table of command line options
406 void TestApp::OnInitCmdLine(wxCmdLineParser
& parser
)
408 TestAppBase::OnInitCmdLine(parser
);
410 static const wxCmdLineEntryDesc cmdLineDesc
[] = {
411 { wxCMD_LINE_SWITCH
, "l", "list",
412 "list the test suites, do not run them",
413 wxCMD_LINE_VAL_NONE
, 0 },
414 { wxCMD_LINE_SWITCH
, "L", "longlist",
415 "list the test cases, do not run them",
416 wxCMD_LINE_VAL_NONE
, 0 },
417 { wxCMD_LINE_SWITCH
, "d", "detail",
418 "print the test case names, run them",
419 wxCMD_LINE_VAL_NONE
, 0 },
420 { wxCMD_LINE_SWITCH
, "t", "timing",
421 "print names and mesure running time of individual test, run them",
422 wxCMD_LINE_VAL_NONE
, 0 },
423 { wxCMD_LINE_OPTION
, "", "locale",
424 "locale to use when running the program",
425 wxCMD_LINE_VAL_STRING
, 0 },
426 { wxCMD_LINE_PARAM
, NULL
, NULL
, "REGISTRY", wxCMD_LINE_VAL_STRING
,
427 wxCMD_LINE_PARAM_OPTIONAL
| wxCMD_LINE_PARAM_MULTIPLE
},
431 parser
.SetDesc(cmdLineDesc
);
434 // Handle command line options
436 bool TestApp::OnCmdLineParsed(wxCmdLineParser
& parser
)
438 if (parser
.GetParamCount())
440 for (size_t i
= 0; i
< parser
.GetParamCount(); i
++)
441 m_registries
.push_back(parser
.GetParam(i
));
444 m_longlist
= parser
.Found("longlist");
445 m_list
= m_longlist
|| parser
.Found("list");
446 m_timing
= parser
.Found("timing");
447 m_detail
= !m_timing
&& parser
.Found("detail");
450 if ( parser
.Found("locale", &loc
) )
452 const wxLanguageInfo
* const info
= wxLocale::FindLanguageInfo(loc
);
455 cerr
<< "Locale \"" << string(loc
.mb_str()) << "\" is unknown.\n";
459 m_locale
= new wxLocale(info
->Language
);
460 if ( !m_locale
->IsOk() )
462 cerr
<< "Using locale \"" << string(loc
.mb_str()) << "\" failed.\n";
467 return TestAppBase::OnCmdLineParsed(parser
);
471 int TestApp::FilterEvent(wxEvent
& event
)
473 if ( m_filterEventFunc
)
474 return (*m_filterEventFunc
)(event
);
476 return TestAppBase::FilterEvent(event
);
479 bool TestApp::ProcessEvent(wxEvent
& event
)
481 if ( m_processEventFunc
)
482 return (*m_processEventFunc
)(event
);
484 return TestAppBase::ProcessEvent(event
);
493 // make sure there's always an autorelease pool ready
494 wxMacAutoreleasePool autoreleasepool
;
499 // Switch off logging unless --verbose
500 bool verbose
= wxLog::GetVerbose();
501 wxLog::EnableLogging(verbose
);
503 bool verbose
= false;
506 CppUnit::TextTestRunner runner
;
508 if ( m_registries
.empty() )
510 // run or list all tests
511 AddTest(runner
, TestFactoryRegistry::getRegistry().makeTest());
513 else // run only the selected tests
515 for (size_t i
= 0; i
< m_registries
.size(); i
++)
517 const wxString reg
= m_registries
[i
];
518 Test
*test
= GetTestByName(reg
);
520 if ( !test
&& !reg
.EndsWith("TestCase") )
522 test
= GetTestByName(reg
+ "TestCase");
527 cerr
<< "No such test suite: " << string(reg
.mb_str()) << endl
;
531 AddTest(runner
, test
);
538 runner
.setOutputter(new CppUnit::CompilerOutputter(&runner
.result(), cout
));
541 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
542 // in some versions of cppunit: they write progress dots to cout (and not
543 // cerr) and don't flush it so all the dots appear at once at the end which
544 // is not very useful so unbuffer cout to work around this
545 cout
.setf(ios::unitbuf
);
547 // add detail listener if needed
548 DetailListener
detailListener(m_timing
);
549 if ( m_detail
|| m_timing
)
550 runner
.eventManager().addListener(&detailListener
);
552 // finally ensure that we report our own exceptions nicely instead of
553 // giving "uncaught exception of unknown type" messages
554 runner
.eventManager().pushProtector(new wxUnitTestProtector
);
556 bool printProgress
= !(verbose
|| m_detail
|| m_timing
);
557 return runner
.run("", false, true, printProgress
) ? EXIT_SUCCESS
: EXIT_FAILURE
;
560 int TestApp::OnExit()
565 delete GetTopWindow();
573 void TestApp::List(Test
*test
, const string
& parent
/*=""*/) const
575 TestSuite
*suite
= dynamic_cast<TestSuite
*>(test
);
579 // take the last component of the name and append to the parent
580 name
= test
->getName();
581 string::size_type i
= name
.find_last_of(".:");
582 if (i
!= string::npos
)
583 name
= name
.substr(i
+ 1);
584 name
= parent
+ "." + name
;
586 // drop the 1st component from the display and indent
588 string::size_type j
= i
= name
.find('.', 1);
589 while ((j
= name
.find('.', j
+ 1)) != string::npos
)
591 cout
<< " " << name
.substr(i
+ 1) << "\n";
594 typedef vector
<Test
*> Tests
;
595 typedef Tests::const_iterator Iter
;
597 const Tests
& tests
= suite
->getTests();
599 for (Iter it
= tests
.begin(); it
!= tests
.end(); ++it
)
602 else if (m_longlist
) {
603 string::size_type i
= 0;
604 while ((i
= parent
.find('.', i
+ 1)) != string::npos
)
606 cout
<< " " << test
->getName() << "\n";