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