1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        tests/strings/vsnprintf.cpp
3 // Purpose:     wxVsnprintf unit test
4 // Author:      Francesco Montorsi
5 //              (part of this file was taken from CMP.c of TRIO package
6 //               written by Bjorn Reese and Daniel Stenberg)
7 // Created:     2006-04-01
8 // Copyright:   (c) 2006 Francesco Montorsi, Bjorn Reese and Daniel Stenberg
9 ///////////////////////////////////////////////////////////////////////////////
10 
11 // ----------------------------------------------------------------------------
12 // headers
13 // ----------------------------------------------------------------------------
14 
15 #include "testprec.h"
16 
17 
18 #include "wx/crt.h"
19 
20 #if wxUSE_WXVSNPRINTF
21 
22 #ifndef WX_PRECOMP
23     #include "wx/wx.h"
24     #include "wx/wxchar.h"
25 #endif // WX_PRECOMP
26 
27 
28 // NOTE: for more info about the specification of wxVsnprintf() behaviour you can
29 //       refer to the following page of the GNU libc manual:
30 //             http://www.gnu.org/software/libc/manual/html_node/Formatted-Output.html
31 
32 
33 // ----------------------------------------------------------------------------
34 // global utilities for testing
35 // ----------------------------------------------------------------------------
36 
37 #define MAX_TEST_LEN        1024
38 
39 // temporary buffers
40 static wxChar buf[MAX_TEST_LEN];
41 int r;
42 
43 // Helper macro verifying both the return value of wxSnprintf() and its output.
44 //
45 // NOTE: the expected string length with this macro must not exceed MAX_TEST_LEN
46 
47 #define CMP(expected, fmt, ...)                          \
48     r=wxSnprintf(buf, MAX_TEST_LEN, fmt, ##__VA_ARGS__); \
49     CHECK( r == (int)wxStrlen(buf) );                    \
50     CHECK( buf == wxString(expected) )
51 
52 // Another helper which takes the size explicitly instead of using MAX_TEST_LEN
53 //
54 // NOTE: this macro is used also with too-small buffers (see Miscellaneous())
55 //       test function, thus the return value can be either -1 or > size and we
56 //       cannot check if r == (int)wxStrlen(buf)
57 #define CMPTOSIZE(buffer, size, failuremsg, expected, fmt, ...) \
58     r=wxSnprintf(buffer, size, fmt, ##__VA_ARGS__);             \
59     INFO(failuremsg);                                           \
60     CHECK( buffer == wxString(expected).Left(size - 1) )
61 
62 // this is the same as wxSnprintf() but it passes the format string to
63 // wxVsnprintf() without using WX_ATTRIBUTE_PRINTF and thus suppresses the gcc
64 // checks (and resulting warnings) for the format string
65 //
66 // use with extreme care and only when you're really sure the warnings must be
67 // suppressed!
68 template<typename T>
69 static int
wxUnsafeSnprintf(T * buf,size_t len,const wxChar * fmt,...)70 wxUnsafeSnprintf(T *buf, size_t len, const wxChar *fmt, ...)
71 {
72     va_list args;
73     va_start(args, fmt);
74 
75     int rc = wxVsnprintf(buf, len, fmt, args);
76 
77     va_end(args);
78 
79     return rc;
80 }
81 
82 // ----------------------------------------------------------------------------
83 // test fixture
84 // ----------------------------------------------------------------------------
85 
86 // Explicitly set C locale to avoid check failures when running on machines
87 // with a locale where the decimal point is not '.'
88 class VsnprintfTestCase : CLocaleSetter
89 {
90 public:
VsnprintfTestCase()91     VsnprintfTestCase() : CLocaleSetter() { }
92 
93 protected:
94     template<typename T>
95         void DoBigToSmallBuffer(T *buffer, int size);
96 
97     // compares the expectedString and the result of wxVsnprintf() char by char
98     // for all its length (not only for first expectedLen chars) and also
99     // checks the return value
100     void DoMisc(int expectedLen, const wxString& expectedString,
101                 size_t max, const wxChar *format, ...);
102 
103     wxDECLARE_NO_COPY_CLASS(VsnprintfTestCase);
104 };
105 
106 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::C", "[vsnprintf]")
107 {
108     CMP("hi!", "%c%c%c", wxT('h'), wxT('i'), wxT('!'));
109 
110     // NOTE:
111     // the NULL characters _can_ be passed to %c to e.g. create strings
112     // with embedded NULs (because strings are not always supposed to be
113     // NUL-terminated).
114 
115     DoMisc(14, wxT("Hello \0 World!"), 16, wxT("Hello %c World!"), wxT('\0'));
116 }
117 
118 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::D", "[vsnprintf]")
119 {
120     CMP("+123456", "%+d", 123456);
121     CMP("-123456", "%d", -123456);
122     CMP(" 123456", "% d", 123456);
123     CMP("    123456", "%10d", 123456);
124     CMP("0000123456", "%010d", 123456);
125     CMP("-123456   ", "%-10d", -123456);
126 }
127 
128 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::X", "[vsnprintf]")
129 {
130     CMP("ABCD", "%X", 0xABCD);
131     CMP("0XABCD", "%#X", 0xABCD);
132     CMP("0xabcd", "%#x", 0xABCD);
133 }
134 
135 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::O", "[vsnprintf]")
136 {
137     CMP("1234567", "%o", 01234567);
138     CMP("01234567", "%#o", 01234567);
139 }
140 
141 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::P", "[vsnprintf]")
142 {
143     // The exact format used for "%p" is not specified by the standard and so
144     // varies among different platforms, so we need to expect different results
145     // here (remember that while we test our own wxPrintf() code here, it uses
146     // the system sprintf() for actual formatting so the results are still
147     // different under different systems).
148 
149 #if defined(__VISUALC__) || (defined(__MINGW32__) && \
150         (!defined(__USE_MINGW_ANSI_STDIO) || !__USE_MINGW_ANSI_STDIO))
151     #if SIZEOF_VOID_P == 4
152         CMP("00ABCDEF", "%p", (void*)0xABCDEF);
153         CMP("00000000", "%p", (void*)NULL);
154     #elif SIZEOF_VOID_P == 8
155         CMP("0000ABCDEFABCDEF", "%p", (void*)0xABCDEFABCDEF);
156         CMP("0000000000000000", "%p", (void*)NULL);
157     #endif
158 #elif defined(__MINGW32__)
159     #if SIZEOF_VOID_P == 4
160         CMP("00abcdef", "%p", (void*)0xABCDEF);
161         CMP("00000000", "%p", (void*)NULL);
162     #elif SIZEOF_VOID_P == 8
163         CMP("0000abcdefabcdef", "%p", (void*)0xABCDEFABCDEF);
164         CMP("0000000000000000", "%p", (void*)NULL);
165     #endif
166 #elif defined(__GNUG__)
167     // glibc prints pointers as %#x except for NULL pointers which are printed
168     // as '(nil)'.
169     CMP("0xabcdef", "%p", (void*)0xABCDEF);
170     CMP("(nil)", "%p", (void*)NULL);
171 #endif
172 }
173 
174 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::N", "[vsnprintf]")
175 {
176     int nchar;
177 
178     wxSnprintf(buf, MAX_TEST_LEN, wxT("%d %s%n\n"), 3, wxT("bears"), &nchar);
179     CHECK( nchar == 7 );
180 }
181 
182 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::E", "[vsnprintf]")
183 {
184     // NB: Use at least three digits for the exponent to workaround
185     //     differences between MSVC, MinGW and GNU libc.
186     //     See wxUSING_MANTISSA_SIZE_3 in testprec.h as well.
187     //
188     //     Some examples:
189     //       printf("%e",2.342E+02);
190     //     -> under MSVC7.1 prints:      2.342000e+002
191     //     -> under GNU libc 2.4 prints: 2.342000e+02
192     CMP("2.342000e+112", "%e",2.342E+112);
193     CMP("-2.3420e-112", "%10.4e",-2.342E-112);
194     CMP("-2.3420e-112", "%11.4e",-2.342E-112);
195     CMP("   -2.3420e-112", "%15.4e",-2.342E-112);
196 
197     CMP("-0.02342", "%G",-2.342E-02);
198     CMP("3.1415E-116", "%G",3.1415e-116);
199     CMP("0003.141500e+103", "%016e", 3141.5e100);
200     CMP("   3.141500e+103", "%16e", 3141.5e100);
201     CMP("3.141500e+103   ", "%-16e", 3141.5e100);
202     CMP("3.142e+103", "%010.3e", 3141.5e100);
203 }
204 
205 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::F", "[vsnprintf]")
206 {
207     CMP("3.300000", "%5f", 3.3);
208     CMP("3.000000", "%5f", 3.0);
209     CMP("0.000100", "%5f", .999999E-4);
210     CMP("0.000990", "%5f", .99E-3);
211     CMP("3333.000000", "%5f", 3333.0);
212 }
213 
214 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::G", "[vsnprintf]")
215 {
216     // NOTE: the same about E() testcase applies here...
217 
218     CMP("  3.3", "%5g", 3.3);
219     CMP("    3", "%5g", 3.0);
220     CMP("9.99999e-115", "%5g", .999999E-114);
221     CMP("0.00099", "%5g", .99E-3);
222     CMP(" 3333", "%5g", 3333.0);
223     CMP(" 0.01", "%5g", 0.01);
224 
225     CMP("    3", "%5.g", 3.3);
226     CMP("    3", "%5.g", 3.0);
227     CMP("1e-114", "%5.g", .999999E-114);
228     CMP("0.0001", "%5.g", 1.0E-4);
229     CMP("0.001", "%5.g", .99E-3);
230     CMP("3e+103", "%5.g", 3333.0E100);
231     CMP(" 0.01", "%5.g", 0.01);
232 
233     CMP("  3.3", "%5.2g", 3.3);
234     CMP("    3", "%5.2g", 3.0);
235     CMP("1e-114", "%5.2g", .999999E-114);
236     CMP("0.00099", "%5.2g", .99E-3);
237     CMP("3.3e+103", "%5.2g", 3333.0E100);
238     CMP(" 0.01", "%5.2g", 0.01);
239 }
240 
241 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::S", "[vsnprintf]")
242 {
243     CMP("  abc", "%5s", wxT("abc"));
244     CMP("    a", "%5s", wxT("a"));
245     CMP("abcdefghi", "%5s", wxT("abcdefghi"));
246     CMP("abc  ", "%-5s", wxT("abc"));
247     CMP("abcdefghi", "%-5s", wxT("abcdefghi"));
248 
249     CMP("abcde", "%.5s", wxT("abcdefghi"));
250 
251     // do the same tests but with Unicode characters:
252 #if wxUSE_UNICODE
253 
254     // Unicode code points from U+03B1 to U+03B9 are the greek letters alpha-iota;
255     // UTF8 encoding of such code points is 0xCEB1 to 0xCEB9
256 
257 #define ALPHA       "\xCE\xB1"
258         // alpha
259 #define ABC         "\xCE\xB1\xCE\xB2\xCE\xB3"
260         // alpha+beta+gamma
261 #define ABCDE       "\xCE\xB1\xCE\xB2\xCE\xB3\xCE\xB4\xCE\xB5"
262         // alpha+beta+gamma+delta+epsilon
263 #define ABCDEFGHI   "\xCE\xB1\xCE\xB2\xCE\xB3\xCE\xB4\xCE\xB5\xCE\xB6\xCE\xB7\xCE\xB8\xCE\xB9"
264         // alpha+beta+gamma+delta+epsilon+zeta+eta+theta+iota
265 
266     // the 'expected' and 'arg' parameters of this macro are supposed to be
267     // UTF-8 strings
268 #define CMP_UTF8(expected, fmt, arg)                                          \
269     CHECK                                                                     \
270     (                                                                         \
271         (int)wxString::FromUTF8(expected).length() ==                         \
272         wxSnprintf(buf, MAX_TEST_LEN, fmt, wxString::FromUTF8(arg))           \
273     );                                                                        \
274     CHECK( wxString::FromUTF8(expected) == buf )
275 
276     CMP_UTF8("  " ABC,     "%5s",  ABC);
277     CMP_UTF8("    " ALPHA, "%5s",  ALPHA);
278     CMP_UTF8(ABCDEFGHI,    "%5s",  ABCDEFGHI);
279     CMP_UTF8(ABC "  ",     "%-5s", ABC);
280     CMP_UTF8(ABCDEFGHI,    "%-5s", ABCDEFGHI);
281     CMP_UTF8(ABCDE,        "%.5s", ABCDEFGHI);
282 #endif // wxUSE_UNICODE
283 
284     // test a string which has a NULL character after "ab";
285     // obviously it should be handled exactly like just as "ab"
286     CMP("   ab", "%5s", wxT("ab\0cdefghi"));
287 }
288 
289 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::Asterisk", "[vsnprintf]")
290 {
291     CMP("       0.1", "%*.*f", 10, 1, 0.123);
292     CMP("    0.1230", "%*.*f", 10, 4, 0.123);
293     CMP("0.1", "%*.*f", 3, 1, 0.123);
294 
295     CMP("%0.002", "%%%.*f", 3, 0.0023456789);
296 
297     CMP("       a", "%*c", 8, 'a');
298     CMP("    four", "%*s", 8, "four");
299     CMP("    four   four", "%*s %*s", 8, "four", 6, "four");
300 }
301 
302 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::Percent", "[vsnprintf]")
303 {
304     // some tests without any argument passed through ...
305     CMP("%", "%%");
306     CMP("%%%", "%%%%%%");
307 
308     CMP("%  abc", "%%%5s", wxT("abc"));
309     CMP("%  abc%", "%%%5s%%", wxT("abc"));
310 
311     // do not test odd number of '%' symbols as different implementations
312     // of snprintf() give different outputs as this situation is not considered
313     // by any standard (in fact, GCC will also warn you about a spurious % if
314     // you write %%% as argument of some *printf function !)
315     // Compare(wxT("%"), wxT("%%%"));
316 }
317 
318 #ifdef wxLongLong_t
319 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::LongLong", "[vsnprintf]")
320 {
321     CMP("123456789", "%lld", (wxLongLong_t)123456789);
322     CMP("-123456789", "%lld", (wxLongLong_t)-123456789);
323 
324     CMP("123456789", "%llu", (wxULongLong_t)123456789);
325 
326 #ifdef __WINDOWS__
327     CMP("123456789", "%I64d", (wxLongLong_t)123456789);
328     CMP("123456789abcdef", "%I64x", wxLL(0x123456789abcdef));
329 #endif
330 }
331 #endif
332 
333 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::WrongFormatStrings", "[vsnprintf]")
334 {
335     // test how wxVsnprintf() behaves with wrong format string:
336 
337     // a missing positional arg should result in an assert
338     WX_ASSERT_FAILS_WITH_ASSERT(
339             wxSnprintf(buf, MAX_TEST_LEN, wxT("%1$d %3$d"), 1, 2, 3) );
340 
341     // positional and non-positionals in the same format string:
342     errno = 0;
343     r = wxSnprintf(buf, MAX_TEST_LEN, wxT("%1$d %d %3$d"), 1, 2, 3);
344     CHECK( r == -1 );
345     CHECK( errno == EINVAL );
346 }
347 
348 // BigToSmallBuffer() test case helper:
349 template<typename T>
DoBigToSmallBuffer(T * buffer,int size)350 void VsnprintfTestCase::DoBigToSmallBuffer(T *buffer, int size)
351 {
352     // Remember that wx*printf could be mapped either to system
353     // implementation or to wx implementation.
354     // In the first case, when the output buffer is too small, the returned
355     // value can be the number of characters required for the output buffer
356     // (conforming to ISO C99; implemented in e.g. GNU libc >= 2.1), or
357     // just a negative number, usually -1; (this is how e.g. MSVC's
358     // *printf() behaves). Luckily, in all implementations, when the
359     // output buffer is too small, it's nonetheless filled up to its max size.
360     //
361     // Note that in the second case (i.e. when we're using our own implementation),
362     // wxVsnprintf() will return the number of characters written in the standard
363     // output or
364     //   -1         if there was an error in the format string
365     //   maxSize+1  if the output buffer is too small
366 
367     wxString errStr;
368     errStr << "The size of the buffer was " << size;
369     std::string errMsg(errStr.mb_str());
370 
371     // test without positionals
372     CMPTOSIZE(buffer, size, errMsg,
373               "123456789012 - test - 123 -4.567",
374               "%i%li - test - %d %.3f",
375               123, (long int)456789012, 123, -4.567);
376 
377 #if wxUSE_PRINTF_POS_PARAMS
378     // test with positional
379     CMPTOSIZE(buffer, size, errMsg,
380               "-4.567 123 - test - 456789012 123",
381               "%4$.3f %1$i - test - %2$li %3$d",
382               123, (long int)456789012, 123, -4.567);
383 #endif
384 
385     // test unicode/ansi conversion specifiers
386     //
387     // NB: we use wxUnsafeSnprintf() as %hs and %hc are invalid in printf
388     //     format and gcc would warn about this otherwise
389 
390     r = wxUnsafeSnprintf(buffer, size,
391                          wxT("unicode string/char: %ls/%lc -- ansi string/char: %hs/%hc"),
392                          L"unicode", L'U', "ansi", 'A');
393     wxString expected =
394         wxString(wxT("unicode string/char: unicode/U -- ansi string/char: ansi/A")).Left(size - 1);
395 
396     CHECK( expected == buffer );
397 }
398 
399 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::BigToSmallBuffer", "[vsnprintf]")
400 {
401 #if wxUSE_UNICODE
402     wchar_t bufw[1024], bufw2[16], bufw3[4], bufw4;
403     DoBigToSmallBuffer(bufw, 1024);
404     DoBigToSmallBuffer(bufw2, 16);
405     DoBigToSmallBuffer(bufw3, 4);
406     DoBigToSmallBuffer(&bufw4, 1);
407 #endif // wxUSE_UNICODE
408 
409     char bufa[1024], bufa2[16], bufa3[4], bufa4;
410     DoBigToSmallBuffer(bufa, 1024);
411     DoBigToSmallBuffer(bufa2, 16);
412     DoBigToSmallBuffer(bufa3, 4);
413     DoBigToSmallBuffer(&bufa4, 1);
414 }
415 
416 // Miscellaneous() test case helper:
DoMisc(int expectedLen,const wxString & expectedString,size_t max,const wxChar * format,...)417 void VsnprintfTestCase::DoMisc(
418         int expectedLen,
419         const wxString& expectedString,
420         size_t max,
421         const wxChar *format, ...)
422 {
423     const size_t BUFSIZE = MAX_TEST_LEN - 1;
424     size_t i;
425     static int count = 0;
426 
427     wxASSERT(max <= BUFSIZE);
428 
429     for (i = 0; i < BUFSIZE; i++)
430         buf[i] = '*';
431     buf[BUFSIZE] = 0;
432 
433     va_list ap;
434     va_start(ap, format);
435 
436     int n = wxVsnprintf(buf, max, format, ap);
437 
438     va_end(ap);
439 
440     // Prepare messages so that it is possible to see from the error which
441     // test was running.
442     wxString errStr, overflowStr;
443     errStr << wxT("No.: ") << ++count << wxT(", expected: ") << expectedLen
444            << wxT(" '") << expectedString << wxT("', result: ");
445     overflowStr << errStr << wxT("buffer overflow");
446     errStr << n << wxT(" '") << buf << wxT("'");
447 
448     // turn them into std::strings
449     std::string errMsg(errStr.mb_str());
450     std::string overflowMsg(overflowStr.mb_str());
451 
452     INFO(errMsg);
453     if ( size_t(n) < max )
454         CHECK(expectedLen == n);
455     else
456         CHECK(expectedLen == -1);
457 
458     CHECK(expectedString == buf);
459 
460     for (i = max; i < BUFSIZE; i++)
461     {
462         INFO(overflowMsg);
463         CHECK(buf[i] == '*');
464     }
465 }
466 
467 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::Miscellaneous", "[vsnprintf]")
468 {
469     // expectedLen, expectedString, max, format, ...
470     DoMisc(5,  wxT("-1234"),   8, wxT("%d"), -1234);
471     DoMisc(7,  wxT("1234567"), 8, wxT("%d"), 1234567);
472     DoMisc(-1, wxT("1234567"), 8, wxT("%d"), 12345678);
473     DoMisc(-1, wxT("-123456"), 8, wxT("%d"), -1234567890);
474 
475     DoMisc(6,  wxT("123456"),  8, wxT("123456"));
476     DoMisc(7,  wxT("1234567"), 8, wxT("1234567"));
477     DoMisc(-1, wxT("1234567"), 8, wxT("12345678"));
478 
479     DoMisc(6,  wxT("123450"),  8, wxT("12345%d"), 0);
480     DoMisc(7,  wxT("1234560"), 8, wxT("123456%d"), 0);
481     DoMisc(-1, wxT("1234567"), 8, wxT("1234567%d"), 0);
482     DoMisc(-1, wxT("1234567"), 8, wxT("12345678%d"), 0);
483 
484     DoMisc(6,  wxT("12%45%"),  8, wxT("12%%45%%"));
485     DoMisc(7,  wxT("12%45%7"), 8, wxT("12%%45%%7"));
486     DoMisc(-1, wxT("12%45%7"), 8, wxT("12%%45%%78"));
487 
488     DoMisc(5,  wxT("%%%%%"),   6, wxT("%%%%%%%%%%"));
489     DoMisc(6,  wxT("%%%%12"),  7, wxT("%%%%%%%%%d"), 12);
490 }
491 
492 
493 /* (C) Copyright C E Chew
494 *
495 * Feel free to copy, use and distribute this software provided:
496 *
497 *        1. you do not pretend that you wrote it
498 *        2. you leave this copyright notice intact.
499 */
500 
501 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::GlibcMisc1", "[vsnprintf]")
502 {
503     CMP("     ",    "%5.s", "xyz");
504     CMP("   33",    "%5.f", 33.3);
505 #if defined(wxDEFAULT_MANTISSA_SIZE_3)
506     CMP("  3e+008", "%8.e", 33.3e7);
507     CMP("  3E+008", "%8.E", 33.3e7);
508     CMP("3e+001",    "%.g",  33.3);
509     CMP("3E+001",    "%.G",  33.3);
510 #else
511     CMP("   3e+08", "%8.e", 33.3e7);
512     CMP("   3E+08", "%8.E", 33.3e7);
513     CMP("3e+01",    "%.g",  33.3);
514     CMP("3E+01",    "%.G",  33.3);
515 #endif
516 }
517 
518 TEST_CASE_METHOD(VsnprintfTestCase, "Vsnprintf::GlibcMisc2", "[vsnprintf]")
519 {
520     int prec;
521     wxString test_format;
522 
523     prec = 0;
524     CMP("3", "%.*g", prec, 3.3);
525 
526     prec = 0;
527     CMP("3", "%.*G", prec, 3.3);
528 
529     prec = 0;
530     CMP("      3", "%7.*G", prec, 3.33);
531 
532     prec = 3;
533     CMP(" 041", "%04.*o", prec, 33);
534 
535     prec = 7;
536     CMP("  0000033", "%09.*u", prec, 33);
537 
538     prec = 3;
539     CMP(" 021", "%04.*x", prec, 33);
540 
541     prec = 3;
542     CMP(" 021", "%04.*X", prec, 33);
543 }
544 
545 #endif // wxUSE_WXVSNPRINTF
546 
547