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