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