source: trunk/src/testlib/qplaintestlogger.cpp@ 787

Last change on this file since 787 was 769, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.3 sources from branches/vendor/nokia/qt.

File size: 16.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation (qt-info@nokia.com)
6**
7** This file is part of the QtTest module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at qt-info@nokia.com.
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "QtTest/private/qtestresult_p.h"
43#include "QtTest/qtestassert.h"
44#include "QtTest/private/qtestlog_p.h"
45#include "QtTest/private/qplaintestlogger_p.h"
46#include "QtTest/private/qbenchmark_p.h"
47
48#include <stdarg.h>
49#include <stdio.h>
50#include <stdlib.h>
51#include <string.h>
52
53#ifdef Q_OS_WIN
54#include "windows.h"
55#endif
56
57#if defined(Q_OS_SYMBIAN)
58#include <e32debug.h>
59#endif
60
61#ifdef Q_OS_WINCE
62#include <QtCore/QString>
63#endif
64
65#include <QtCore/QByteArray>
66#include <QtCore/qmath.h>
67
68QT_BEGIN_NAMESPACE
69
70namespace QTest {
71
72#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
73
74 static CRITICAL_SECTION outputCriticalSection;
75 static HANDLE hConsole = INVALID_HANDLE_VALUE;
76 static WORD consoleAttributes = 0;
77
78 static const char *qWinColoredMsg(int prefix, int color, const char *msg)
79 {
80 if (!hConsole)
81 return msg;
82
83 WORD attr = consoleAttributes & ~(FOREGROUND_GREEN | FOREGROUND_BLUE
84 | FOREGROUND_RED | FOREGROUND_INTENSITY);
85 if (prefix)
86 attr |= FOREGROUND_INTENSITY;
87 if (color == 32)
88 attr |= FOREGROUND_GREEN;
89 if (color == 36)
90 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN;
91 if (color == 31)
92 attr |= FOREGROUND_RED | FOREGROUND_INTENSITY;
93 if (color == 37)
94 attr |= FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
95 if (color == 33)
96 attr |= FOREGROUND_RED | FOREGROUND_GREEN;
97 SetConsoleTextAttribute(hConsole, attr);
98 printf(msg);
99 SetConsoleTextAttribute(hConsole, consoleAttributes);
100 return "";
101 }
102
103# define COLORED_MSG(prefix, color, msg) colored ? qWinColoredMsg(prefix, color, msg) : msg
104#else
105# define COLORED_MSG(prefix, color, msg) colored && QAbstractTestLogger::isTtyOutput() ? "\033["#prefix";"#color"m" msg "\033[0m" : msg
106#endif
107
108 static const char *incidentType2String(QAbstractTestLogger::IncidentTypes type)
109 {
110 static bool colored = (!qgetenv("QTEST_COLORED").isEmpty());
111 switch (type) {
112 case QAbstractTestLogger::Pass:
113 return COLORED_MSG(0, 32, "PASS "); //green
114 case QAbstractTestLogger::XFail:
115 return COLORED_MSG(1, 32, "XFAIL "); //light green
116 case QAbstractTestLogger::Fail:
117 return COLORED_MSG(0, 31, "FAIL! "); //red
118 case QAbstractTestLogger::XPass:
119 return COLORED_MSG(0, 31, "XPASS "); //red, too
120 }
121 return "??????";
122 }
123
124 static const char *benchmarkResult2String()
125 {
126 static bool colored = (!qgetenv("QTEST_COLORED").isEmpty());
127 return COLORED_MSG(0, 36, "RESULT "); // cyan
128 }
129
130 static const char *messageType2String(QAbstractTestLogger::MessageTypes type)
131 {
132#ifdef Q_OS_WIN
133 static bool colored = (!qgetenv("QTEST_COLORED").isEmpty());
134#else
135 static bool colored = ::getenv("QTEST_COLORED");
136#endif
137 switch (type) {
138 case QAbstractTestLogger::Skip:
139 return COLORED_MSG(0, 37, "SKIP "); //white
140 case QAbstractTestLogger::Warn:
141 return COLORED_MSG(0, 33, "WARNING"); // yellow
142 case QAbstractTestLogger::QWarning:
143 return COLORED_MSG(1, 33, "QWARN ");
144 case QAbstractTestLogger::QDebug:
145 return COLORED_MSG(1, 33, "QDEBUG ");
146 case QAbstractTestLogger::QSystem:
147 return COLORED_MSG(1, 33, "QSYSTEM");
148 case QAbstractTestLogger::QFatal:
149 return COLORED_MSG(0, 31, "QFATAL "); // red
150 case QAbstractTestLogger::Info:
151 return "INFO "; // no coloring
152 }
153 return "??????";
154 }
155
156 static void outputMessage(const char *str)
157 {
158#if defined(Q_OS_WINCE)
159 QString strUtf16 = QString::fromLatin1(str);
160 const int maxOutputLength = 255;
161 do {
162 QString tmp = strUtf16.left(maxOutputLength);
163 OutputDebugString((wchar_t*)tmp.utf16());
164 strUtf16.remove(0, maxOutputLength);
165 } while (!strUtf16.isEmpty());
166 if (QTestLog::outputFileName())
167#elif defined(Q_OS_WIN)
168 EnterCriticalSection(&outputCriticalSection);
169 // OutputDebugString is not threadsafe
170 OutputDebugStringA(str);
171 LeaveCriticalSection(&outputCriticalSection);
172#elif defined(Q_OS_SYMBIAN)
173 // RDebug::Print has a cap of 256 characters so break it up
174 TPtrC8 ptr(reinterpret_cast<const TUint8*>(str));
175 _LIT(format, "[QTestLib] %S");
176 const int maxBlockSize = 256 - ((const TDesC &)format).Length();
177 HBufC* hbuffer = HBufC::New(maxBlockSize);
178 if(hbuffer) {
179 for (int i = 0; i < ptr.Length(); i += maxBlockSize) {
180 int size = Min(maxBlockSize, ptr.Length() - i);
181 hbuffer->Des().Copy(ptr.Mid(i, size));
182 RDebug::Print(format, hbuffer);
183 }
184 delete hbuffer;
185 }
186 else {
187 // fast, no allocations, but truncates silently
188 RDebug::RawPrint(format);
189 TPtrC8 ptr(reinterpret_cast<const TUint8*>(str));
190 RDebug::RawPrint(ptr);
191 RDebug::RawPrint(_L8("\n"));
192 }
193#endif
194 QAbstractTestLogger::outputString(str);
195 }
196
197 static void printMessage(const char *type, const char *msg, const char *file = 0, int line = 0)
198 {
199 QTEST_ASSERT(type);
200 QTEST_ASSERT(msg);
201
202 QTestCharBuffer buf;
203
204 const char *fn = QTestResult::currentTestFunction() ? QTestResult::currentTestFunction()
205 : "UnknownTestFunc";
206 const char *tag = QTestResult::currentDataTag() ? QTestResult::currentDataTag() : "";
207 const char *gtag = QTestResult::currentGlobalDataTag()
208 ? QTestResult::currentGlobalDataTag()
209 : "";
210 const char *filler = (tag[0] && gtag[0]) ? ":" : "";
211 if (file) {
212 QTest::qt_asprintf(&buf, "%s: %s::%s(%s%s%s)%s%s\n"
213#ifdef Q_OS_WIN
214 "%s(%d) : failure location\n"
215#else
216 " Loc: [%s(%d)]\n"
217#endif
218 , type, QTestResult::currentTestObjectName(), fn, gtag, filler, tag,
219 msg[0] ? " " : "", msg, file, line);
220 } else {
221 QTest::qt_asprintf(&buf, "%s: %s::%s(%s%s%s)%s%s\n",
222 type, QTestResult::currentTestObjectName(), fn, gtag, filler, tag,
223 msg[0] ? " " : "", msg);
224 }
225 // In colored mode, printf above stripped our nonprintable control characters.
226 // Put them back.
227 memcpy(buf.data(), type, strlen(type));
228 outputMessage(buf.data());
229 }
230
231 template <typename T>
232 static int countSignificantDigits(T num)
233 {
234 if (num <= 0)
235 return 0;
236
237 int digits = 0;
238 qreal divisor = 1;
239
240 while (num / divisor >= 1) {
241 divisor *= 10;
242 ++digits;
243 }
244
245 return digits;
246 }
247
248 // Pretty-prints a benchmark result using the given number of digits.
249 template <typename T> QString formatResult(T number, int significantDigits)
250 {
251 if (number < T(0))
252 return QLatin1String("NAN");
253 if (number == T(0))
254 return QLatin1String("0");
255
256 QString beforeDecimalPoint = QString::number(qint64(number), 'f', 0);
257 QString afterDecimalPoint = QString::number(number, 'f', 20);
258 afterDecimalPoint.remove(0, beforeDecimalPoint.count() + 1);
259
260 int beforeUse = qMin(beforeDecimalPoint.count(), significantDigits);
261 int beforeRemove = beforeDecimalPoint.count() - beforeUse;
262
263 // Replace insignificant digits before the decimal point with zeros.
264 beforeDecimalPoint.chop(beforeRemove);
265 for (int i = 0; i < beforeRemove; ++i) {
266 beforeDecimalPoint.append(QLatin1Char('0'));
267 }
268
269 int afterUse = significantDigits - beforeUse;
270
271 // leading zeroes after the decimal point does not count towards the digit use.
272 if (beforeDecimalPoint == QLatin1String("0") && afterDecimalPoint.isEmpty() == false) {
273 ++afterUse;
274
275 int i = 0;
276 while (i < afterDecimalPoint.count() && afterDecimalPoint.at(i) == QLatin1Char('0')) {
277 ++i;
278 }
279
280 afterUse += i;
281 }
282
283 int afterRemove = afterDecimalPoint.count() - afterUse;
284 afterDecimalPoint.chop(afterRemove);
285
286 QChar separator = QLatin1Char(',');
287 QChar decimalPoint = QLatin1Char('.');
288
289 // insert thousands separators
290 int length = beforeDecimalPoint.length();
291 for (int i = beforeDecimalPoint.length() -1; i >= 1; --i) {
292 if ((length - i) % 3 == 0)
293 beforeDecimalPoint.insert(i, separator);
294 }
295
296 QString print;
297 print = beforeDecimalPoint;
298 if (afterUse > 0)
299 print.append(decimalPoint);
300
301 print += afterDecimalPoint;
302
303
304 return print;
305 }
306
307 template <typename T>
308 int formatResult(char * buffer, int bufferSize, T number, int significantDigits)
309 {
310 QString result = formatResult(number, significantDigits);
311 qstrncpy(buffer, result.toAscii().constData(), bufferSize);
312 int size = result.count();
313 return size;
314 }
315
316// static void printBenchmarkResult(const char *bmtag, int value, int iterations)
317 static void printBenchmarkResult(const QBenchmarkResult &result)
318 {
319 const char *bmtag = QTest::benchmarkResult2String();
320
321 char buf1[1024];
322 QTest::qt_snprintf(
323 buf1, sizeof(buf1), "%s: %s::%s",
324 bmtag,
325 QTestResult::currentTestObjectName(),
326 result.context.slotName.toAscii().data());
327
328
329 char bufTag[1024];
330 bufTag[0] = 0;
331 QByteArray tag = result.context.tag.toAscii();
332 if (tag.isEmpty() == false) {
333 QTest::qt_snprintf(bufTag, sizeof(bufTag), ":\"%s\"", tag.data());
334 }
335
336
337 char fillFormat[8];
338 int fillLength = 5;
339 QTest::qt_snprintf(
340 fillFormat, sizeof(fillFormat), ":\n%%%ds", fillLength);
341 char fill[1024];
342 QTest::qt_snprintf(fill, sizeof(fill), fillFormat, "");
343
344
345 QByteArray unitText = QBenchmarkGlobalData::current->measurer->unitText().toAscii();
346
347 qreal valuePerIteration = qreal(result.value) / qreal(result.iterations);
348 char resultBuffer[100] = "";
349 formatResult(resultBuffer, 100, valuePerIteration, countSignificantDigits(result.value));
350
351 QByteArray iterationText = "per iteration";
352
353 char buf2[1024];
354 Q_ASSERT(result.iterations > 0);
355 QTest::qt_snprintf(
356 buf2, sizeof(buf2), "%s %s %s",
357 resultBuffer,
358 unitText.data(),
359 iterationText.data());
360
361 char buf3[1024];
362 Q_ASSERT(result.iterations > 0);
363 QTest::qt_snprintf(
364 buf3, sizeof(buf3), " (total: %s, iterations: %d)\n",
365 QByteArray::number(result.value).constData(), // no 64-bit qt_snprintf support
366 result.iterations);
367
368 char buf[1024];
369 QTest::qt_snprintf(buf, sizeof(buf), "%s%s%s%s%s", buf1, bufTag, fill, buf2, buf3);
370 memcpy(buf, bmtag, strlen(bmtag));
371 outputMessage(buf);
372 }
373}
374
375QPlainTestLogger::QPlainTestLogger()
376{
377#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
378 InitializeCriticalSection(&QTest::outputCriticalSection);
379 QTest::hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
380 if (QTest::hConsole != INVALID_HANDLE_VALUE) {
381 CONSOLE_SCREEN_BUFFER_INFO info;
382 if (GetConsoleScreenBufferInfo(QTest::hConsole, &info)) {
383 QTest::consoleAttributes = info.wAttributes;
384 } else {
385 QTest::hConsole = INVALID_HANDLE_VALUE;
386 }
387 }
388#endif
389}
390
391QPlainTestLogger::~QPlainTestLogger()
392{
393#if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
394 DeleteCriticalSection(&QTest::outputCriticalSection);
395#endif
396}
397
398void QPlainTestLogger::startLogging()
399{
400 QAbstractTestLogger::startLogging();
401
402 char buf[1024];
403 if (QTestLog::verboseLevel() < 0) {
404 QTest::qt_snprintf(buf, sizeof(buf), "Testing %s\n",
405 QTestResult::currentTestObjectName());
406 } else {
407 QTest::qt_snprintf(buf, sizeof(buf),
408 "********* Start testing of %s *********\n"
409 "Config: Using QTest library " QTEST_VERSION_STR
410 ", Qt %s\n", QTestResult::currentTestObjectName(), qVersion());
411 }
412 QTest::outputMessage(buf);
413}
414
415void QPlainTestLogger::stopLogging()
416{
417 char buf[1024];
418 if (QTestLog::verboseLevel() < 0) {
419 QTest::qt_snprintf(buf, sizeof(buf), "Totals: %d passed, %d failed, %d skipped\n",
420 QTestResult::passCount(), QTestResult::failCount(),
421 QTestResult::skipCount());
422 } else {
423 QTest::qt_snprintf(buf, sizeof(buf),
424 "Totals: %d passed, %d failed, %d skipped\n"
425 "********* Finished testing of %s *********\n",
426 QTestResult::passCount(), QTestResult::failCount(),
427 QTestResult::skipCount(), QTestResult::currentTestObjectName());
428 }
429 QTest::outputMessage(buf);
430
431 QAbstractTestLogger::stopLogging();
432}
433
434
435void QPlainTestLogger::enterTestFunction(const char * /*function*/)
436{
437 if (QTestLog::verboseLevel() >= 1)
438 QTest::printMessage(QTest::messageType2String(Info), "entering");
439}
440
441void QPlainTestLogger::leaveTestFunction()
442{
443}
444
445void QPlainTestLogger::addIncident(IncidentTypes type, const char *description,
446 const char *file, int line)
447{
448 // suppress PASS in silent mode
449 if (type == QAbstractTestLogger::Pass && QTestLog::verboseLevel() < 0)
450 return;
451
452 QTest::printMessage(QTest::incidentType2String(type), description, file, line);
453}
454
455void QPlainTestLogger::addBenchmarkResult(const QBenchmarkResult &result)
456{
457// QTest::printBenchmarkResult(QTest::benchmarkResult2String(), value, iterations);
458 QTest::printBenchmarkResult(result);
459}
460
461void QPlainTestLogger::addMessage(MessageTypes type, const char *message,
462 const char *file, int line)
463{
464 // suppress PASS in silent mode
465 if ((type == QAbstractTestLogger::Skip || type == QAbstractTestLogger::Info)
466 && QTestLog::verboseLevel() < 0)
467 return;
468
469 QTest::printMessage(QTest::messageType2String(type), message, file, line);
470}
471
472QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.