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