1 /****************************************************************************
3 ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtTest module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
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.
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.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
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"
57 #if defined(Q_OS_SYMBIAN)
62 #include <QtCore/QString>
65 #include <QtCore/QByteArray>
66 #include <QtCore/qmath.h>
72 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
74 static CRITICAL_SECTION outputCriticalSection
;
75 static HANDLE hConsole
= INVALID_HANDLE_VALUE
;
76 static WORD consoleAttributes
= 0;
78 static const char *qWinColoredMsg(int prefix
, int color
, const char *msg
)
83 WORD attr
= consoleAttributes
& ~(FOREGROUND_GREEN
| FOREGROUND_BLUE
84 | FOREGROUND_RED
| FOREGROUND_INTENSITY
);
86 attr
|= FOREGROUND_INTENSITY
;
88 attr
|= FOREGROUND_GREEN
;
90 attr
|= FOREGROUND_BLUE
| FOREGROUND_GREEN
;
92 attr
|= FOREGROUND_RED
| FOREGROUND_INTENSITY
;
94 attr
|= FOREGROUND_RED
| FOREGROUND_GREEN
| FOREGROUND_BLUE
;
96 attr
|= FOREGROUND_RED
| FOREGROUND_GREEN
;
97 SetConsoleTextAttribute(hConsole
, attr
);
99 SetConsoleTextAttribute(hConsole
, consoleAttributes
);
103 # define COLORED_MSG(prefix, color, msg) colored ? qWinColoredMsg(prefix, color, msg) : msg
105 # define COLORED_MSG(prefix, color, msg) colored && QAbstractTestLogger::isTtyOutput() ? "\033["#prefix";"#color"m" msg "\033[0m" : msg
108 static const char *incidentType2String(QAbstractTestLogger::IncidentTypes type
)
110 static bool colored
= (!qgetenv("QTEST_COLORED").isEmpty());
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
124 static const char *benchmarkResult2String()
126 static bool colored
= (!qgetenv("QTEST_COLORED").isEmpty());
127 return COLORED_MSG(0, 36, "RESULT "); // cyan
130 static const char *messageType2String(QAbstractTestLogger::MessageTypes type
)
133 static bool colored
= (!qgetenv("QTEST_COLORED").isEmpty());
135 static bool colored
= ::getenv("QTEST_COLORED");
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
156 static void outputMessage(const char *str
)
158 #if defined(Q_OS_WINCE)
159 QString strUtf16
= QString::fromLatin1(str
);
160 const int maxOutputLength
= 255;
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
);
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
);
186 // fast, no allocations, but truncates silently
187 RDebug::RawPrint(format
);
188 TPtrC8
ptr(reinterpret_cast<const TUint8
*>(str
));
189 RDebug::RawPrint(ptr
);
190 RDebug::RawPrint(_L8("\n"));
193 QAbstractTestLogger::outputString(str
);
196 static void printMessage(const char *type
, const char *msg
, const char *file
= 0, int line
= 0)
203 const char *fn
= QTestResult::currentTestFunction() ? QTestResult::currentTestFunction()
205 const char *tag
= QTestResult::currentDataTag() ? QTestResult::currentDataTag() : "";
206 const char *gtag
= QTestResult::currentGlobalDataTag()
207 ? QTestResult::currentGlobalDataTag()
209 const char *filler
= (tag
[0] && gtag
[0]) ? ":" : "";
211 QTest::qt_asprintf(&buf
, "%s: %s::%s(%s%s%s)%s%s\n"
213 "%s(%d) : failure location\n"
217 , type
, QTestResult::currentTestObjectName(), fn
, gtag
, filler
, tag
,
218 msg
[0] ? " " : "", msg
, file
, line
);
220 QTest::qt_asprintf(&buf
, "%s: %s::%s(%s%s%s)%s%s\n",
221 type
, QTestResult::currentTestObjectName(), fn
, gtag
, filler
, tag
,
222 msg
[0] ? " " : "", msg
);
224 // In colored mode, printf above stripped our nonprintable control characters.
226 memcpy(buf
.data(), type
, strlen(type
));
227 outputMessage(buf
.data());
230 template <typename T
>
231 static int countSignificantDigits(T num
)
239 while (num
/ divisor
>= 1) {
247 // Pretty-prints a benchmark result using the given number of digits.
248 template <typename T
> QString
formatResult(T number
, int significantDigits
)
251 return QLatin1String("NAN");
253 return QLatin1String("0");
255 QString beforeDecimalPoint
= QString::number(qint64(number
), 'f', 0);
256 QString afterDecimalPoint
= QString::number(number
, 'f', 20);
257 afterDecimalPoint
.remove(0, beforeDecimalPoint
.count() + 1);
259 int beforeUse
= qMin(beforeDecimalPoint
.count(), significantDigits
);
260 int beforeRemove
= beforeDecimalPoint
.count() - beforeUse
;
262 // Replace insignificant digits before the decimal point with zeros.
263 beforeDecimalPoint
.chop(beforeRemove
);
264 for (int i
= 0; i
< beforeRemove
; ++i
) {
265 beforeDecimalPoint
.append(QLatin1Char('0'));
268 int afterUse
= significantDigits
- beforeUse
;
270 // leading zeroes after the decimal point does not count towards the digit use.
271 if (beforeDecimalPoint
== QLatin1String("0") && afterDecimalPoint
.isEmpty() == false) {
275 while (i
< afterDecimalPoint
.count() && afterDecimalPoint
.at(i
) == QLatin1Char('0')) {
282 int afterRemove
= afterDecimalPoint
.count() - afterUse
;
283 afterDecimalPoint
.chop(afterRemove
);
285 QChar separator
= QLatin1Char(',');
286 QChar decimalPoint
= QLatin1Char('.');
288 // insert thousands separators
289 int length
= beforeDecimalPoint
.length();
290 for (int i
= beforeDecimalPoint
.length() -1; i
>= 1; --i
) {
291 if ((length
- i
) % 3 == 0)
292 beforeDecimalPoint
.insert(i
, separator
);
296 print
= beforeDecimalPoint
;
298 print
.append(decimalPoint
);
300 print
+= afterDecimalPoint
;
306 template <typename T
>
307 int formatResult(char * buffer
, int bufferSize
, T number
, int significantDigits
)
309 QString result
= formatResult(number
, significantDigits
);
310 qstrncpy(buffer
, result
.toAscii().constData(), bufferSize
);
311 int size
= result
.count();
315 // static void printBenchmarkResult(const char *bmtag, int value, int iterations)
316 static void printBenchmarkResult(const QBenchmarkResult
&result
)
318 const char *bmtag
= QTest::benchmarkResult2String();
322 buf1
, sizeof(buf1
), "%s: %s::%s",
324 QTestResult::currentTestObjectName(),
325 result
.context
.slotName
.toAscii().data());
330 QByteArray tag
= result
.context
.tag
.toAscii();
331 if (tag
.isEmpty() == false) {
332 QTest::qt_snprintf(bufTag
, sizeof(bufTag
), ":\"%s\"", tag
.data());
339 fillFormat
, sizeof(fillFormat
), ":\n%%%ds", fillLength
);
341 QTest::qt_snprintf(fill
, sizeof(fill
), fillFormat
, "");
344 QByteArray unitText
= QBenchmarkGlobalData::current
->measurer
->unitText().toAscii();
346 qreal valuePerIteration
= qreal(result
.value
) / qreal(result
.iterations
);
347 char resultBuffer
[100] = "";
348 formatResult(resultBuffer
, 100, valuePerIteration
, countSignificantDigits(result
.value
));
350 QByteArray iterationText
= "per iteration";
353 Q_ASSERT(result
.iterations
> 0);
355 buf2
, sizeof(buf2
), "%s %s %s",
358 iterationText
.data());
361 Q_ASSERT(result
.iterations
> 0);
363 buf3
, sizeof(buf3
), " (total: %s, iterations: %d)\n",
364 QByteArray::number(result
.value
).constData(), // no 64-bit qt_snprintf support
368 QTest::qt_snprintf(buf
, sizeof(buf
), "%s%s%s%s%s", buf1
, bufTag
, fill
, buf2
, buf3
);
369 memcpy(buf
, bmtag
, strlen(bmtag
));
374 QPlainTestLogger::QPlainTestLogger()
376 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
377 InitializeCriticalSection(&QTest::outputCriticalSection
);
378 QTest::hConsole
= GetStdHandle(STD_OUTPUT_HANDLE
);
379 if (QTest::hConsole
!= INVALID_HANDLE_VALUE
) {
380 CONSOLE_SCREEN_BUFFER_INFO info
;
381 if (GetConsoleScreenBufferInfo(QTest::hConsole
, &info
)) {
382 QTest::consoleAttributes
= info
.wAttributes
;
384 QTest::hConsole
= INVALID_HANDLE_VALUE
;
390 QPlainTestLogger::~QPlainTestLogger()
392 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
393 DeleteCriticalSection(&QTest::outputCriticalSection
);
397 void QPlainTestLogger::startLogging()
399 QAbstractTestLogger::startLogging();
402 if (QTestLog::verboseLevel() < 0) {
403 QTest::qt_snprintf(buf
, sizeof(buf
), "Testing %s\n",
404 QTestResult::currentTestObjectName());
406 QTest::qt_snprintf(buf
, sizeof(buf
),
407 "********* Start testing of %s *********\n"
408 "Config: Using QTest library " QTEST_VERSION_STR
409 ", Qt %s\n", QTestResult::currentTestObjectName(), qVersion());
411 QTest::outputMessage(buf
);
414 void QPlainTestLogger::stopLogging()
417 if (QTestLog::verboseLevel() < 0) {
418 QTest::qt_snprintf(buf
, sizeof(buf
), "Totals: %d passed, %d failed, %d skipped\n",
419 QTestResult::passCount(), QTestResult::failCount(),
420 QTestResult::skipCount());
422 QTest::qt_snprintf(buf
, sizeof(buf
),
423 "Totals: %d passed, %d failed, %d skipped\n"
424 "********* Finished testing of %s *********\n",
425 QTestResult::passCount(), QTestResult::failCount(),
426 QTestResult::skipCount(), QTestResult::currentTestObjectName());
428 QTest::outputMessage(buf
);
430 QAbstractTestLogger::stopLogging();
434 void QPlainTestLogger::enterTestFunction(const char * /*function*/)
436 if (QTestLog::verboseLevel() >= 1)
437 QTest::printMessage(QTest::messageType2String(Info
), "entering");
440 void QPlainTestLogger::leaveTestFunction()
444 void QPlainTestLogger::addIncident(IncidentTypes type
, const char *description
,
445 const char *file
, int line
)
447 // suppress PASS in silent mode
448 if (type
== QAbstractTestLogger::Pass
&& QTestLog::verboseLevel() < 0)
451 QTest::printMessage(QTest::incidentType2String(type
), description
, file
, line
);
454 void QPlainTestLogger::addBenchmarkResult(const QBenchmarkResult
&result
)
456 // QTest::printBenchmarkResult(QTest::benchmarkResult2String(), value, iterations);
457 QTest::printBenchmarkResult(result
);
460 void QPlainTestLogger::addMessage(MessageTypes type
, const char *message
,
461 const char *file
, int line
)
463 // suppress PASS in silent mode
464 if ((type
== QAbstractTestLogger::Skip
|| type
== QAbstractTestLogger::Info
)
465 && QTestLog::verboseLevel() < 0)
468 QTest::printMessage(QTest::messageType2String(type
), message
, file
, line
);