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