]> git.saurik.com Git - wxWidgets.git/blob - tests/test.cpp
fix PCH-less build
[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 cout << "Test program for wxWidgets\n"
389 << "build: " << WX_BUILD_OPTIONS_SIGNATURE << std::endl;
390
391 #if wxUSE_GUI
392 // create a hidden parent window to be used as parent for the GUI controls
393 new wxFrame(NULL, wxID_ANY, "Hidden wx test frame");
394 #endif // wxUSE_GUI
395
396 return true;
397 }
398
399 // The table of command line options
400 //
401 void TestApp::OnInitCmdLine(wxCmdLineParser& parser)
402 {
403 TestAppBase::OnInitCmdLine(parser);
404
405 static const wxCmdLineEntryDesc cmdLineDesc[] = {
406 { wxCMD_LINE_SWITCH, "l", "list",
407 "list the test suites, do not run them",
408 wxCMD_LINE_VAL_NONE, 0 },
409 { wxCMD_LINE_SWITCH, "L", "longlist",
410 "list the test cases, do not run them",
411 wxCMD_LINE_VAL_NONE, 0 },
412 { wxCMD_LINE_SWITCH, "d", "detail",
413 "print the test case names, run them",
414 wxCMD_LINE_VAL_NONE, 0 },
415 { wxCMD_LINE_SWITCH, "t", "timing",
416 "print names and mesure running time of individual test, run them",
417 wxCMD_LINE_VAL_NONE, 0 },
418 { wxCMD_LINE_OPTION, "", "locale",
419 "locale to use when running the program",
420 wxCMD_LINE_VAL_STRING, 0 },
421 { wxCMD_LINE_PARAM, NULL, NULL, "REGISTRY", wxCMD_LINE_VAL_STRING,
422 wxCMD_LINE_PARAM_OPTIONAL | wxCMD_LINE_PARAM_MULTIPLE },
423 wxCMD_LINE_DESC_END
424 };
425
426 parser.SetDesc(cmdLineDesc);
427 }
428
429 // Handle command line options
430 //
431 bool TestApp::OnCmdLineParsed(wxCmdLineParser& parser)
432 {
433 if (parser.GetParamCount())
434 {
435 for (size_t i = 0; i < parser.GetParamCount(); i++)
436 m_registries.push_back(parser.GetParam(i));
437 }
438
439 m_longlist = parser.Found("longlist");
440 m_list = m_longlist || parser.Found("list");
441 m_timing = parser.Found("timing");
442 m_detail = !m_timing && parser.Found("detail");
443
444 wxString loc;
445 if ( parser.Found("locale", &loc) )
446 {
447 const wxLanguageInfo * const info = wxLocale::FindLanguageInfo(loc);
448 if ( !info )
449 {
450 cerr << "Locale \"" << string(loc.mb_str()) << "\" is unknown.\n";
451 return false;
452 }
453
454 m_locale = new wxLocale(info->Language);
455 if ( !m_locale->IsOk() )
456 {
457 cerr << "Using locale \"" << string(loc.mb_str()) << "\" failed.\n";
458 return false;
459 }
460 }
461
462 return TestAppBase::OnCmdLineParsed(parser);
463 }
464
465 // Event handling
466 int TestApp::FilterEvent(wxEvent& event)
467 {
468 if ( m_filterEventFunc )
469 return (*m_filterEventFunc)(event);
470
471 return TestAppBase::FilterEvent(event);
472 }
473
474 bool TestApp::ProcessEvent(wxEvent& event)
475 {
476 if ( m_processEventFunc )
477 return (*m_processEventFunc)(event);
478
479 return TestAppBase::ProcessEvent(event);
480 }
481
482 // Run
483 //
484 int TestApp::OnRun()
485 {
486 #if wxUSE_GUI
487 #ifdef __WXOSX__
488 // make sure there's always an autorelease pool ready
489 wxMacAutoreleasePool autoreleasepool;
490 #endif
491 #endif
492
493 #if wxUSE_LOG
494 // Switch off logging unless --verbose
495 bool verbose = wxLog::GetVerbose();
496 wxLog::EnableLogging(verbose);
497 #else
498 bool verbose = false;
499 #endif
500
501 CppUnit::TextTestRunner runner;
502
503 if ( m_registries.empty() )
504 {
505 // run or list all tests
506 AddTest(runner, TestFactoryRegistry::getRegistry().makeTest());
507 }
508 else // run only the selected tests
509 {
510 for (size_t i = 0; i < m_registries.size(); i++)
511 {
512 const wxString reg = m_registries[i];
513 Test *test = GetTestByName(reg);
514
515 if ( !test && !reg.EndsWith("TestCase") )
516 {
517 test = GetTestByName(reg + "TestCase");
518 }
519
520 if ( !test )
521 {
522 cerr << "No such test suite: " << string(reg.mb_str()) << endl;
523 return 2;
524 }
525
526 AddTest(runner, test);
527 }
528 }
529
530 if ( m_list )
531 return EXIT_SUCCESS;
532
533 runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), cout));
534
535 // there is a bug
536 // (http://sf.net/tracker/index.php?func=detail&aid=1649369&group_id=11795&atid=111795)
537 // in some versions of cppunit: they write progress dots to cout (and not
538 // cerr) and don't flush it so all the dots appear at once at the end which
539 // is not very useful so unbuffer cout to work around this
540 cout.setf(ios::unitbuf);
541
542 // add detail listener if needed
543 DetailListener detailListener(m_timing);
544 if ( m_detail || m_timing )
545 runner.eventManager().addListener(&detailListener);
546
547 // finally ensure that we report our own exceptions nicely instead of
548 // giving "uncaught exception of unknown type" messages
549 runner.eventManager().pushProtector(new wxUnitTestProtector);
550
551 bool printProgress = !(verbose || m_detail || m_timing);
552 return runner.run("", false, true, printProgress) ? EXIT_SUCCESS : EXIT_FAILURE;
553 }
554
555 int TestApp::OnExit()
556 {
557 delete m_locale;
558
559 #if wxUSE_GUI
560 delete GetTopWindow();
561 #endif // wxUSE_GUI
562
563 return 0;
564 }
565
566 // List the tests
567 //
568 void TestApp::List(Test *test, const string& parent /*=""*/) const
569 {
570 TestSuite *suite = dynamic_cast<TestSuite*>(test);
571 string name;
572
573 if (suite) {
574 // take the last component of the name and append to the parent
575 name = test->getName();
576 string::size_type i = name.find_last_of(".:");
577 if (i != string::npos)
578 name = name.substr(i + 1);
579 name = parent + "." + name;
580
581 // drop the 1st component from the display and indent
582 if (parent != "") {
583 string::size_type j = i = name.find('.', 1);
584 while ((j = name.find('.', j + 1)) != string::npos)
585 cout << " ";
586 cout << " " << name.substr(i + 1) << "\n";
587 }
588
589 typedef vector<Test*> Tests;
590 typedef Tests::const_iterator Iter;
591
592 const Tests& tests = suite->getTests();
593
594 for (Iter it = tests.begin(); it != tests.end(); ++it)
595 List(*it, name);
596 }
597 else if (m_longlist) {
598 string::size_type i = 0;
599 while ((i = parent.find('.', i + 1)) != string::npos)
600 cout << " ";
601 cout << " " << test->getName() << "\n";
602 }
603 }