]> git.saurik.com Git - wxWidgets.git/blob - tests/regex/regextest.cpp
d3cb7c62c96d0f99f48165e9f41bb835e8149613
[wxWidgets.git] / tests / regex / regextest.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: tests/regex/regex.cpp
3 // Purpose: Test the built-in regex lib and wxRegEx
4 // Author: Mike Wetherell
5 // RCS-ID: $Id$
6 // Copyright: (c) 2004 Mike Wetherell
7 // Licence: wxWidgets licence
8 ///////////////////////////////////////////////////////////////////////////////
9
10 //
11 // Notes:
12 //
13 // To run just one section, say wx_1, do this:
14 // test regex.wx_1
15 //
16 // To run all the regex tests:
17 // test regex
18 //
19 // Some tests must be skipped since they use features which we do not make
20 // available through wxRegEx. To see the list of tests that have been skipped
21 // turn on verbose logging, e.g.:
22 // test --verbose regex
23 //
24 // The tests here are for the builtin library, tests for wxRegEx in general
25 // should go in wxregex.cpp
26 //
27 // The tests are generated from Henry Spencer's reg.test, additional test
28 // can be added in wxreg.test. These test files are then turned into a C++
29 // include file 'regex.inc' (included below) using a script 'regex.pl'.
30 //
31
32 // For compilers that support precompilation, includes "wx/wx.h".
33 #include "wx/wxprec.h"
34
35 #ifdef __BORLANDC__
36 #pragma hdrstop
37 #endif
38
39 // for all others, include the necessary headers
40 #ifndef WX_PRECOMP
41 #include "wx/wx.h"
42 #endif
43
44
45 // many of the tests are specific to the builtin regex lib, so only attempts
46 // to do them when using the builtin regex lib.
47 //
48 #ifdef wxHAS_REGEX_ADVANCED
49
50 #include "wx/regex.h"
51 #include "wx/cppunit.h"
52 #include <string>
53 #include <vector>
54
55 using CppUnit::Test;
56 using CppUnit::TestCase;
57 using CppUnit::TestSuite;
58 using CppUnit::Exception;
59
60 using namespace std;
61
62 ///////////////////////////////////////////////////////////////////////////////
63 // The test case - an instance represents a single test
64
65 class RegExTestCase : public TestCase
66 {
67 public:
68 // constructor - create a single testcase
69 RegExTestCase(
70 const string& name,
71 const char *mode,
72 const char *id,
73 const char *flags,
74 const char *pattern,
75 const char *data,
76 const vector<const char *>& expected);
77
78 protected:
79 // run this testcase
80 void runTest();
81
82 private:
83 // workers
84 wxString Conv(const char *str);
85 void parseFlags(const wxString& flags);
86 void doTest(int flavor);
87 static wxString quote(const wxString& arg);
88 const wxChar *convError() const { return _T("<cannot convert>"); }
89
90 // assertions - adds some information about the test that failed
91 void fail(const wxString& msg) const;
92 void failIf(bool condition, const wxString& msg) const
93 { if (condition) fail(msg); }
94
95 // mode, id, flags, pattern, test data, expected results...
96 int m_mode;
97 wxString m_id;
98 wxString m_flags;
99 wxString m_pattern;
100 wxString m_data;
101 wxArrayString m_expected;
102
103 // the flag decoded
104 int m_compileFlags;
105 int m_matchFlags;
106 bool m_basic;
107 bool m_extended;
108 bool m_advanced;
109 };
110
111 // constructor - throws Exception on failure
112 //
113 RegExTestCase::RegExTestCase(
114 const string& name,
115 const char *mode,
116 const char *id,
117 const char *flags,
118 const char *pattern,
119 const char *data,
120 const vector<const char *>& expected)
121 :
122 TestCase(name),
123 m_mode(mode[0]),
124 m_id(Conv(id)),
125 m_flags(Conv(flags)),
126 m_pattern(Conv(pattern)),
127 m_data(Conv(data)),
128 m_compileFlags(0),
129 m_matchFlags(0),
130 m_basic(false),
131 m_extended(false),
132 m_advanced(false)
133 {
134 bool badconv = m_pattern == convError() || m_data == convError();
135 vector<const char *>::const_iterator it;
136
137 for (it = expected.begin(); it != expected.end(); ++it) {
138 m_expected.push_back(Conv(*it));
139 badconv = badconv || *m_expected.rbegin() == convError();
140 }
141
142 failIf(badconv, _T("cannot convert to default character encoding"));
143
144 // the flags need further parsing...
145 parseFlags(m_flags);
146
147 #ifndef wxHAS_REGEX_ADVANCED
148 failIf(!m_basic && !m_extended, _T("advanced regexs not available"));
149 #endif
150 }
151
152 int wxWcscmp(const wchar_t* s1, const wchar_t* s2)
153 {
154 size_t nLen1 = wxWcslen(s1);
155 size_t nLen2 = wxWcslen(s2);
156
157 if (nLen1 != nLen2)
158 return nLen1 - nLen2;
159
160 return wxMemcmp(s1, s2, nLen1);
161 }
162
163 // convert a string from UTF8 to the internal encoding
164 //
165 wxString RegExTestCase::Conv(const char *str)
166 {
167 const wxWCharBuffer wstr = wxConvUTF8.cMB2WC(str);
168 const wxWC2WXbuf buf = wxConvCurrent->cWC2WX(wstr);
169
170 if (!buf || wxWcscmp(wxConvCurrent->cWX2WC(buf), wstr) != 0)
171 return convError();
172 else
173 return buf;
174 }
175
176 // Parse flags
177 //
178 void RegExTestCase::parseFlags(const wxString& flags)
179 {
180 for (const wxChar *p = flags; *p; p++) {
181 switch (*p) {
182 // noop
183 case '-': break;
184
185 // we don't fully support these flags, but they don't stop us
186 // checking for success of failure of the match, so treat as noop
187 case 'A': case 'B': case 'E': case 'H':
188 case 'I': case 'L': case 'M': case 'N':
189 case 'P': case 'Q': case 'R': case 'S':
190 case 'T': case 'U': case '%':
191 break;
192
193 // match options
194 case '^': m_matchFlags |= wxRE_NOTBOL; break;
195 case '$': m_matchFlags |= wxRE_NOTEOL; break;
196 #if wxUSE_UNICODE
197 case '*': break;
198 #endif
199 // compile options
200 case '&': m_advanced = m_basic = true; break;
201 case 'b': m_basic = true; break;
202 case 'e': m_extended = true; break;
203 case 'i': m_compileFlags |= wxRE_ICASE; break;
204 case 'o': m_compileFlags |= wxRE_NOSUB; break;
205 case 'n': m_compileFlags |= wxRE_NEWLINE; break;
206 case 't': if (strchr("ep", m_mode)) break; // else fall through...
207
208 // anything else we must skip the test
209 default:
210 fail(wxString::Format(
211 _T("requires unsupported flag '%c'"), *p));
212 }
213 }
214 }
215
216 // Try test for all flavours of expression specified
217 //
218 void RegExTestCase::runTest()
219 {
220 if (m_basic)
221 doTest(wxRE_BASIC);
222 if (m_extended)
223 doTest(wxRE_EXTENDED);
224 #ifdef wxHAS_REGEX_ADVANCED
225 if (m_advanced || (!m_basic && !m_extended))
226 doTest(wxRE_ADVANCED);
227 #endif
228 }
229
230 // Try the test for a single flavour of expression
231 //
232 void RegExTestCase::doTest(int flavor)
233 {
234 wxRegEx re(m_pattern, m_compileFlags | flavor);
235
236 // 'e' - test that the pattern fails to compile
237 if (m_mode == 'e') {
238 failIf(re.IsValid(), _T("compile succeeded (should fail)"));
239 return;
240 }
241 failIf(!re.IsValid(), _T("compile failed"));
242
243 bool matches = re.Matches(m_data, m_matchFlags);
244
245 // 'f' or 'p' - test that the pattern does not match
246 if (m_mode == 'f' || m_mode == 'p') {
247 failIf(matches, _T("match succeeded (should fail)"));
248 return;
249 }
250
251 // otherwise 'm' or 'i' - test the pattern does match
252 failIf(!matches, _T("match failed"));
253
254 if (m_compileFlags & wxRE_NOSUB)
255 return;
256
257 // check wxRegEx has correctly counted the number of subexpressions
258 failIf(m_expected.size() != re.GetMatchCount(),
259 wxString::Format(_T("GetMatchCount() == %d, expected %d"),
260 re.GetMatchCount(), m_expected.size()));
261
262 wxString result;
263 size_t start, len;
264
265 for (size_t i = 0; i < m_expected.size(); i++) {
266 failIf(!re.GetMatch(&start, &len, i), wxString::Format(
267 _T("wxRegEx::GetMatch failed for match %d"), i));
268
269 // m - check the match returns the strings given
270 if (m_mode == 'm')
271 if (start < INT_MAX)
272 result = m_data.substr(start, len);
273 else
274 result = _T("");
275
276 // i - check the match returns the offsets given
277 else if (m_mode == 'i')
278 if (start < INT_MAX)
279 result = wxString::Format(_T("%d %d"), start, start + len - 1);
280 else
281 result = _T("-1 -1");
282
283 failIf(result != m_expected[i], wxString::Format(
284 _T("match(%d) == %s, expected == %s"), i,
285 quote(result).c_str(), quote(m_expected[i]).c_str()));
286 }
287 }
288
289 // assertion - adds some information about the test that failed
290 //
291 void RegExTestCase::fail(const wxString& msg) const
292 {
293 wxString str;
294 wxArrayString::const_iterator it;
295
296 str << (wxChar)m_mode << _T(" ") << m_id << _T(" ") << m_flags << _T(" ")
297 << quote(m_pattern) << _T(" ") << quote(m_data);
298
299 for (it = m_expected.begin(); it != m_expected.end(); ++it)
300 str << _T(" ") << quote(*it);
301
302 if (str.length() > 77)
303 str = str.substr(0, 74) + _T("...");
304
305 str << _T("\n ") << msg;
306
307 // no lossy convs so using utf8
308 CPPUNIT_FAIL(string(str.mb_str(wxConvUTF8)));
309 }
310
311 // quote a string so that it can be displayed (static)
312 //
313 wxString RegExTestCase::quote(const wxString& arg)
314 {
315 const wxChar *needEscape = _T("\a\b\t\n\v\f\r\"\\");
316 const wxChar *escapes = _T("abtnvfr\"\\");
317 wxString str;
318
319 for (size_t i = 0; i < arg.length(); i++) {
320 wxUChar ch = arg[i];
321 const wxChar *p = wxStrchr(needEscape, ch);
322
323 if (p)
324 str += wxString::Format(_T("\\%c"), escapes[p - needEscape]);
325 else if (wxIscntrl(ch))
326 str += wxString::Format(_T("\\%03o"), ch);
327 else
328 str += ch;
329 }
330
331 return str.length() == arg.length() && str.find(' ') == wxString::npos ?
332 str : _T("\"") + str + _T("\"");
333 }
334
335
336 ///////////////////////////////////////////////////////////////////////////////
337 // Test suite
338
339 class RegExTestSuite : public TestSuite
340 {
341 public:
342 RegExTestSuite(string name) : TestSuite(name) { }
343 void add(const char *mode, const char *id, const char *flags,
344 const char *pattern, const char *data, const char *expected, ...);
345 };
346
347 // Add a testcase to the suite
348 //
349 void RegExTestSuite::add(
350 const char *mode,
351 const char *id,
352 const char *flags,
353 const char *pattern,
354 const char *data,
355 const char *expected, ...)
356 {
357 string name = getName() + "." + id;
358
359 vector<const char *> expected_results;
360 va_list ap;
361
362 for (va_start(ap, expected); expected; expected = va_arg(ap, const char *))
363 expected_results.push_back(expected);
364
365 va_end(ap);
366
367 try {
368 addTest(new RegExTestCase(
369 name, mode, id, flags, pattern, data, expected_results));
370 }
371 catch (Exception& e) {
372 wxLogInfo(wxString::Format(_T("skipping: %s\n %s\n"),
373 wxString(name.c_str(), wxConvUTF8).c_str(),
374 wxString(e.what(), wxConvUTF8).c_str()));
375 }
376 }
377
378
379 // Include the generated tests
380 //
381 #include "regex.inc"
382
383
384 #endif // wxHAS_REGEX_ADVANCED