]> git.saurik.com Git - wxWidgets.git/blame - tests/test.cpp
Exclude tests relying on last error being set under MinGW.
[wxWidgets.git] / tests / test.cpp
CommitLineData
670ec357
VS
1///////////////////////////////////////////////////////////////////////////////
2// Name: test.cpp
3// Purpose: Test program for wxWidgets
4// Author: Mike Wetherell
5// RCS-ID: $Id$
6// Copyright: (c) 2004 Mike Wetherell
526954c5 7// Licence: wxWindows licence
670ec357
VS
8///////////////////////////////////////////////////////////////////////////////
9
1f51673b
FM
10// ----------------------------------------------------------------------------
11// headers
12// ----------------------------------------------------------------------------
13
8899b155
RN
14// For compilers that support precompilation, includes "wx/wx.h"
15// and "wx/cppunit.h"
16#include "testprec.h"
670ec357
VS
17
18#ifdef __BORLANDC__
19 #pragma hdrstop
20#endif
21
22// for all others, include the necessary headers
23#ifndef WX_PRECOMP
24 #include "wx/wx.h"
25#endif
26
afd90468 27#include "wx/beforestd.h"
6d9407fe
VZ
28#ifdef __VISUALC__
29 #pragma warning(disable:4100)
30#endif
de830910 31
afd90468 32#include <cppunit/TestListener.h>
b33e98f0 33#include <cppunit/Protector.h>
afd90468
VZ
34#include <cppunit/Test.h>
35#include <cppunit/TestResult.h>
29e0c68e 36#include <cppunit/TestFailure.h>
de830910
VZ
37
38#ifdef __VISUALC__
39 #pragma warning(default:4100)
40#endif
afd90468
VZ
41#include "wx/afterstd.h"
42
670ec357 43#include "wx/cmdline.h"
670ec357
VS
44#include <iostream>
45
b33e98f0
VZ
46#ifdef __WXMSW__
47 #include "wx/msw/msvcrt.h"
48#endif
49
8b7b1a57
SC
50#ifdef __WXOSX__
51 #include "wx/osx/private.h"
52#endif
53
232fdc63
VZ
54#if wxUSE_GUI
55 #include "testableframe.h"
56#endif
57
1f51673b 58#include "wx/socket.h"
232fdc63 59#include "wx/evtloop.h"
1f51673b 60
b33e98f0
VZ
61using namespace std;
62
3e5f6c1c
WS
63using CppUnit::Test;
64using CppUnit::TestSuite;
65using CppUnit::TestFactoryRegistry;
3e5f6c1c 66
1f51673b
FM
67
68// ----------------------------------------------------------------------------
69// helper classes
70// ----------------------------------------------------------------------------
71
b33e98f0
VZ
72// exception class for MSVC debug CRT assertion failures
73#ifdef wxUSE_VC_CRTDBG
74
75struct CrtAssertFailure
76{
77 CrtAssertFailure(const char *message) : m_msg(message) { }
78
79 const wxString m_msg;
80
81 wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure);
82};
83
84#endif // wxUSE_VC_CRTDBG
85
884ca4e4
VZ
86#if wxDEBUG_LEVEL
87
88static wxString FormatAssertMessage(const wxString& file,
89 int line,
90 const wxString& func,
91 const wxString& cond,
92 const wxString& msg)
93{
94 wxString str;
95 str << "wxWidgets assert: " << cond << " failed "
96 "at " << file << ":" << line << " in " << func
97 << " with message '" << msg << "'";
98 return str;
99}
100
101static void TestAssertHandler(const wxString& file,
102 int line,
103 const wxString& func,
104 const wxString& cond,
105 const wxString& msg)
106{
107 // can't throw from other threads, die immediately
108 if ( !wxIsMainThread() )
109 {
110 wxPrintf("%s in a worker thread -- aborting.",
111 FormatAssertMessage(file, line, func, cond, msg));
112 fflush(stdout);
113 _exit(-1);
114 }
115
116 throw TestAssertFailure(file, line, func, cond, msg);
117}
118
119#endif // wxDEBUG_LEVEL
120
b33e98f0
VZ
121// this function should only be called from a catch clause
122static string GetExceptionMessage()
123{
124 wxString msg;
125
126 try
127 {
128 throw;
129 }
130#if wxDEBUG_LEVEL
131 catch ( TestAssertFailure& e )
132 {
884ca4e4
VZ
133 msg << FormatAssertMessage(e.m_file, e.m_line, e.m_func,
134 e.m_cond, e.m_msg);
b33e98f0
VZ
135 }
136#endif // wxDEBUG_LEVEL
137#ifdef wxUSE_VC_CRTDBG
138 catch ( CrtAssertFailure& e )
139 {
140 msg << "CRT assert failure: " << e.m_msg;
141 }
142#endif // wxUSE_VC_CRTDBG
143 catch ( std::exception& e )
144 {
145 msg << "std::exception: " << e.what();
146 }
147 catch ( ... )
148 {
149 msg = "Unknown exception caught.";
150 }
151
152 return string(msg.mb_str());
153}
154
155// Protector adding handling of wx-specific (this includes MSVC debug CRT in
156// this context) exceptions
157class wxUnitTestProtector : public CppUnit::Protector
158{
159public:
160 virtual bool protect(const CppUnit::Functor &functor,
161 const CppUnit::ProtectorContext& context)
162 {
163 try
164 {
165 return functor();
166 }
92f8206f 167 catch ( std::exception& )
9912799c
VZ
168 {
169 // cppunit deals with the standard exceptions itself, let it do as
170 // it output more details (especially for std::exception-derived
171 // CppUnit::Exception) than we do
172 throw;
173 }
b33e98f0
VZ
174 catch ( ... )
175 {
176 reportError(context, CppUnit::Message("Uncaught exception",
177 GetExceptionMessage()));
178 }
179
180 return false;
181 }
182};
afd90468 183
6d9407fe
VZ
184// Displays the test name before starting to execute it: this helps with
185// diagnosing where exactly does a test crash or hang when/if it does.
afd90468
VZ
186class DetailListener : public CppUnit::TestListener
187{
188public:
189 DetailListener(bool doTiming = false):
190 CppUnit::TestListener(),
191 m_timing(doTiming)
192 {
193 }
194
195 virtual void startTest(CppUnit::Test *test)
196 {
29e0c68e
VZ
197 wxPrintf(" %-60s ", test->getName());
198 m_result = RESULT_OK;
afd90468
VZ
199 m_watch.Start();
200 }
201
62714742
VZ
202 virtual void addFailure(const CppUnit::TestFailure& failure)
203 {
29e0c68e
VZ
204 m_result = failure.isError() ? RESULT_ERROR : RESULT_FAIL;
205 }
206
afd90468
VZ
207 virtual void endTest(CppUnit::Test * WXUNUSED(test))
208 {
209 m_watch.Pause();
29e0c68e
VZ
210 wxPrintf(GetResultStr(m_result));
211 if (m_timing)
212 wxPrintf(" %6d ms", m_watch.Time());
213 wxPrintf("\n");
afd90468
VZ
214 }
215
216protected :
62714742
VZ
217 enum ResultType
218 {
29e0c68e
VZ
219 RESULT_OK = 0,
220 RESULT_FAIL,
62714742
VZ
221 RESULT_ERROR,
222 RESULT_MAX
29e0c68e
VZ
223 };
224
62714742
VZ
225 wxString GetResultStr(ResultType type) const
226 {
227 static const char *resultTypeNames[] =
228 {
229 " OK",
230 "FAIL",
231 " ERR"
29e0c68e 232 };
62714742
VZ
233
234 wxCOMPILE_TIME_ASSERT( WXSIZEOF(resultTypeNames) == RESULT_MAX,
235 ResultTypeNamesMismatch );
236
237 return resultTypeNames[type];
29e0c68e
VZ
238 }
239
afd90468
VZ
240 bool m_timing;
241 wxStopWatch m_watch;
29e0c68e 242 ResultType m_result;
afd90468
VZ
243};
244
c0d9b217
VZ
245#if wxUSE_GUI
246 typedef wxApp TestAppBase;
247#else
248 typedef wxAppConsole TestAppBase;
249#endif
250
670ec357
VS
251// The application class
252//
c0d9b217 253class TestApp : public TestAppBase
670ec357
VS
254{
255public:
256 TestApp();
257
258 // standard overrides
c0d9b217
VZ
259 virtual void OnInitCmdLine(wxCmdLineParser& parser);
260 virtual bool OnCmdLineParsed(wxCmdLineParser& parser);
261 virtual bool OnInit();
262 virtual int OnRun();
263 virtual int OnExit();
670ec357 264
1649d288
VZ
265 // used by events propagation test
266 virtual int FilterEvent(wxEvent& event);
267 virtual bool ProcessEvent(wxEvent& event);
268
269 void SetFilterEventFunc(FilterEventFunc f) { m_filterEventFunc = f; }
270 void SetProcessEventFunc(ProcessEventFunc f) { m_processEventFunc = f; }
271
670ec357 272private:
8dae9169 273 void List(Test *test, const string& parent = "") const;
670ec357 274
e992b97f
VZ
275 // call List() if m_list or runner.addTest() otherwise
276 void AddTest(CppUnit::TestRunner& runner, Test *test)
277 {
278 if (m_list)
279 List(test);
280 else
281 runner.addTest(test);
282 }
283
670ec357
VS
284 // command lines options/parameters
285 bool m_list;
a81f3066 286 bool m_longlist;
afd90468
VZ
287 bool m_detail;
288 bool m_timing;
6582f592 289 wxArrayString m_registries;
ad16130f 290 wxLocale *m_locale;
1649d288 291
232fdc63
VZ
292 // event loop for GUI tests
293 wxEventLoop* m_eventloop;
294
1649d288
VZ
295 // event handling hooks
296 FilterEventFunc m_filterEventFunc;
297 ProcessEventFunc m_processEventFunc;
670ec357
VS
298};
299
b33e98f0
VZ
300IMPLEMENT_APP_NO_MAIN(TestApp)
301
1f51673b
FM
302
303// ----------------------------------------------------------------------------
304// global functions
305// ----------------------------------------------------------------------------
306
b33e98f0
VZ
307#ifdef wxUSE_VC_CRTDBG
308
309static int TestCrtReportHook(int reportType, char *message, int *)
310{
311 if ( reportType != _CRT_ASSERT )
312 return FALSE;
313
314 throw CrtAssertFailure(message);
315}
316
317#endif // wxUSE_VC_CRTDBG
318
b33e98f0
VZ
319int main(int argc, char **argv)
320{
321 // tests can be ran non-interactively so make sure we don't show any assert
322 // dialog boxes -- neither our own nor from MSVC debug CRT -- which would
323 // prevent them from completing
324
325#if wxDEBUG_LEVEL
326 wxSetAssertHandler(TestAssertHandler);
327#endif // wxDEBUG_LEVEL
328
329#ifdef wxUSE_VC_CRTDBG
330 _CrtSetReportHook(TestCrtReportHook);
331#endif // wxUSE_VC_CRTDBG
332
333 try
334 {
335 return wxEntry(argc, argv);
336 }
337 catch ( ... )
338 {
339 cerr << "\n" << GetExceptionMessage() << endl;
340 }
341
342 return -1;
343}
670ec357 344
1f51673b
FM
345extern void SetFilterEventFunc(FilterEventFunc func)
346{
347 wxGetApp().SetFilterEventFunc(func);
348}
349
350extern void SetProcessEventFunc(ProcessEventFunc func)
351{
352 wxGetApp().SetProcessEventFunc(func);
353}
354
355extern bool IsNetworkAvailable()
356{
357 // NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
358 // wxCore we use a simple rough test:
359
360 wxSocketBase::Initialize();
361
362 wxIPV4address addr;
363 if (!addr.Hostname("www.google.com") || !addr.Service("www"))
364 {
365 wxSocketBase::Shutdown();
366 return false;
367 }
368
369 wxSocketClient sock;
5b105c6f 370 sock.SetTimeout(10); // 10 secs
1f51673b
FM
371 bool online = sock.Connect(addr);
372
373 wxSocketBase::Shutdown();
374
375 return online;
376}
377
378// helper of OnRun(): gets the test with the given name, returning NULL (and
379// not an empty test suite) if there is no such test
380static Test *GetTestByName(const wxString& name)
381{
382 Test *
383 test = TestFactoryRegistry::getRegistry(string(name.mb_str())).makeTest();
384 if ( test )
385 {
386 TestSuite * const suite = dynamic_cast<TestSuite *>(test);
387 if ( !suite || !suite->countTestCases() )
388 {
389 // it's a bogus test, don't use it
390 delete test;
391 test = NULL;
392 }
393 }
394
395 return test;
396}
397
398
399// ----------------------------------------------------------------------------
400// TestApp
401// ----------------------------------------------------------------------------
402
670ec357 403TestApp::TestApp()
8dae9169
VS
404 : m_list(false),
405 m_longlist(false)
670ec357 406{
1649d288
VZ
407 m_filterEventFunc = NULL;
408 m_processEventFunc = NULL;
ad16130f
VZ
409
410 m_locale = NULL;
232fdc63 411 m_eventloop = NULL;
670ec357
VS
412}
413
414// Init
415//
416bool TestApp::OnInit()
417{
c0d9b217
VZ
418 if ( !TestAppBase::OnInit() )
419 return false;
420
9e91447c
FM
421#if wxUSE_GUI
422 cout << "Test program for wxWidgets GUI features\n"
423#else
424 cout << "Test program for wxWidgets non-GUI features\n"
425#endif
3e5f6c1c 426 << "build: " << WX_BUILD_OPTIONS_SIGNATURE << std::endl;
9f7a07ab 427
c0d9b217
VZ
428#if wxUSE_GUI
429 // create a hidden parent window to be used as parent for the GUI controls
232fdc63
VZ
430 wxTestableFrame* frame = new wxTestableFrame();
431 frame->Show();
432
433 m_eventloop = new wxEventLoop;
434 wxEventLoop::SetActive(m_eventloop);
c0d9b217
VZ
435#endif // wxUSE_GUI
436
437 return true;
9f10e7c7 438}
670ec357
VS
439
440// The table of command line options
441//
442void TestApp::OnInitCmdLine(wxCmdLineParser& parser)
443{
c0d9b217 444 TestAppBase::OnInitCmdLine(parser);
670ec357
VS
445
446 static const wxCmdLineEntryDesc cmdLineDesc[] = {
aa3b041e
VZ
447 { wxCMD_LINE_SWITCH, "l", "list",
448 "list the test suites, do not run them",
a81f3066 449 wxCMD_LINE_VAL_NONE, 0 },
aa3b041e
VZ
450 { wxCMD_LINE_SWITCH, "L", "longlist",
451 "list the test cases, do not run them",
670ec357 452 wxCMD_LINE_VAL_NONE, 0 },
afd90468
VZ
453 { wxCMD_LINE_SWITCH, "d", "detail",
454 "print the test case names, run them",
455 wxCMD_LINE_VAL_NONE, 0 },
456 { wxCMD_LINE_SWITCH, "t", "timing",
20ba398d 457 "print names and measure running time of individual test, run them",
afd90468 458 wxCMD_LINE_VAL_NONE, 0 },
ad16130f
VZ
459 { wxCMD_LINE_OPTION, "", "locale",
460 "locale to use when running the program",
461 wxCMD_LINE_VAL_STRING, 0 },
aa3b041e 462 { wxCMD_LINE_PARAM, NULL, NULL, "REGISTRY", wxCMD_LINE_VAL_STRING,
a81f3066 463 wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },
aa3b041e 464 wxCMD_LINE_DESC_END
670ec357
VS
465 };
466
467 parser.SetDesc(cmdLineDesc);
468}
469
470// Handle command line options
471//
472bool TestApp::OnCmdLineParsed(wxCmdLineParser& parser)
473{
a81f3066 474 if (parser.GetParamCount())
ad16130f 475 {
a81f3066 476 for (size_t i = 0; i < parser.GetParamCount(); i++)
6582f592 477 m_registries.push_back(parser.GetParam(i));
ad16130f 478 }
ad16130f
VZ
479
480 m_longlist = parser.Found("longlist");
481 m_list = m_longlist || parser.Found("list");
482 m_timing = parser.Found("timing");
483 m_detail = !m_timing && parser.Found("detail");
484
485 wxString loc;
486 if ( parser.Found("locale", &loc) )
487 {
488 const wxLanguageInfo * const info = wxLocale::FindLanguageInfo(loc);
489 if ( !info )
490 {
491 cerr << "Locale \"" << string(loc.mb_str()) << "\" is unknown.\n";
492 return false;
493 }
3e5f6c1c 494
ad16130f
VZ
495 m_locale = new wxLocale(info->Language);
496 if ( !m_locale->IsOk() )
497 {
498 cerr << "Using locale \"" << string(loc.mb_str()) << "\" failed.\n";
499 return false;
500 }
501 }
670ec357 502
c0d9b217 503 return TestAppBase::OnCmdLineParsed(parser);
670ec357
VS
504}
505
1649d288
VZ
506// Event handling
507int TestApp::FilterEvent(wxEvent& event)
508{
509 if ( m_filterEventFunc )
510 return (*m_filterEventFunc)(event);
511
512 return TestAppBase::FilterEvent(event);
513}
514
515bool TestApp::ProcessEvent(wxEvent& event)
516{
517 if ( m_processEventFunc )
518 return (*m_processEventFunc)(event);
519
520 return TestAppBase::ProcessEvent(event);
521}
522
670ec357
VS
523// Run
524//
525int TestApp::OnRun()
526{
8b7b1a57
SC
527#if wxUSE_GUI
528#ifdef __WXOSX__
529 // make sure there's always an autorelease pool ready
530 wxMacAutoreleasePool autoreleasepool;
531#endif
532#endif
533
875f82b1
VZ
534#if wxUSE_LOG
535 // Switch off logging unless --verbose
536 bool verbose = wxLog::GetVerbose();
537 wxLog::EnableLogging(verbose);
538#else
539 bool verbose = false;
540#endif
541
2976d6cb 542 CppUnit::TextTestRunner runner;
a81f3066 543
e992b97f 544 if ( m_registries.empty() )
6d423df0 545 {
20ba398d
FM
546 // run or list all tests which use the CPPUNIT_TEST_SUITE_REGISTRATION() macro
547 // (i.e. those registered in the "All tests" registry); if there are other
548 // tests not registered with the CPPUNIT_TEST_SUITE_REGISTRATION() macro
549 // then they won't be listed/run!
e992b97f 550 AddTest(runner, TestFactoryRegistry::getRegistry().makeTest());
20ba398d
FM
551
552 if (m_list)
553 {
554 cout << "\nNote that the list above is not complete as it doesn't include the \n";
555 cout << "tests disabled by default.\n";
556 }
e992b97f
VZ
557 }
558 else // run only the selected tests
559 {
560 for (size_t i = 0; i < m_registries.size(); i++)
d73a5209 561 {
e992b97f
VZ
562 const wxString reg = m_registries[i];
563 Test *test = GetTestByName(reg);
d73a5209
VZ
564
565 if ( !test && !reg.EndsWith("TestCase") )
566 {
567 test = GetTestByName(reg + "TestCase");
568 }
569
570 if ( !test )
571 {
572 cerr << "No such test suite: " << string(reg.mb_str()) << endl;
573 return 2;
574 }
a81f3066 575
e992b97f
VZ
576 AddTest(runner, test);
577 }
670ec357 578 }
a81f3066 579
2976d6cb 580 if ( m_list )
1dd8319a 581 return EXIT_SUCCESS;
2976d6cb
VZ
582
583 runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), cout));
14dc53b2 584
2976d6cb
VZ
585 // there is a bug
586 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
587 // in some versions of cppunit: they write progress dots to cout (and not
588 // cerr) and don't flush it so all the dots appear at once at the end which
589 // is not very useful so unbuffer cout to work around this
590 cout.setf(ios::unitbuf);
591
afd90468
VZ
592 // add detail listener if needed
593 DetailListener detailListener(m_timing);
594 if ( m_detail || m_timing )
595 runner.eventManager().addListener(&detailListener);
596
b33e98f0
VZ
597 // finally ensure that we report our own exceptions nicely instead of
598 // giving "uncaught exception of unknown type" messages
599 runner.eventManager().pushProtector(new wxUnitTestProtector);
600
29e0c68e
VZ
601 bool printProgress = !(verbose || m_detail || m_timing);
602 return runner.run("", false, true, printProgress) ? EXIT_SUCCESS : EXIT_FAILURE;
670ec357
VS
603}
604
c0d9b217
VZ
605int TestApp::OnExit()
606{
ad16130f
VZ
607 delete m_locale;
608
c0d9b217
VZ
609#if wxUSE_GUI
610 delete GetTopWindow();
232fdc63
VZ
611 wxEventLoop::SetActive(NULL);
612 delete m_eventloop;
c0d9b217
VZ
613#endif // wxUSE_GUI
614
615 return 0;
616}
617
670ec357
VS
618// List the tests
619//
8dae9169 620void TestApp::List(Test *test, const string& parent /*=""*/) const
670ec357 621{
670ec357 622 TestSuite *suite = dynamic_cast<TestSuite*>(test);
8dae9169
VS
623 string name;
624
bc10103e 625 if (suite) {
8dae9169
VS
626 // take the last component of the name and append to the parent
627 name = test->getName();
628 string::size_type i = name.find_last_of(".:");
f44eaed6
RN
629 if (i != string::npos)
630 name = name.substr(i + 1);
631 name = parent + "." + name;
8dae9169
VS
632
633 // drop the 1st component from the display and indent
634 if (parent != "") {
635 string::size_type j = i = name.find('.', 1);
636 while ((j = name.find('.', j + 1)) != string::npos)
637 cout << " ";
638 cout << " " << name.substr(i + 1) << "\n";
639 }
a81f3066 640
f69577be 641 typedef vector<Test*> Tests;
670ec357
VS
642 typedef Tests::const_iterator Iter;
643
f69577be 644 const Tests& tests = suite->getTests();
670ec357
VS
645
646 for (Iter it = tests.begin(); it != tests.end(); ++it)
8dae9169 647 List(*it, name);
670ec357 648 }
bc10103e
VS
649 else if (m_longlist) {
650 string::size_type i = 0;
651 while ((i = parent.find('.', i + 1)) != string::npos)
652 cout << " ";
653 cout << " " << test->getName() << "\n";
654 }
670ec357 655}