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