Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtestcase.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// Copyright (C) 2022 Intel Corporation.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4
5#include <QtTest/qtestcase.h>
6#include <QtTest/private/qtestcase_p.h>
7#include <QtTest/qtestassert.h>
8
9#include <QtCore/qbytearray.h>
10#include <QtCore/qcoreapplication.h>
11#include <QtCore/qdebug.h>
12#include <QtCore/qdir.h>
13#include <QtCore/qdirlisting.h>
14#if QT_CONFIG(future)
15#include <QtCore/qexception.h>
16#endif
17#include <QtCore/qfile.h>
18#include <QtCore/qfileinfo.h>
19#include <QtCore/qfloat16.h>
20#include <QtCore/qlibraryinfo.h>
21#include <QtCore/qlist.h>
22#include <QtCore/qmetaobject.h>
23#include <QtCore/qobject.h>
24#include <QtCore/qstringlist.h>
25#include <QtCore/qtemporarydir.h>
26#include <QtCore/qthread.h>
27#include <QtCore/qvarlengtharray.h>
28#include <QtCore/private/qlocking_p.h>
29#include <QtCore/private/qtools_p.h>
30#include <QtCore/private/qwaitcondition_p.h>
31
32#include <QtCore/qtestsupport_core.h>
33
34#include <QtTest/private/qtestlog_p.h>
35#include <QtTest/private/qtesttable_p.h>
36#include <QtTest/qtestdata.h>
37#include <QtTest/private/qtestresult_p.h>
38#include <QtTest/private/qsignaldumper_p.h>
39#include <QtTest/private/qbenchmark_p.h>
40#if QT_CONFIG(batch_test_support)
41#include <QtTest/private/qtestregistry_p.h>
42#endif // QT_CONFIG(batch_test_support)
43#include <QtTest/private/cycle_include_p.h>
44#include <QtTest/private/qtestblacklist_p.h>
45#include <QtTest/private/qtestcrashhandler_p.h>
46#if defined(HAVE_XCTEST)
47#include <QtTest/private/qxctestlogger_p.h>
48#endif
49#if defined Q_OS_MACOS
50#include <QtTest/private/qtestutil_macos_p.h>
51#endif
52
53#if defined(Q_OS_DARWIN)
54#include <QtTest/private/qappletestlogger_p.h>
55#endif
56
57#include <algorithm>
58#include <array>
59#if !defined(Q_OS_INTEGRITY) || __GHS_VERSION_NUMBER > 202014
60# include <charconv>
61#else
62// Broken implementation, causes link failures just by #include'ing!
63# undef __cpp_lib_to_chars // in case <version> was included
64#endif
65#include <chrono>
66#include <cmath>
67#include <cstdio>
68#include <exception>
69#include <limits>
70#include <memory>
71#include <mutex>
72#include <numeric>
73#include <optional>
74
75#include <stdarg.h>
76#include <stdlib.h>
77
78#if defined(Q_OS_LINUX)
79#include <sys/types.h>
80#include <fcntl.h>
81#endif
82
83#ifdef Q_OS_WIN
84# include <iostream>
85# if !defined(Q_CC_MINGW) || (defined(Q_CC_MINGW) && defined(__MINGW64_VERSION_MAJOR))
86# include <crtdbg.h>
87# endif
88#include <qt_windows.h> // for Sleep
89#endif
90#ifdef Q_OS_UNIX
91#include <QtCore/private/qcore_unix_p.h>
92
93#include <errno.h>
94#if __has_include(<paths.h>)
95# include <paths.h>
96#endif
97#include <time.h>
98#include <sys/mman.h>
99#include <sys/uio.h>
100#include <sys/wait.h>
101#include <unistd.h>
102# if !defined(Q_OS_INTEGRITY)
103# include <sys/resource.h>
104# endif
105#endif
106
107#if defined(Q_OS_MACOS)
108#include <IOKit/pwr_mgt/IOPMLib.h>
109#include <mach/task.h>
110#include <mach/mach_init.h>
111#include <CoreFoundation/CFPreferences.h>
112#endif
113
114#if defined(Q_OS_WASM)
115#include <emscripten.h>
116#endif
117
118#ifdef Q_OS_ANDROID
119#include <QtCore/QStandardPaths>
120#endif
121
122#include <vector>
123
124QT_BEGIN_NAMESPACE
125
126using namespace Qt::StringLiterals;
127
128using QtMiscUtils::toHexUpper;
129using QtMiscUtils::fromHex;
130
131static bool installCoverageTool(const char * appname, const char * testname)
132{
133#if defined(__COVERAGESCANNER__) && !QT_CONFIG(testlib_selfcover)
134 if (!qEnvironmentVariableIsEmpty("QT_TESTCOCOON_ACTIVE"))
135 return false;
136 // Set environment variable QT_TESTCOCOON_ACTIVE to prevent an eventual subtest from
137 // being considered as a stand-alone test regarding the coverage analysis.
138 qputenv("QT_TESTCOCOON_ACTIVE", "1");
139
140 // Install Coverage Tool
141 __coveragescanner_install(appname);
142 __coveragescanner_testname(testname);
143 __coveragescanner_clear();
144 return true;
145#else
146 Q_UNUSED(appname);
147 Q_UNUSED(testname);
148 return false;
149#endif
150}
151
152static bool isValidSlot(const QMetaMethod &sl)
153{
154 if (sl.access() != QMetaMethod::Private || sl.parameterCount() != 0
155 || sl.returnType() != QMetaType::Void || sl.methodType() != QMetaMethod::Slot)
156 return false;
157 const QByteArray name = sl.name();
158 return !(name.isEmpty() || name.endsWith("_data")
159 || name == "initTestCase" || name == "cleanupTestCase"
160 || name == "init" || name == "cleanup");
161}
162
163namespace QTestPrivate
164{
166}
167
168namespace {
169
170#if !QT_CONFIG(future)
171using QException = std::exception;
172#endif
173
174class TestFailedException : public QException // clazy:exclude=copyable-polymorphic
175{
176public:
177 TestFailedException() = default;
178 ~TestFailedException() override = default;
179
180 const char *what() const noexcept override { return "QtTest: test failed"; }
181
182#if QT_CONFIG(future)
183 TestFailedException *clone() const override { return new TestFailedException(); }
184 void raise() const override { throw TestFailedException(); }
185#endif
186};
187
188class TestSkippedException : public QException // clazy:exclude=copyable-polymorphic
189{
190public:
191 TestSkippedException() = default;
192 ~TestSkippedException() override = default;
193
194 const char *what() const noexcept override { return "QtTest: test was skipped"; }
195
196#if QT_CONFIG(future)
197 TestSkippedException *clone() const override { return new TestSkippedException(); }
198 void raise() const override { throw TestSkippedException(); }
199#endif
200};
201
202} // unnamed namespace
203
204namespace QTest
205{
206
209
210Q_CONSTINIT static QBasicAtomicInt g_throwOnFail = Q_BASIC_ATOMIC_INITIALIZER(0);
211Q_CONSTINIT static QBasicAtomicInt g_throwOnSkip = Q_BASIC_ATOMIC_INITIALIZER(0);
212
218
224
225/*
226//! [return-void]
227 Defining this macro is useful if you wish to use \1 in functions that have
228 a non-\c{void} return type. Without this macro defined, \2, for example,
229 expands to a statement including \c{return;}, so it cannot be used in
230 functions (or lambdas) that return something else than \c{void}, e.g.
231 \l{QString}. This includes the case where throwing exceptions is enabled
232 only at runtime (using \3). With this macro defined, \2 instead expands to
233 a statement without a \c{return;}, which is usable from any function.
234//! [return-void]
235*/
236
237/*!
238 \since 6.8
239 \macro QTEST_THROW_ON_FAIL
240 \relates QTest
241
242 When defined, QCOMPARE()/QVERIFY() etc always throw on failure.
243 QTest::setThrowOnFail() then no longer has any effect.
244
245 \include qtestcase.cpp {return-void} {QCOMPARE() or QVERIFY()} {QCOMPARE()} {QTest::setThrowOnFail(true)}
246*/
247
248/*!
249 \since 6.8
250 \macro QTEST_THROW_ON_SKIP
251 \relates QTest
252
253 When defined, QSKIP() always throws. QTest::setThrowOnSkip() then no longer
254 has any effect.
255
256 \include qtestcase.cpp {return-void} {QSKIP()} {QSKIP()} {QTest::setThrowOnSkip(true)}
257*/
258
259/*!
260 \since 6.8
261 \class QTest::ThrowOnFailEnabler
262 \inmodule QtTestLib
263
264 RAII class around setThrowOnFail().
265*/
266/*!
267 \fn QTest::ThrowOnFailEnabler::ThrowOnFailEnabler()
268
269 Constructor. Calls \c{setThrowOnFail(true)}.
270*/
271/*!
272 \fn QTest::ThrowOnFailEnabler::~ThrowOnFailEnabler()
273
274 Destructor. Calls \c{setThrowOnFail(false)}.
275*/
276
277/*!
278 \since 6.8
279 \class QTest::ThrowOnFailDisabler
280 \inmodule QtTestLib
281
282 RAII class around setThrowOnFail().
283*/
284/*!
285 \fn QTest::ThrowOnFailDisabler::ThrowOnFailDisabler()
286
287 Constructor. Calls \c{setThrowOnFail(false)}.
288*/
289/*!
290 \fn QTest::ThrowOnFailDisabler::~ThrowOnFailDisabler()
291
292 Destructor. Calls \c{setThrowOnFail(true)}.
293*/
294
295/*!
296 \since 6.8
297 \class QTest::ThrowOnSkipEnabler
298 \inmodule QtTestLib
299
300 RAII class around setThrowOnSkip().
301*/
302/*!
303 \fn QTest::ThrowOnSkipEnabler::ThrowOnSkipEnabler()
304
305 Constructor. Calls \c{setThrowOnSkip(true)}.
306*/
307/*!
308 \fn QTest::ThrowOnSkipEnabler::~ThrowOnSkipEnabler()
309
310 Destructor. Calls \c{setThrowOnSkip(false)}.
311*/
312
313/*!
314 \since 6.8
315 \class QTest::ThrowOnSkipDisabler
316 \inmodule QtTestLib
317
318 RAII class around setThrowOnSkip().
319*/
320/*!
321 \fn QTest::ThrowOnSkipDisabler::ThrowOnSkipDisabler()
322
323 Constructor. Calls \c{setThrowOnSkip(false)}.
324*/
325/*!
326 \fn QTest::ThrowOnSkipDisabler::~ThrowOnSkipDisabler()
327
328 Destructor. Calls \c{setThrowOnSkip(true)}.
329*/
330
331/*!
332 \since 6.8
333
334 Enables (\a enable = \c true) or disables (\ enable = \c false) throwing on
335 QCOMPARE()/QVERIFY() failures (as opposed to just returning from the
336 immediately-surrounding function context).
337
338 The feature is reference-counted: If you call this function \e{N} times
339 with \c{true}, you need to call it \e{N} times with \c{false} to get back
340 to where you started.
341
342 This call has no effect when the \l{QTEST_THROW_ON_FAIL} C++ macro is
343 defined.
344
345 \note You must compile your tests with exceptions enabled to use this
346 feature.
347
348 \sa setThrowOnSkip(), ThrowOnFailEnabler, ThrowOnFailDisabler, QTEST_THROW_ON_FAIL
349*/
350void setThrowOnFail(bool enable) noexcept
351{
352 g_throwOnFail.fetchAndAddRelaxed(enable ? 1 : -1);
353}
354
355/*!
356 \since 6.8
357
358 Enables (\a enable = \c true) or disables (\ enable = \c false) throwing on
359 QSKIP() (as opposed to just returning from the immediately-surrounding
360 function context).
361
362 The feature is reference-counted: If you call this function \e{N} times
363 with \c{true}, you need to call it \e{N} times with \c{false} to get back
364 to where you started.
365
366 This call has no effect when the \l{QTEST_THROW_ON_SKIP} C++ macro is
367 defined.
368
369 \note You must compile your tests with exceptions enabled to use this
370 feature.
371
372 \sa setThrowOnFail(), ThrowOnSkipEnabler, ThrowOnSkipDisabler, QTEST_THROW_ON_SKIP
373*/
374void setThrowOnSkip(bool enable) noexcept
375{
376 g_throwOnSkip.fetchAndAddRelaxed(enable ? 1 : -1);
377}
378
382{
383 return "QTestLib: This test case check (\"%1\") failed because the requested timeout (%2 ms) "
384 "was too short, %3 ms would have been sufficient this time."_L1
386}
387
389
390class WatchDog;
391
392static QObject *currentTestObject = nullptr;
394static bool inTestFunction = false;
395
396#if defined(Q_OS_MACOS)
399#endif
400
402public:
404
406
407 explicit TestMethods(const QObject *o, MetaMethods m = {});
408
409 void invokeTests(QObject *testObject) const;
410
411 static QMetaMethod findMethod(const QObject *obj, const char *signature);
412
413private:
414 void invokeTest(int index, QLatin1StringView tag, std::optional<WatchDog> &watchDog) const;
415 void invokeTestOnData(int index) const;
416
417 QMetaMethod m_initTestCaseMethod; // might not exist, check isValid().
418 QMetaMethod m_initTestCaseDataMethod;
419 QMetaMethod m_cleanupTestCaseMethod;
420 QMetaMethod m_initMethod;
421 QMetaMethod m_cleanupMethod;
422
423 MetaMethods m_methods;
424};
425
426TestMethods::TestMethods(const QObject *o, MetaMethods m)
427 : m_initTestCaseMethod(TestMethods::findMethod(o, "initTestCase()"))
428 , m_initTestCaseDataMethod(TestMethods::findMethod(o, "initTestCase_data()"))
429 , m_cleanupTestCaseMethod(TestMethods::findMethod(o, "cleanupTestCase()"))
430 , m_initMethod(TestMethods::findMethod(o, "init()"))
431 , m_cleanupMethod(TestMethods::findMethod(o, "cleanup()"))
432 , m_methods(std::move(m))
433{
434 if (m_methods.empty()) {
435 const QMetaObject *metaObject = o->metaObject();
436 const int count = metaObject->methodCount();
437 m_methods.reserve(count);
438 for (int i = 0; i < count; ++i) {
439 const QMetaMethod me = metaObject->method(i);
440 if (isValidSlot(me))
441 m_methods.push_back(me);
442 }
443 }
444}
445
446QMetaMethod TestMethods::findMethod(const QObject *obj, const char *signature)
447{
448 const QMetaObject *metaObject = obj->metaObject();
449 const int funcIndex = metaObject->indexOfMethod(signature);
450 return funcIndex >= 0 ? metaObject->method(funcIndex) : QMetaMethod();
451}
452
453static int keyDelay = -1;
454static int mouseDelay = -1;
455static int eventDelay = -1;
456#if QT_CONFIG(thread)
457static int timeout = -1;
458#endif
459static int repetitions = 1;
460static bool skipBlacklisted = false;
461
462namespace Internal {
463bool noCrashHandler = false;
464}
465
466static bool invokeTestMethodIfValid(QMetaMethod m, QObject *obj = QTest::currentTestObject)
467{
468 if (!m.isValid())
469 return false;
470 bool ok = true;
471 try { ok = m.invoke(obj, Qt ::DirectConnection); }
472 catch (const TestFailedException &) {} // ignore (used for control flow)
473 catch (const TestSkippedException &) {} // ditto
474 // every other exception is someone else's problem
475 return ok;
476}
477
478static void invokeTestMethodIfExists(const char *methodName, QObject *obj = QTest::currentTestObject)
479{
480 const QMetaObject *metaObject = obj->metaObject();
481 int funcIndex = metaObject->indexOfMethod(methodName);
482 // doesn't generate a warning if it doesn't exist:
483 invokeTestMethodIfValid(metaObject->method(funcIndex), obj);
484}
485
487{
488 if (eventDelay == -1) {
489 const QByteArray env = qgetenv("QTEST_EVENT_DELAY");
490 if (!env.isEmpty())
491 eventDelay = atoi(env.constData());
492 else
493 eventDelay = 0;
494 }
495 return eventDelay;
496}
497
498int Q_TESTLIB_EXPORT defaultMouseDelay()
499{
500 if (mouseDelay == -1) {
501 const QByteArray env = qgetenv("QTEST_MOUSEEVENT_DELAY");
502 if (!env.isEmpty())
504 else
506 }
507 return mouseDelay;
508}
509
510int Q_TESTLIB_EXPORT defaultKeyDelay()
511{
512 if (keyDelay == -1) {
513 const QByteArray env = qgetenv("QTEST_KEYEVENT_DELAY");
514 if (!env.isEmpty())
516 else
518 }
519 return keyDelay;
520}
521#if QT_CONFIG(thread)
523{
524 if (timeout == -1) {
525 bool ok = false;
526 timeout = qEnvironmentVariableIntValue("QTEST_FUNCTION_TIMEOUT", &ok);
527
528 if (!ok || timeout <= 0)
529 timeout = 5*60*1000;
530 }
531 return std::chrono::milliseconds{timeout};
532}
533#endif
534
536Q_TESTLIB_EXPORT QStringList testFunctions;
537Q_TESTLIB_EXPORT QStringList testTags;
538
539static bool qPrintTestSlots(FILE *stream, const char *filter = nullptr, const char *preamble = "")
540{
541 const auto matches = [filter](const QByteArray &s) {
542 return !filter || QLatin1StringView(s).contains(QLatin1StringView(filter),
543 Qt::CaseInsensitive);
544 };
545 bool matched = false;
546 for (int i = 0; i < QTest::currentTestObject->metaObject()->methodCount(); ++i) {
547 QMetaMethod sl = QTest::currentTestObject->metaObject()->method(i);
548 if (isValidSlot(sl)) {
549 const QByteArray signature = sl.methodSignature();
550 if (matches(signature)) {
551 std::fprintf(stream, "%s%s\n", preamble, signature.constData());
552 preamble = "";
553 matched = true;
554 }
555 }
556 }
557 return matched;
558}
559
560static void qPrintDataTags(FILE *stream)
561{
562 // Avoid invoking the actual test functions, and also avoid printing irrelevant output:
563 QTestLog::setPrintAvailableTagsMode();
564
565 // Get global data tags:
566 QTestTable::globalTestTable();
567 invokeTestMethodIfExists("initTestCase_data()");
568 const QTestTable *gTable = QTestTable::globalTestTable();
569
570 const QMetaObject *currTestMetaObj = QTest::currentTestObject->metaObject();
571
572 // Process test functions:
573 for (int i = 0; i < currTestMetaObj->methodCount(); ++i) {
574 QMetaMethod tf = currTestMetaObj->method(i);
575
576 if (isValidSlot(tf)) {
577
578 // Retrieve local tags:
579 QStringList localTags;
580 QTestTable table;
581 const QByteArray slot = tf.methodSignature().chopped(2);
582 const QByteArray member = slot + "_data()";
583 invokeTestMethodIfExists(member.constData());
584 const int dataCount = table.dataCount();
585 localTags.reserve(dataCount);
586 for (int j = 0; j < dataCount; ++j)
587 localTags << QLatin1StringView(table.testData(j)->dataTag());
588
589 // Print all tag combinations:
590 if (gTable->dataCount() == 0) {
591 if (localTags.size() == 0) {
592 // No tags at all, so just print the test function:
593 std::fprintf(stream, "%s %s\n", currTestMetaObj->className(), slot.data());
594 } else {
595 // Only local tags, so print each of them:
596 for (int k = 0; k < localTags.size(); ++k)
597 std::fprintf(stream, "%s %s %s\n",
598 currTestMetaObj->className(),
599 slot.data(),
600 localTags.at(k).toLatin1().data());
601 }
602 } else {
603 for (int j = 0; j < gTable->dataCount(); ++j) {
604 if (localTags.size() == 0) {
605 // Only global tags, so print the current one:
606 std::fprintf(stream, "%s %s __global__ %s\n",
607 currTestMetaObj->className(),
608 slot.data(),
609 gTable->testData(j)->dataTag());
610 } else {
611 // Local and global tags, so print each of the local ones and
612 // the current global one:
613 for (int k = 0; k < localTags.size(); ++k)
614 std::fprintf(stream, "%s %s %s __global__ %s\n",
615 currTestMetaObj->className(),
616 slot.data(),
617 localTags.at(k).toLatin1().data(),
618 gTable->testData(j)->dataTag());
619 }
620 }
621 }
622 }
623 }
624}
625
626static int qToInt(const char *str)
627{
628 char *pEnd;
629 int l = static_cast<int>(strtol(str, &pEnd, 10));
630 if (*pEnd != 0) {
631 std::fprintf(stderr, "Invalid numeric parameter: '%s'\n", str);
632 exit(1);
633 }
634 return l;
635}
636
637Q_TESTLIB_EXPORT void qtest_qParseArgs(int argc, const char *const argv[], bool qml)
638{
639 int logFormat = -1; // Not set
640 const char *logFilename = nullptr;
641
642 repetitions = 1;
643
644 QTest::testFunctions.clear();
645 QTest::testTags.clear();
646
647#if defined(Q_OS_DARWIN) && defined(HAVE_XCTEST)
648 if (QXcodeTestLogger::canLogTestProgress())
649 logFormat = QTestLog::XCTest;
650#endif
651
652 const char *testOptions =
653 " New-style logging options:\n"
654 " -o filename,format : Output results to file in the specified format\n"
655 " Use - to output to stdout\n"
656 " Valid formats are:\n"
657 " txt : Plain text\n"
658 " csv : CSV format (suitable for benchmarks)\n"
659 " junitxml : XML JUnit document\n"
660 " xml : XML document\n"
661 " lightxml : A stream of XML tags\n"
662 " teamcity : TeamCity format\n"
663 " tap : Test Anything Protocol\n"
664 "\n"
665 " *** Multiple loggers can be specified, but at most one can log to stdout.\n"
666 "\n"
667 " Old-style logging options:\n"
668 " -o filename : Write the output into file\n"
669 " -txt : Output results in Plain Text\n"
670 " -csv : Output results in a CSV format (suitable for benchmarks)\n"
671 " -junitxml : Output results as XML JUnit document\n"
672 " -xml : Output results as XML document\n"
673 " -lightxml : Output results as stream of XML tags\n"
674 " -teamcity : Output results in TeamCity format\n"
675 " -tap : Output results in Test Anything Protocol format\n"
676 "\n"
677 " *** If no output file is specified, stdout is assumed.\n"
678 " *** If no output format is specified, -txt is assumed.\n"
679 "\n"
680 " Test log detail options:\n"
681 " -silent : Log failures and fatal errors only\n"
682 " -v1 : Log the start of each testfunction\n"
683 " -v2 : Log each QVERIFY/QCOMPARE/QTEST (implies -v1)\n"
684 " -vs : Log every signal emission and resulting slot invocations\n"
685 "\n"
686 " *** The -silent and -v1 options only affect plain text output.\n"
687 "\n"
688 " Testing options:\n"
689 " -functions : Returns a list of current testfunctions\n"
690 " -datatags : Returns a list of current data tags.\n"
691 " A global data tag is preceded by ' __global__ '.\n"
692 " -eventdelay ms : Set default delay for mouse and keyboard simulation to ms milliseconds\n"
693 " -keydelay ms : Set default delay for keyboard simulation to ms milliseconds\n"
694 " -mousedelay ms : Set default delay for mouse simulation to ms milliseconds\n"
695 " -maxwarnings n : Sets the maximum amount of messages to output.\n"
696 " 0 means unlimited, default: 2000\n"
697 " -nocrashhandler : Disables the crash handler. Useful for debugging crashes.\n"
698 " -repeat n : Run the testsuite n times or until the test fails.\n"
699 " Useful for finding flaky tests. If negative, the tests are\n"
700 " repeated forever. This is intended as a developer tool, and\n"
701 " is only supported with the plain text logger.\n"
702 " -skipblacklisted : Skip blacklisted tests. Useful for measuring test coverage.\n"
703 " -trytimeout ms : Set default timeout for the QTRY_* macros and the qWaitFor()\n"
704 " functions to ms milliseconds.\n"
705 "\n"
706 " Benchmarking options:\n"
707#if QT_CONFIG(valgrind)
708 " -callgrind : Use callgrind to time benchmarks\n"
709#endif
710#ifdef QTESTLIB_USE_PERF_EVENTS
711 " -perf : Use Linux perf events to time benchmarks\n"
712 " -perfcounter name : Use the counter named 'name'\n"
713 " -perfcounterlist : Lists the counters available\n"
714#endif
715#ifdef HAVE_TICK_COUNTER
716 " -tickcounter : Use CPU tick counters to time benchmarks\n"
717#endif
718 " -eventcounter : Counts events received during benchmarks\n"
719 " -minimumvalue n : Sets the minimum acceptable measurement value\n"
720 " -minimumtotal n : Sets the minimum acceptable total for repeated executions of a test function\n"
721 " -iterations n : Sets the number of accumulation iterations.\n"
722 " -median n : Sets the number of median iterations.\n"
723 " -vb : Print out verbose benchmarking information.\n";
724
725 for (int i = 1; i < argc; ++i) {
726 if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0
727 || strcmp(argv[i], "/?") == 0) {
728 std::printf(" Usage: %s [options] [testfunction[:testdata]]...\n"
729 " By default, all testfunctions will be run.\n\n"
730 "%s", argv[0], testOptions);
731
732 if (qml) {
733 std::printf("\n"
734 " QmlTest options:\n"
735 " -import dir : Specify an import directory.\n"
736 " -plugins dir : Specify a directory where to search for plugins.\n"
737 " -input dir/file : Specify the root directory for test cases or a single test case file.\n"
738 " -translation file : Specify the translation file.\n"
739 " -file-selector dir : Specify a file selector for the QML engine.\n");
740 }
741
742 std::printf("\n"
743 " -help : This help\n");
744 exit(0);
745 } else if (strcmp(argv[i], "-functions") == 0) {
746 if (qml) {
748 } else {
749 qPrintTestSlots(stdout);
750 exit(0);
751 }
752 } else if (strcmp(argv[i], "-datatags") == 0) {
753 if (!qml) {
754 qPrintDataTags(stdout);
755 exit(0);
756 }
757 } else if (strcmp(argv[i], "-txt") == 0) {
758 logFormat = QTestLog::Plain;
759 } else if (strcmp(argv[i], "-csv") == 0) {
760 logFormat = QTestLog::CSV;
761 } else if (strcmp(argv[i], "-junitxml") == 0) {
762 logFormat = QTestLog::JUnitXML;
763 } else if (strcmp(argv[i], "-xunitxml") == 0) {
764 std::fprintf(stderr, "WARNING: xunitxml is deprecated. Please use junitxml.\n");
765 logFormat = QTestLog::JUnitXML;
766 } else if (strcmp(argv[i], "-xml") == 0) {
767 logFormat = QTestLog::XML;
768 } else if (strcmp(argv[i], "-lightxml") == 0) {
769 logFormat = QTestLog::LightXML;
770 } else if (strcmp(argv[i], "-teamcity") == 0) {
771 logFormat = QTestLog::TeamCity;
772 } else if (strcmp(argv[i], "-tap") == 0) {
773 logFormat = QTestLog::TAP;
774 } else if (strcmp(argv[i], "-silent") == 0) {
775 QTestLog::setVerboseLevel(-1);
776 } else if (strcmp(argv[i], "-v1") == 0) {
777 QTestLog::setVerboseLevel(1);
778 } else if (strcmp(argv[i], "-v2") == 0) {
779 QTestLog::setVerboseLevel(2);
780 } else if (strcmp(argv[i], "-vs") == 0) {
781 QSignalDumper::setEnabled(true);
782 } else if (strcmp(argv[i], "-o") == 0) {
783 if (i + 1 >= argc) {
784 std::fprintf(stderr, "-o needs an extra parameter specifying the filename and optional format\n");
785 exit(1);
786 }
787 ++i;
788 // Do we have the old or new style -o option?
789 char *filename = new char[strlen(argv[i])+1];
790 char *format = new char[strlen(argv[i])+1];
791 if (std::sscanf(argv[i], "%[^,],%s", filename, format) == 1) {
792 // Old-style
793 logFilename = argv[i];
794 } else {
795 // New-style
796 if (strcmp(format, "txt") == 0)
797 logFormat = QTestLog::Plain;
798 else if (strcmp(format, "csv") == 0)
799 logFormat = QTestLog::CSV;
800 else if (strcmp(format, "lightxml") == 0)
801 logFormat = QTestLog::LightXML;
802 else if (strcmp(format, "xml") == 0)
803 logFormat = QTestLog::XML;
804 else if (strcmp(format, "junitxml") == 0)
805 logFormat = QTestLog::JUnitXML;
806 else if (strcmp(format, "xunitxml") == 0) {
807 std::fprintf(stderr, "WARNING: xunitxml is deprecated. Please use junitxml.\n");
808 logFormat = QTestLog::JUnitXML;
809 } else if (strcmp(format, "teamcity") == 0)
810 logFormat = QTestLog::TeamCity;
811 else if (strcmp(format, "tap") == 0)
812 logFormat = QTestLog::TAP;
813 else {
814 std::fprintf(stderr, "output format must be one of txt, csv, lightxml, xml, tap, teamcity or junitxml\n");
815 exit(1);
816 }
817 if (strcmp(filename, "-") == 0 && QTestLog::loggerUsingStdout()) {
818 std::fprintf(stderr, "only one logger can log to stdout\n");
819 exit(1);
820 }
821 QTestLog::addLogger(QTestLog::LogMode(logFormat), filename);
822 }
823 delete [] filename;
824 delete [] format;
825 } else if (strcmp(argv[i], "-eventdelay") == 0) {
826 if (i + 1 >= argc) {
827 std::fprintf(stderr, "-eventdelay needs an extra parameter to indicate the delay(ms)\n");
828 exit(1);
829 } else {
830 QTest::eventDelay = qToInt(argv[++i]);
831 }
832 } else if (strcmp(argv[i], "-keydelay") == 0) {
833 if (i + 1 >= argc) {
834 std::fprintf(stderr, "-keydelay needs an extra parameter to indicate the delay(ms)\n");
835 exit(1);
836 } else {
837 QTest::keyDelay = qToInt(argv[++i]);
838 }
839 } else if (strcmp(argv[i], "-mousedelay") == 0) {
840 if (i + 1 >= argc) {
841 std::fprintf(stderr, "-mousedelay needs an extra parameter to indicate the delay(ms)\n");
842 exit(1);
843 } else {
844 QTest::mouseDelay = qToInt(argv[++i]);
845 }
846 } else if (strcmp(argv[i], "-maxwarnings") == 0) {
847 if (i + 1 >= argc) {
848 std::fprintf(stderr, "-maxwarnings needs an extra parameter with the amount of warnings\n");
849 exit(1);
850 } else {
851 QTestLog::setMaxWarnings(qToInt(argv[++i]));
852 }
853 } else if (strcmp(argv[i], "-repeat") == 0) {
854 if (i + 1 >= argc) {
855 std::fprintf(stderr, "-repeat needs an extra parameter for the number of repetitions\n");
856 exit(1);
857 } else {
858 repetitions = qToInt(argv[++i]);
859 }
860 } else if (strcmp(argv[i], "-nocrashhandler") == 0) {
862 } else if (strcmp(argv[i], "-skipblacklisted") == 0) {
864 } else if (strcmp(argv[i], "-trytimeout") == 0) {
865 if (i + 1 >= argc) {
866 std::fprintf(stderr, "-trytimeout needs an extra parameter to indicate the timeout(ms)\n");
867 exit(1);
868 } else {
869 QTest::defaultTryTimeout.store(std::chrono::milliseconds{qToInt(argv[++i])},
870 std::memory_order_relaxed);
871 }
872#if QT_CONFIG(valgrind)
873 } else if (strcmp(argv[i], "-callgrind") == 0) {
874 if (!QBenchmarkValgrindUtils::haveValgrind()) {
875 std::fprintf(stderr,
876 "WARNING: Valgrind not found or too old. "
877 "Make sure it is installed and in your path. "
878 "Using the walltime measurer.\n");
879 } else if (QFileInfo(QDir::currentPath()).isWritable()) {
880 QBenchmarkGlobalData::current->setMode(
881 QBenchmarkGlobalData::CallgrindParentProcess);
882 } else {
883 std::fprintf(stderr,
884 "WARNING: Current directory not writable. "
885 "Using the walltime measurer.\n");
886 }
887 } else if (strcmp(argv[i], "-callgrindchild") == 0) { // "private" option
888 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::CallgrindChildProcess);
889 QBenchmarkGlobalData::current->callgrindOutFileBase =
890 QBenchmarkValgrindUtils::outFileBase();
891#endif
892#ifdef QTESTLIB_USE_PERF_EVENTS
893 } else if (strcmp(argv[i], "-perf") == 0) {
894 if (QBenchmarkPerfEventsMeasurer::isAvailable()) {
895 // perf available
896 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::PerfCounter);
897 } else {
898 std::fprintf(stderr, "WARNING: Linux perf events not available. Using the walltime measurer.\n");
899 }
900 } else if (strcmp(argv[i], "-perfcounter") == 0) {
901 if (i + 1 >= argc) {
902 std::fprintf(stderr, "-perfcounter needs an extra parameter with the name of the counter\n");
903 exit(1);
904 } else {
905 QBenchmarkPerfEventsMeasurer::setCounter(argv[++i]);
906 }
907 } else if (strcmp(argv[i], "-perfcounterlist") == 0) {
908 QBenchmarkPerfEventsMeasurer::listCounters();
909 exit(0);
910#endif
911#ifdef HAVE_TICK_COUNTER
912 } else if (strcmp(argv[i], "-tickcounter") == 0) {
913 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::TickCounter);
914#endif
915 } else if (strcmp(argv[i], "-eventcounter") == 0) {
916 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::EventCounter);
917 } else if (strcmp(argv[i], "-minimumvalue") == 0) {
918 if (i + 1 >= argc) {
919 std::fprintf(stderr, "-minimumvalue needs an extra parameter to indicate the minimum time(ms)\n");
920 exit(1);
921 } else {
922 QBenchmarkGlobalData::current->walltimeMinimum = qToInt(argv[++i]);
923 }
924 } else if (strcmp(argv[i], "-minimumtotal") == 0) {
925 if (i + 1 >= argc) {
926 std::fprintf(stderr, "-minimumtotal needs an extra parameter to indicate the minimum total measurement\n");
927 exit(1);
928 } else {
929 QBenchmarkGlobalData::current->minimumTotal = qToInt(argv[++i]);
930 }
931 } else if (strcmp(argv[i], "-iterations") == 0) {
932 if (i + 1 >= argc) {
933 std::fprintf(stderr, "-iterations needs an extra parameter to indicate the number of iterations\n");
934 exit(1);
935 } else {
936 QBenchmarkGlobalData::current->iterationCount = qToInt(argv[++i]);
937 }
938 } else if (strcmp(argv[i], "-median") == 0) {
939 if (i + 1 >= argc) {
940 std::fprintf(stderr, "-median needs an extra parameter to indicate the number of median iterations\n");
941 exit(1);
942 } else {
943 QBenchmarkGlobalData::current->medianIterationCount = qToInt(argv[++i]);
944 }
945
946 } else if (strcmp(argv[i], "-vb") == 0) {
947 QBenchmarkGlobalData::current->verboseOutput = true;
948#if defined(Q_OS_DARWIN)
949 } else if (strncmp(argv[i], "-Apple", 6) == 0) {
950 i += 1; // Skip Apple-specific user preferences
951 continue;
952# if defined(HAVE_XCTEST)
953 } else if (int skip = QXcodeTestLogger::parseCommandLineArgument(argv[i])) {
954 i += (skip - 1); // Eating argv[i] with a continue counts towards skips
955 continue;
956# endif
957#endif
958 } else if (argv[i][0] == '-') {
959 std::fprintf(stderr, "Unknown option: '%s'\n\n%s", argv[i], testOptions);
960 if (qml) {
961 std::fprintf(stderr, "\nqmltest related options:\n"
962 " -import : Specify an import directory.\n"
963 " -plugins : Specify a directory where to search for plugins.\n"
964 " -input : Specify the root directory for test cases.\n");
965 }
966
967 std::fprintf(stderr, "\n"
968 " -help : This help\n");
969 exit(1);
970 } else {
971 // We can't check the availability of test functions until
972 // we load the QML files. So just store the data for now.
973 int colon = -1;
974 int offset;
975 for (offset = 0; argv[i][offset]; ++offset) {
976 if (argv[i][offset] == ':') {
977 if (argv[i][offset + 1] == ':') {
978 // "::" is used as a test name separator.
979 // e.g. "ClickTests::test_click:row1".
980 ++offset;
981 } else {
982 colon = offset;
983 break;
984 }
985 }
986 }
987 if (colon == -1) {
988 QTest::testFunctions += QString::fromLatin1(argv[i]);
989 QTest::testTags += QString();
990 } else {
991 QTest::testFunctions += QString::fromLatin1(argv[i], colon);
992 QTest::testTags += QString::fromLatin1(argv[i] + colon + 1);
993 }
994 }
995 }
996
997 bool installedTestCoverage = installCoverageTool(QTestResult::currentAppName(), QTestResult::currentTestObjectName());
998 QTestLog::setInstalledTestCoverage(installedTestCoverage);
999
1000 // If no loggers were created by the long version of the -o command-line
1001 // option, but a logger was requested via the old-style option, add it.
1002 const bool explicitLoggerRequested = logFormat != -1;
1003 if (!QTestLog::hasLoggers() && explicitLoggerRequested)
1004 QTestLog::addLogger(QTestLog::LogMode(logFormat), logFilename);
1005
1006 bool addFallbackLogger = !explicitLoggerRequested;
1007
1008#if defined(QT_USE_APPLE_UNIFIED_LOGGING)
1009 // Any explicitly requested loggers will be added by now, so we can check if they use stdout
1010 const bool safeToAddAppleLogger = !AppleUnifiedLogger::preventsStderrLogging() || !QTestLog::loggerUsingStdout();
1011 if (safeToAddAppleLogger && QAppleTestLogger::debugLoggingEnabled()) {
1012 QTestLog::addLogger(QTestLog::Apple, nullptr);
1013 if (AppleUnifiedLogger::preventsStderrLogging() && !logFilename)
1014 addFallbackLogger = false; // Prevent plain test logger fallback below
1015 }
1016#endif
1017
1018 if (addFallbackLogger)
1019 QTestLog::addLogger(QTestLog::Plain, logFilename);
1020
1021 if (repetitions != 1 && !QTestLog::isRepeatSupported()) {
1022 std::fprintf(stderr, "-repeat is only supported with plain text logger\n");
1023 exit(1);
1024 }
1025}
1026
1027// Temporary, backwards compatibility, until qtdeclarative's use of it is converted
1028Q_TESTLIB_EXPORT void qtest_qParseArgs(int argc, char *argv[], bool qml) {
1029 qtest_qParseArgs(argc, const_cast<const char *const *>(argv), qml);
1030}
1031
1032static QList<QBenchmarkResult> qMedian(const QList<QList<QBenchmarkResult>> &container)
1033{
1034 const int count = container.size();
1035 if (count == 0)
1036 return {};
1037
1038 if (count == 1)
1039 return container.front();
1040
1041 QList<QList<QBenchmarkResult>> containerCopy = container;
1042 std::sort(containerCopy.begin(), containerCopy.end(),
1043 [](const QList<QBenchmarkResult> &a, const QList<QBenchmarkResult> &b) {
1044 return a.first() < b.first();
1045 });
1046
1047 const int middle = count / 2;
1048
1049 // ### handle even-sized containers here by doing an arithmetic mean of the two middle items.
1050 return containerCopy.at(middle);
1051}
1052
1054{
1055 QTestDataSetter(QTestData *data)
1056 {
1057 QTestResult::setCurrentTestData(data);
1058 }
1060 {
1061 QTestResult::setCurrentTestData(nullptr);
1062 }
1063};
1064
1065void TestMethods::invokeTestOnData(int index) const
1066{
1067 /* Benchmarking: for each median iteration*/
1068
1069 bool isBenchmark = false;
1070 int i = (QBenchmarkGlobalData::current->measurer->needsWarmupIteration()) ? -1 : 0;
1071
1072 QList<QList<QBenchmarkResult>> resultsList;
1073 bool minimumTotalReached = false;
1074 do {
1075 QBenchmarkTestMethodData::current->beginDataRun();
1076 if (i < 0)
1077 QBenchmarkTestMethodData::current->iterationCount = 1;
1078
1079 /* Benchmarking: for each accumulation iteration*/
1080 bool invokeOk;
1081 do {
1082 QTest::inTestFunction = true;
1083 invokeTestMethodIfValid(m_initMethod);
1084
1085 const bool initQuit = QTest::currentTestResolved();
1086 if (!initQuit) {
1087 QBenchmarkTestMethodData::current->results.clear();
1088 QBenchmarkTestMethodData::current->resultAccepted = false;
1089 QBenchmarkTestMethodData::current->valid = false;
1090
1091 QBenchmarkGlobalData::current->context.tag = QLatin1StringView(
1092 QTestResult::currentDataTag() ? QTestResult::currentDataTag() : "");
1093
1094 invokeOk = invokeTestMethodIfValid(m_methods[index]);
1095 if (!invokeOk)
1096 QTestResult::addFailure("Unable to execute slot", __FILE__, __LINE__);
1097
1098 isBenchmark = QBenchmarkTestMethodData::current->isBenchmark();
1099 } else {
1100 invokeOk = false;
1101 }
1102
1103 QTest::inTestFunction = false;
1104 QTestResult::finishedCurrentTestData();
1105
1106 if (!initQuit) {
1107 invokeTestMethodIfValid(m_cleanupMethod);
1108
1109 // Process any deleteLater(), used by event-loop-based apps.
1110 // Fixes memleak reports.
1111 if (QCoreApplication::instance())
1112 QCoreApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
1113 }
1114 // If the test isn't a benchmark, finalize the result after
1115 // cleanup() has finished (or init has lead us to skip the test).
1116 if (!isBenchmark)
1117 QTestResult::finishedCurrentTestDataCleanup();
1118
1119 // If this test method has a benchmark, repeat until all measurements are
1120 // acceptable.
1121 // The QBENCHMARK macro increases the number of iterations for each run until
1122 // this happens.
1123 } while (invokeOk && !QTest::currentTestResolved() && isBenchmark
1124 && !QBenchmarkTestMethodData::current->resultsAccepted());
1125
1126 QBenchmarkTestMethodData::current->endDataRun();
1127 if (!QTest::currentTestResolved()) {
1128 if (i > -1) // iteration -1 is the warmup iteration.
1129 resultsList.append(QBenchmarkTestMethodData::current->results);
1130
1131 if (isBenchmark && QBenchmarkGlobalData::current->verboseOutput &&
1132 !QBenchmarkTestMethodData::current->results.isEmpty()) {
1133 // we only print the first result
1134 const QBenchmarkResult &first = QBenchmarkTestMethodData::current->results.constFirst();
1135 QString pattern = i < 0 ? "warmup stage result : %1 std.dev: %2"_L1
1136 : "accumulation stage result: %1 std.dev: %2"_L1;
1137 QTestLog::info(qPrintable(pattern.arg(first.measurement.value, 0,'f', 3)
1138 .arg(sqrt(first.measurement.variance), 0, 'e', 2)),
1139 nullptr, 0);
1140 }
1141 }
1142
1143 // Verify if the minimum total measurement (for the first measurement)
1144 // was reached, if it was specified:
1145 if (QBenchmarkGlobalData::current->minimumTotal == -1) {
1146 minimumTotalReached = true;
1147 } else {
1148 auto addResult = [](qreal current, const QList<QBenchmarkResult> &r) {
1149 if (!r.isEmpty())
1150 current += r.first().measurement.value;
1151 return current;
1152 };
1153 const qreal total = std::accumulate(resultsList.begin(), resultsList.end(), 0.0, addResult);
1154 minimumTotalReached = (total >= QBenchmarkGlobalData::current->minimumTotal);
1155 }
1156 } while (isBenchmark && !QTest::currentTestResolved()
1157 && (++i < QBenchmarkGlobalData::current->adjustMedianIterationCount()
1158 // Test that before this so i *does* get its increment:
1159 || !minimumTotalReached));
1160
1161 // If the test is a benchmark, finalize the result after all iterations have finished.
1162 if (isBenchmark) {
1163 bool testPassed = !QTest::currentTestResolved();
1164 QTestResult::finishedCurrentTestDataCleanup();
1165 // Only report benchmark figures if the test passed
1166 if (testPassed && QBenchmarkTestMethodData::current->resultsAccepted())
1167 QTestLog::addBenchmarkResults(qMedian(resultsList));
1168 }
1169}
1170
1171#if QT_CONFIG(thread)
1172
1173class WatchDog : public QThread
1174{
1175 enum Expectation : std::size_t {
1176 // bits 0..1: state
1180 ThreadEnd,
1181
1182 // bits 2..: generation
1183 };
1185 static_assert(size_t(ExpectationMask) == 0x3);
1186 static constexpr size_t GenerationShift = 2;
1187
1188 static constexpr Expectation state(Expectation e) noexcept
1189 { return Expectation{e & ExpectationMask}; }
1190 static constexpr size_t generation(Expectation e) noexcept
1191 { return e >> GenerationShift; }
1192 static constexpr Expectation combine(Expectation e, size_t gen) noexcept
1193 { return Expectation{e | (gen << GenerationShift)}; }
1194
1196 {
1197 auto expectationChanged = [this, e] { return expecting.load(std::memory_order_relaxed) != e; };
1198 switch (state(e)) {
1199 case TestFunctionEnd:
1201 case ThreadStart:
1202 case ThreadEnd:
1203 case TestFunctionStart:
1205 return true;
1206 }
1207 Q_UNREACHABLE_RETURN(false);
1208 }
1209
1211 {
1212 Q_ASSERT(generation(e) == 0); // no embedded generation allowed
1213 const auto locker = qt_scoped_lock(mutex);
1215 auto gen = generation(cur);
1216 if (e == TestFunctionStart)
1217 ++gen;
1218 e = combine(e, gen);
1221 }
1222
1223public:
1224 WatchDog()
1226 {
1227 setObjectName("QtTest Watchdog"_L1);
1228 auto locker = qt_unique_lock(mutex);
1229 start();
1231 }
1232
1233 ~WatchDog()
1234 {
1236 wait();
1237 }
1238
1239 void beginTest()
1240 {
1242 }
1243
1244 void testFinished()
1245 {
1247 }
1248
1249 void run() override
1250 {
1252 auto locker = qt_unique_lock(mutex);
1255 while (true) {
1257 switch (state(e)) {
1258 case ThreadEnd:
1259 return;
1260 case ThreadStart:
1261 Q_UNREACHABLE();
1262 case TestFunctionStart:
1263 case TestFunctionEnd:
1264 if (Q_UNLIKELY(!waitFor(locker, e))) {
1265 std::fflush(stderr);
1268 qFatal("Test function timed out");
1269 }
1270 }
1271 }
1272 }
1273
1274private:
1275 std::mutex mutex;
1278};
1279
1280#else // !QT_CONFIG(thread)
1281
1282class WatchDog : public QObject
1283{
1284public:
1285 void beginTest() {};
1286 void testFinished() {};
1287};
1288
1289#endif // QT_CONFIG(thread)
1290
1291template <typename Functor>
1292void runWithWatchdog(std::optional<WatchDog> &watchDog, Functor &&f)
1293{
1294 if (watchDog)
1295 watchDog->beginTest();
1296
1297 f();
1298
1299 if (watchDog)
1300 watchDog->testFinished();
1301}
1302
1303static void printUnknownDataTagError(QLatin1StringView name, QLatin1StringView tag,
1304 const QTestTable &lTable, const QTestTable &gTable)
1305{
1306 std::fprintf(stderr, "Unknown testdata for function %s(): '%s'\n", name.constData(), tag.data());
1307 const int localDataCount = lTable.dataCount();
1308 if (localDataCount) {
1309 std::fputs("Available test-specific data tags:\n", stderr);
1310 for (int i = 0; i < localDataCount; ++i)
1311 std::fprintf(stderr, "\t%s\n", lTable.testData(i)->dataTag());
1312 }
1313 const int globalDataCount = gTable.dataCount();
1314 if (globalDataCount) {
1315 std::fputs("Available global data tags:\n", stderr);
1316 for (int i = 0; i < globalDataCount; ++i)
1317 std::fprintf(stderr, "\t%s\n", gTable.testData(i)->dataTag());
1318 }
1319 if (localDataCount == 0 && globalDataCount == 0)
1320 std::fputs("Function has no data tags\n", stderr);
1321}
1322
1323/*!
1324 \internal
1325
1326 Call slot_data(), init(), slot(), cleanup(), init(), slot(), cleanup(), ...
1327 If data is set then it is the only test that is performed
1328*/
1329void TestMethods::invokeTest(int index, QLatin1StringView tag, std::optional<WatchDog> &watchDog) const
1330{
1331 QBenchmarkTestMethodData benchmarkData;
1332 QBenchmarkTestMethodData::current = &benchmarkData;
1333
1334 const QByteArray &name = m_methods[index].name();
1335 QBenchmarkGlobalData::current->context.slotName = QLatin1StringView(name) + "()"_L1;
1336
1337 char member[512];
1338 QTestTable table;
1339
1340 QTestResult::setCurrentTestFunction(name.constData());
1341
1342 const QTestTable *gTable = QTestTable::globalTestTable();
1343 const int globalDataCount = gTable->dataCount();
1344 int curGlobalDataIndex = 0;
1345 const auto globalDataTag = [gTable, globalDataCount](int index) {
1346 return globalDataCount ? gTable->testData(index)->dataTag() : nullptr;
1347 };
1348
1349 const auto dataTagMatches = [](QLatin1StringView tag, QLatin1StringView local,
1350 QLatin1StringView global) {
1351 if (tag.isEmpty()) // No tag specified => run all data sets for this function
1352 return true;
1353 if (tag == local || tag == global) // Equal to either => run it
1354 return true;
1355 // Also allow global:local as a match:
1356 return tag.startsWith(global) && tag.endsWith(local) &&
1357 tag.size() == global.size() + 1 + local.size() &&
1358 tag[global.size()] == ':';
1359 };
1360 bool foundFunction = false;
1361 bool blacklisted = false;
1362
1363 /* For each entry in the global data table, do: */
1364 do {
1365 if (!gTable->isEmpty())
1366 QTestResult::setCurrentGlobalTestData(gTable->testData(curGlobalDataIndex));
1367
1368 if (curGlobalDataIndex == 0) {
1369 std::snprintf(member, 512, "%s_data()", name.constData());
1370 runWithWatchdog(watchDog, [&member] {
1372 });
1373 if (QTestResult::skipCurrentTest())
1374 break;
1375 }
1376
1377 int curDataIndex = 0;
1378 const int dataCount = table.dataCount();
1379 const auto dataTag = [&table, dataCount](int index) {
1380 return dataCount ? table.testData(index)->dataTag() : nullptr;
1381 };
1382
1383 /* For each entry in this test's data table, do: */
1384 do {
1385 QTestResult::setSkipCurrentTest(false);
1386 QTestResult::setBlacklistCurrentTest(false);
1387 if (dataTagMatches(tag, QLatin1StringView(dataTag(curDataIndex)),
1388 QLatin1StringView(globalDataTag(curGlobalDataIndex)))) {
1389 foundFunction = true;
1390 blacklisted = QTestPrivate::checkBlackLists(name.constData(), dataTag(curDataIndex),
1391 globalDataTag(curGlobalDataIndex));
1392 if (blacklisted)
1393 QTestResult::setBlacklistCurrentTest(true);
1394
1395 if (blacklisted && skipBlacklisted) {
1396 QTest::qSkip("Skipping blacklisted test since -skipblacklisted option is set.",
1397 NULL, 0);
1398 QTestResult::finishedCurrentTestData();
1399 QTestResult::finishedCurrentTestDataCleanup();
1400 } else {
1402 curDataIndex >= dataCount ? nullptr : table.testData(curDataIndex));
1403
1404 QTestPrivate::qtestMouseButtons = Qt::NoButton;
1405
1406 // Maintain at least 500ms mouse event timestamps between each test function
1407 // call
1409
1410 runWithWatchdog(watchDog, [this, index] {
1411 invokeTestOnData(index);
1412 });
1413 }
1414
1415 if (!tag.isEmpty() && !globalDataCount)
1416 break;
1417 }
1418 ++curDataIndex;
1419 } while (curDataIndex < dataCount);
1420
1421 QTestResult::setCurrentGlobalTestData(nullptr);
1422 ++curGlobalDataIndex;
1423 } while (curGlobalDataIndex < globalDataCount);
1424
1425 if (!tag.isEmpty() && !foundFunction) {
1426 printUnknownDataTagError(QLatin1StringView(name), tag, table, *gTable);
1427 QTestResult::addFailure(qPrintable("Data tag not found: %1"_L1.arg(tag)));
1428 }
1429 QTestResult::finishedCurrentTestFunction();
1430 QTestResult::setSkipCurrentTest(false);
1431 QTestResult::setBlacklistCurrentTest(false);
1432}
1433
1434void *fetchData(QTestData *data, const char *tagName, int typeId)
1435{
1436 QTEST_ASSERT(typeId);
1437 QTEST_ASSERT_X(data, "QTest::fetchData()", "Test data requested, but no testdata available.");
1438 QTEST_ASSERT(data->parent());
1439
1440 int idx = data->parent()->indexOf(tagName);
1441
1442 if (Q_UNLIKELY(idx == -1 || idx >= data->dataCount())) {
1443 qFatal("QFETCH: Requested testdata '%s' not available, check your _data function.",
1444 tagName);
1445 }
1446
1447 if (Q_UNLIKELY(typeId != data->parent()->elementTypeId(idx))) {
1448 qFatal("Requested type '%s' does not match available type '%s'.",
1449 QMetaType(typeId).name(),
1450 QMetaType(data->parent()->elementTypeId(idx)).name());
1451 }
1452
1453 return data->data(idx);
1454}
1455
1456/*!
1457 * \internal
1458*/
1459char *formatString(const char *prefix, const char *suffix, size_t numArguments, ...)
1460{
1461 va_list ap;
1462 va_start(ap, numArguments);
1463
1464 QByteArray arguments;
1465 arguments += prefix;
1466
1467 if (numArguments > 0) {
1468 arguments += va_arg(ap, const char *);
1469
1470 for (size_t i = 1; i < numArguments; ++i) {
1471 arguments += ", ";
1472 arguments += va_arg(ap, const char *);
1473 }
1474 }
1475
1476 va_end(ap);
1477 arguments += suffix;
1478 return qstrdup(arguments.constData());
1479}
1480
1481/*!
1482 Returns a pointer to a string that is the string \a ba represented
1483 as a space-separated sequence of hex characters. If the input is
1484 considered too long, it is truncated. A trucation is indicated in
1485 the returned string as an ellipsis at the end. The caller has
1486 ownership of the returned pointer and must ensure it is later passed
1487 to operator delete[].
1488
1489 \a length is the length of the string \a ba.
1490*/
1491char *toHexRepresentation(const char *ba, qsizetype length)
1492{
1493 if (length == 0)
1494 return qstrdup("");
1495
1496 /* We output at maximum about maxLen characters in order to avoid
1497 * running out of memory and flooding things when the byte array
1498 * is large.
1499 *
1500 * maxLen can't be for example 200 because Qt Test is sprinkled with fixed
1501 * size char arrays.
1502 * */
1503 const qsizetype maxLen = 50;
1504 const qsizetype len = qMin(maxLen, length);
1505 char *result = nullptr;
1506
1507 if (length > maxLen) {
1508 const qsizetype size = len * 3 + 4;
1509 result = new char[size];
1510
1511 char *const forElipsis = result + size - 5;
1512 forElipsis[0] = ' ';
1513 forElipsis[1] = '.';
1514 forElipsis[2] = '.';
1515 forElipsis[3] = '.';
1516 result[size - 1] = '\0';
1517 }
1518 else {
1519 const qsizetype size = len * 3;
1520 result = new char[size];
1521 result[size - 1] = '\0';
1522 }
1523
1524 qsizetype i = 0;
1525 qsizetype o = 0;
1526
1527 while (true) {
1528 const char at = ba[i];
1529
1530 result[o] = toHexUpper(at >> 4);
1531 ++o;
1532 result[o] = toHexUpper(at);
1533
1534 ++i;
1535 ++o;
1536 if (i == len)
1537 break;
1538 result[o] = ' ';
1539 ++o;
1540 }
1541
1542 return result;
1543}
1544
1545/*!
1546 \internal
1547 Returns the same QByteArray but with only the ASCII characters still shown;
1548 everything else is replaced with \c {\xHH}.
1549*/
1550char *toPrettyCString(const char *p, qsizetype length)
1551{
1552 bool trimmed = false;
1553 auto buffer = std::make_unique<char[]>(256);
1554 const char *end = p + length;
1555 char *dst = buffer.get();
1556
1557 bool lastWasHexEscape = false;
1558 *dst++ = '"';
1559 for ( ; p != end; ++p) {
1560 // we can add:
1561 // 1 byte: a single character
1562 // 2 bytes: a simple escape sequence (\n)
1563 // 3 bytes: "" and a character
1564 // 4 bytes: an hex escape sequence (\xHH)
1565 if (dst - buffer.get() > 246) {
1566 // plus the quote, the three dots and NUL, it's 255 in the worst case
1567 trimmed = true;
1568 break;
1569 }
1570
1571 // check if we need to insert "" to break an hex escape sequence
1572 if (Q_UNLIKELY(lastWasHexEscape)) {
1573 if (fromHex(*p) != -1) {
1574 // yes, insert it
1575 *dst++ = '"';
1576 *dst++ = '"';
1577 }
1578 lastWasHexEscape = false;
1579 }
1580
1581 if (*p < 0x7f && *p >= 0x20 && *p != '\\' && *p != '"') {
1582 *dst++ = *p;
1583 continue;
1584 }
1585
1586 // write as an escape sequence
1587 // this means we may advance dst to buffer.data() + 247 or 250
1588 *dst++ = '\\';
1589 switch (*p) {
1590 case 0x5c:
1591 case 0x22:
1592 *dst++ = uchar(*p);
1593 break;
1594 case 0x8:
1595 *dst++ = 'b';
1596 break;
1597 case 0xc:
1598 *dst++ = 'f';
1599 break;
1600 case 0xa:
1601 *dst++ = 'n';
1602 break;
1603 case 0xd:
1604 *dst++ = 'r';
1605 break;
1606 case 0x9:
1607 *dst++ = 't';
1608 break;
1609 default:
1610 // print as hex escape
1611 *dst++ = 'x';
1612 *dst++ = toHexUpper(uchar(*p) >> 4);
1613 *dst++ = toHexUpper(uchar(*p));
1614 lastWasHexEscape = true;
1615 break;
1616 }
1617 }
1618
1619 *dst++ = '"';
1620 if (trimmed) {
1621 *dst++ = '.';
1622 *dst++ = '.';
1623 *dst++ = '.';
1624 }
1625 *dst++ = '\0';
1626 return buffer.release();
1627}
1628
1629/*!
1630 \fn char *toPrettyUnicode(QStringView string)
1631 \internal
1632 Returns the same QString but with only the ASCII characters still shown;
1633 everything else is replaced with \c {\uXXXX}.
1634
1635 Similar to QDebug::putString().
1636*/
1637
1639// escape sequence, closing quote, the three dots and NUL
1640constexpr qsizetype PrettyUnicodeMaxIncrement = sizeof(R"(\uXXXX"...)"); // includes NUL
1641
1642static char *writePrettyUnicodeChar(char16_t ch, char * const buffer)
1643{
1644 auto dst = buffer;
1645 auto first = [&](int n) { Q_ASSERT(dst - buffer == n); return dst; };
1646 if (ch < 0x7f && ch >= 0x20 && ch != '\\' && ch != '"') {
1647 *dst++ = ch;
1648 return first(1);
1649 }
1650
1651 // write as an escape sequence
1652 *dst++ = '\\';
1653 switch (ch) {
1654 case 0x22:
1655 case 0x5c:
1656 *dst++ = uchar(ch);
1657 break;
1658 case 0x8:
1659 *dst++ = 'b';
1660 break;
1661 case 0xc:
1662 *dst++ = 'f';
1663 break;
1664 case 0xa:
1665 *dst++ = 'n';
1666 break;
1667 case 0xd:
1668 *dst++ = 'r';
1669 break;
1670 case 0x9:
1671 *dst++ = 't';
1672 break;
1673 default:
1674 *dst++ = 'u';
1675 *dst++ = toHexUpper(ch >> 12);
1676 *dst++ = toHexUpper(ch >> 8);
1677 *dst++ = toHexUpper(ch >> 4);
1678 *dst++ = toHexUpper(ch);
1679 return first(6);
1680 }
1681 return first(2);
1682}
1683
1684char *toPrettyUnicode(QStringView string)
1685{
1686 auto p = string.utf16();
1687 auto length = string.size();
1688 // keep it simple for the vast majority of cases
1689 bool trimmed = false;
1690 auto buffer = std::make_unique<char[]>(PrettyUnicodeMaxOutputSize);
1691 const auto end = p + length;
1692 char *dst = buffer.get();
1693
1694 *dst++ = '"';
1695 for ( ; p != end; ++p) {
1696 if (dst - buffer.get() > PrettyUnicodeMaxOutputSize - PrettyUnicodeMaxIncrement) {
1697 trimmed = true;
1698 break;
1699 }
1700 dst = writePrettyUnicodeChar(*p, dst);
1701 }
1702
1703 *dst++ = '"';
1704 if (trimmed) {
1705 *dst++ = '.';
1706 *dst++ = '.';
1707 *dst++ = '.';
1708 }
1709 *dst++ = '\0';
1710 return buffer.release();
1711}
1712
1713void TestMethods::invokeTests(QObject *testObject) const
1714{
1715 const QMetaObject *metaObject = testObject->metaObject();
1716 QTEST_ASSERT(metaObject);
1717
1718 std::optional<WatchDog> watchDog = std::nullopt;
1719 if (!CrashHandler::alreadyDebugging()
1720#if QT_CONFIG(valgrind)
1721 && QBenchmarkGlobalData::current->mode() != QBenchmarkGlobalData::CallgrindChildProcess
1722#endif
1723 ) {
1724 watchDog.emplace();
1725 }
1726
1727 QTestResult::setCurrentTestFunction("initTestCase");
1728 runWithWatchdog(watchDog, [this, testObject] {
1729 invokeTestMethodIfValid(m_initTestCaseDataMethod, testObject);
1730 });
1731
1732 QSignalDumper::startDump();
1733
1734 if (!QTest::currentTestResolved()) {
1735
1736 runWithWatchdog(watchDog, [this, testObject] {
1737 invokeTestMethodIfValid(m_initTestCaseMethod, testObject);
1738 });
1739
1740 // finishedCurrentTestDataCleanup() resets QTestResult::currentTestFailed(), so use a local copy.
1741 const bool previousFailed = QTestResult::currentTestFailed();
1742 QTestResult::finishedCurrentTestData();
1743 QTestResult::finishedCurrentTestDataCleanup();
1744 QTestResult::finishedCurrentTestFunction();
1745
1746 if (!QTestResult::skipCurrentTest() && !previousFailed) {
1747 for (int i = 0, count = int(m_methods.size()); i < count; ++i) {
1748 const char *data = nullptr;
1749 if (i < QTest::testTags.size() && !QTest::testTags.at(i).isEmpty())
1750 data = qstrdup(QTest::testTags.at(i).toLatin1().constData());
1751 invokeTest(i, QLatin1StringView(data), watchDog);
1752 delete [] data;
1753 }
1754 }
1755
1756 const bool wasSkipped = QTestResult::skipCurrentTest();
1757 QTestResult::setSkipCurrentTest(false);
1758 QTestResult::setBlacklistCurrentTest(false);
1759 QTestResult::setCurrentTestFunction("cleanupTestCase");
1760 runWithWatchdog(watchDog, [this, testObject] {
1761 invokeTestMethodIfValid(m_cleanupTestCaseMethod, testObject);
1762 });
1763
1764 QTestResult::finishedCurrentTestData();
1765 // Restore skip state as it affects decision on whether we passed:
1766 QTestResult::setSkipCurrentTest(wasSkipped || QTestResult::skipCurrentTest());
1767 QTestResult::finishedCurrentTestDataCleanup();
1768 }
1769 QTestResult::finishedCurrentTestFunction();
1770 QTestResult::setCurrentTestFunction(nullptr);
1771
1772 QSignalDumper::endDump();
1773}
1774
1775#if QT_DEPRECATED_SINCE(6, 8)
1776static const char *functionRefFormatter(const void *f)
1777{
1778 auto formatter = static_cast<const qxp::function_ref<const char *()> *>(f);
1779 return (*formatter)();
1780};
1781
1782bool reportResult(bool success, qxp::function_ref<const char *()> lhs,
1783 qxp::function_ref<const char *()> rhs,
1784 const char *lhsExpr, const char *rhsExpr,
1785 ComparisonOperation op, const char *file, int line)
1786{
1789 lhsExpr, rhsExpr, op, file, line);
1790}
1791#endif // QT_DEPRECATED_SINCE(6, 8)
1792
1793bool reportResult(bool success, const void *lhs, const void *rhs,
1794 const char *(*lhsFormatter)(const void*),
1795 const char *(*rhsFormatter)(const void*),
1796 const char *lhsExpr, const char *rhsExpr,
1797 ComparisonOperation op, const char *file, int line)
1798{
1799 return QTestResult::reportResult(success, lhs, rhs, lhsFormatter, rhsFormatter,
1800 lhsExpr, rhsExpr, op, file, line);
1801}
1802
1803Q_CONSTINIT static std::terminate_handler oldTerminateHandler = nullptr;
1805{
1806 Q_CONSTINIT static std::atomic_flag terminationLatch = ATOMIC_FLAG_INIT;
1807 if (terminationLatch.test_and_set(std::memory_order_relaxed)) {
1808 // another thread has already reached the handler; let it terminate the
1809 // application
1810 qSleep(std::chrono::milliseconds::max());
1811 }
1812
1813 const char *reason = std::current_exception()
1814 ? "Caught unhandled exception" : "std::terminate() called";
1815 QTestResult::addFailure(reason, __FILE__, __LINE__);
1816 if (QTestResult::currentTestFunction()) {
1817 QTestResult::finishedCurrentTestFunction();
1818 QTestResult::setCurrentTestFunction(nullptr);
1819 }
1820
1821 // Run the old termination handler directly, not via std::terminate().
1822 // On some platforms, that runs this function again despite not being
1823 // the terminate handler any more.
1824 const std::terminate_handler next = oldTerminateHandler;
1825 qCleanup();
1826 next();
1827 std::abort(); // terminate handlers must not return
1828}
1829} // namespace QTest
1830
1831static void initEnvironment()
1832{
1833 qputenv("QT_QTESTLIB_RUNNING", "1");
1834}
1835
1836#ifdef Q_OS_ANDROID
1837static QFile androidExitCodeFile()
1838{
1839 const QString testHome = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
1840 return QFile(testHome + "/qtest_last_exit_code"_L1);
1841}
1842#endif
1843
1844/*!
1845 Executes tests declared in \a testObject. In addition, the private slots
1846 \c{initTestCase()}, \c{cleanupTestCase()}, \c{init()} and \c{cleanup()}
1847 are executed if they exist. See \l{Creating a Test} for more details.
1848
1849 Optionally, the command line arguments \a argc and \a argv can be provided.
1850 For a list of recognized arguments, read \l {Qt Test Command Line Arguments}.
1851
1852 The following example will run all tests in \c MyTestObject:
1853
1854 \snippet code/src_qtestlib_qtestcase.cpp 18
1855
1856 This function returns 0 if no tests failed, or a value other than 0 if one
1857 or more tests failed (skipped tests do not influence the return value). No
1858 exceptions are handled by this function: if a test throws, the process will
1859 terminate.
1860
1861 For stand-alone test applications, the convenience macro \l QTEST_MAIN() can
1862 be used to declare a main() function that parses the command line arguments
1863 and executes the tests, avoiding the need to call this function explicitly.
1864
1865 The return value from this function is also the exit code of the test
1866 application when the \l QTEST_MAIN() macro is used.
1867
1868 For stand-alone test applications, this function should not be called more
1869 than once, as command-line options for logging test output to files and
1870 executing individual test functions will not behave correctly.
1871
1872 \note This function is not reentrant, only one test can run at a time. A
1873 test that was executed with qExec() can't run another test via qExec() and
1874 threads are not allowed to call qExec() simultaneously.
1875
1876 If you have programmatically created the arguments, as opposed to getting them
1877 from the arguments in \c main(), it is likely of interest to use
1878 QTest::qExec(QObject *, const QStringList &) since it is Unicode safe.
1879
1880 \sa QTEST_MAIN(), QTEST_GUILESS_MAIN(), QTEST_APPLESS_MAIN()
1881*/
1882
1883int QTest::qExec(QObject *testObject, int argc, char **argv)
1884{
1885 // NB: QtQuick's testing recombines qInit(), qRun() and qCleanup() to
1886 // provide a replacement for qExec() that calls qRun() once for each
1887 // built-in style. So think twice about moving parts between these three
1888 // functions, as doing so may mess up QtQuick's testing.
1889 qInit(testObject, argc, argv);
1890 int ret = qRun();
1891 qCleanup();
1892
1893#if defined(Q_OS_WASM)
1894 EM_ASM({
1895 if (typeof Module != "undefined" && typeof Module.notifyTestFinished != "undefined")
1896 Module.notifyTestFinished($0);
1897 }, ret);
1898#endif // Q_OS_WASM
1899
1900 return ret;
1901}
1902
1903/*! \internal
1904*/
1905void QTest::qInit(QObject *testObject, int argc, char **argv)
1906{
1908 CrashHandler::maybeDisableCoreDump();
1909 QBenchmarkGlobalData::current = new QBenchmarkGlobalData;
1910
1911#if defined(Q_OS_MACOS)
1912 // Don't restore saved window state for auto tests
1913 QTestPrivate::disableWindowRestore();
1914
1915 // Disable App Nap which may cause tests to stall
1916 if (!appNapDisabler)
1917 appNapDisabler.emplace();
1918
1919 IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
1920 kIOPMAssertionLevelOn, CFSTR("QtTest running tests"),
1921 &macPowerSavingDisabled);
1922#endif
1923
1924 QTestPrivate::parseBlackList();
1925 QTestResult::reset();
1926
1927 QTEST_ASSERT(testObject);
1928 QTEST_ASSERT(!currentTestObject);
1929 currentTestObject = testObject;
1930
1931 const QMetaObject *metaObject = testObject->metaObject();
1932 QTEST_ASSERT(metaObject);
1933
1934 QTestResult::setCurrentTestObject(metaObject->className());
1935 if (argc > 0)
1936 QTestResult::setCurrentAppName(argv[0]);
1937
1938 qtest_qParseArgs(argc, argv, false);
1939
1940#if QT_CONFIG(valgrind)
1941 if (QBenchmarkGlobalData::current->mode() != QBenchmarkGlobalData::CallgrindParentProcess)
1942#endif
1943 QTestLog::startLogging();
1944
1945#ifdef Q_OS_ANDROID
1946 androidExitCodeFile().remove();
1947#endif
1948
1949 oldTerminateHandler = std::get_terminate();
1950 std::set_terminate(terminateHandler);
1951}
1952
1953/*! \internal
1954*/
1956{
1957 QTEST_ASSERT(currentTestObject);
1958
1959#if QT_CONFIG(valgrind)
1960 int callgrindChildExitCode = 0;
1961#endif
1962
1963#if defined(Q_OS_WIN) && !defined(QT_NO_EXCEPTIONS)
1964 // Our WindowsFaultHandler interferes with reporting uncaught exceptions
1965 try {
1966#endif
1967
1968#if QT_CONFIG(valgrind)
1969 if (QBenchmarkGlobalData::current->mode() == QBenchmarkGlobalData::CallgrindParentProcess) {
1970 if (Q_UNLIKELY(!qApp))
1971 qFatal("QtTest: -callgrind option is not available with QTEST_APPLESS_MAIN");
1972
1973 const QStringList origAppArgs(QCoreApplication::arguments());
1974 if (!QBenchmarkValgrindUtils::rerunThroughCallgrind(origAppArgs, callgrindChildExitCode))
1975 return -1;
1976
1977 QBenchmarkValgrindUtils::cleanup();
1978
1979 } else
1980#endif
1981 {
1982 std::optional<CrashHandler::FatalSignalHandler> handler;
1983 CrashHandler::prepareStackTrace();
1985 handler.emplace();
1986
1987 TestMethods::MetaMethods commandLineMethods;
1988 commandLineMethods.reserve(static_cast<size_t>(QTest::testFunctions.size()));
1989 std::vector<size_t> badFunctionIndices;
1990 size_t index = 0;
1991 for (const QString &tf : std::as_const(QTest::testFunctions)) {
1992 const QByteArray tfB = tf.toLatin1();
1993 const QByteArray signature = tfB + QByteArrayLiteral("()");
1994 QMetaMethod m = TestMethods::findMethod(currentTestObject, signature.constData());
1995 if (m.isValid() && isValidSlot(m)) {
1996 commandLineMethods.push_back(m);
1997 } else {
1998 std::fprintf(stderr, "Unknown test function: '%s'.", tfB.constData());
1999 if (!qPrintTestSlots(stderr, tfB.constData(), " Possible matches:\n"))
2000 std::fputc('\n', stderr);
2001 QTestResult::setCurrentTestFunction(tfB.constData());
2002 QTestResult::addFailure(qPrintable("Function not found: %1"_L1.arg(tf)));
2003 QTestResult::finishedCurrentTestFunction();
2004 // Record bad indices in reverse order to make removal easier:
2005 badFunctionIndices.insert(badFunctionIndices.begin(), index);
2006 }
2007 ++index;
2008 }
2009 if (badFunctionIndices.size() > 0) {
2010 // Provide relevant help to do better next time:
2011 std::fprintf(stderr, "\n%s -functions\nlists all available test functions.\n\n",
2012 QTestResult::currentAppName());
2013 if (commandLineMethods.empty()) // All requested functions missing.
2014 return 1;
2015
2016 // List is in decreasing order, so we delete later entries before
2017 // earlier, avoiding problems with entries after each deletion
2018 // changing index:
2019 for (size_t i : std::as_const(badFunctionIndices)) {
2020 // Purge the bogus entries from testFunctions and testTags. We
2021 // need to do this from testTags so that its indexing matches
2022 // commandLineMethods. Quick Test will be calling qRun() again
2023 // later, once for each style, so we need testFunctions to stay
2024 // in sync with testTags, so we don't attempt to remove the same
2025 // tag again on each repeat (QTBUG-143440).
2026 QTest::testFunctions.removeAt(i);
2027 QTest::testTags.removeAt(i);
2028 }
2029 }
2030 // If commandLineMethods is empty, constructor uses all available instead:
2031 TestMethods test(currentTestObject, std::move(commandLineMethods));
2032
2033 int remainingRepetitions = repetitions;
2034 const bool repeatForever = repetitions < 0;
2035 const int badArgCount = QTestLog::failCount(); // Stop if anything else fails.
2036 while (!(QTestLog::failCount() > badArgCount)
2037 && (repeatForever || remainingRepetitions-- > 0)) {
2038 QTestTable::globalTestTable();
2039 test.invokeTests(currentTestObject);
2040 QTestTable::clearGlobalTestTable();
2041 }
2042 }
2043
2044#if defined(Q_OS_WIN) && !defined(QT_NO_EXCEPTIONS)
2045 } catch (...) {
2046 QTestResult::addFailure("Caught unhandled exception", __FILE__, __LINE__);
2047 if (QTestResult::currentTestFunction()) {
2048 QTestResult::finishedCurrentTestFunction();
2049 QTestResult::setCurrentTestFunction(nullptr);
2050 }
2051
2052 qCleanup();
2053
2054 // Re-throw exception to make debugging easier
2055 throw;
2056 return 1;
2057 }
2058#endif
2059
2060#if QT_CONFIG(valgrind)
2061 if (QBenchmarkGlobalData::current->mode() == QBenchmarkGlobalData::CallgrindParentProcess)
2062 return callgrindChildExitCode;
2063#endif
2064 // make sure our exit code is never going above 127
2065 // since that could wrap and indicate 0 test fails
2066 const int exitCode = qMin(QTestLog::failCount(), 127);
2067
2068#ifdef Q_OS_ANDROID
2069 QFile exitCodeFile = androidExitCodeFile();
2070 if (exitCodeFile.open(QIODevice::WriteOnly)) {
2071 exitCodeFile.write(qPrintable(QString::number(exitCode)));
2072 } else {
2073 qWarning("Failed to open %s for writing test exit code: %s",
2074 qPrintable(exitCodeFile.fileName()), qPrintable(exitCodeFile.errorString()));
2075 }
2076#endif
2077
2078 return exitCode;
2079}
2080
2081/*! \internal
2082*/
2084{
2085 if (std::get_terminate() == terminateHandler)
2086 std::set_terminate(oldTerminateHandler);
2087 oldTerminateHandler = nullptr;
2088 currentTestObject = nullptr;
2089
2090#if QT_CONFIG(valgrind)
2091 if (QBenchmarkGlobalData::current->mode() != QBenchmarkGlobalData::CallgrindParentProcess)
2092#endif
2093 QTestLog::stopLogging();
2094
2095 delete QBenchmarkGlobalData::current;
2096 QBenchmarkGlobalData::current = nullptr;
2097
2098#if defined(Q_OS_MACOS)
2099 IOPMAssertionRelease(macPowerSavingDisabled);
2100 appNapDisabler = std::nullopt;
2101#endif
2102}
2103
2104#if QT_CONFIG(batch_test_support) || defined(Q_QDOC)
2105/*!
2106 Registers the test \a name, with entry function \a entryFunction, in a
2107 central test case registry for the current binary.
2108
2109 The \a name will be listed when running the batch test binary with no
2110 parameters. Running the test binary with the argv[1] of \a name will result
2111 in \a entryFunction being called.
2112
2113 \since 6.5
2114*/
2115void QTest::qRegisterTestCase(const QString &name, TestEntryFunction entryFunction)
2116{
2117 QTest::TestRegistry::instance()->registerTest(name, entryFunction);
2118}
2119
2120QList<QString> QTest::qGetTestCaseNames()
2121{
2122 return QTest::TestRegistry::instance()->getAllTestNames();
2123}
2124
2125QTest::TestEntryFunction QTest::qGetTestCaseEntryFunction(const QString& name)
2126{
2127 return QTest::TestRegistry::instance()->getTestEntryFunction(name);
2128}
2129
2130#endif // QT_CONFIG(batch_test_support)
2131
2132/*!
2133 \overload
2134 \since 4.4
2135
2136 Behaves identically to qExec(QObject *, int, char**) but takes a
2137 QStringList of \a arguments instead of a \c char** list.
2138*/
2139int QTest::qExec(QObject *testObject, const QStringList &arguments)
2140{
2141 const int argc = arguments.size();
2142 QVarLengthArray<char *> argv(argc);
2143
2144 QList<QByteArray> args;
2145 args.reserve(argc);
2146
2147 for (int i = 0; i < argc; ++i)
2148 {
2149 args.append(arguments.at(i).toLocal8Bit().constData());
2150 argv[i] = args.last().data();
2151 }
2152
2153 return qExec(testObject, argc, argv.data());
2154}
2155
2156/*! \internal
2157*/
2158void QTest::qFail(const char *message, const char *file, int line)
2159{
2160 QTestResult::fail(message, file, line);
2161}
2162
2163/*! \internal
2164*/
2165bool QTest::qVerify(bool statement, const char *statementStr, const char *description,
2166 const char *file, int line)
2167{
2168 return QTestResult::verify(statement, statementStr, description, file, line);
2169}
2170
2171/*! \fn void QTest::qSkip(const char *message, const char *file, int line)
2172 \internal
2173*/
2174void QTest::qSkip(const char *message, const char *file, int line)
2175{
2176 QTestResult::addSkip(message, file, line);
2177 QTestResult::setSkipCurrentTest(true);
2178}
2179
2180/*! \fn bool QTest::qExpectFail(const char *dataIndex, const char *comment, TestFailMode mode, const char *file, int line)
2181 \internal
2182*/
2183bool QTest::qExpectFail(const char *dataIndex, const char *comment,
2184 QTest::TestFailMode mode, const char *file, int line)
2185{
2186 return QTestResult::expectFail(dataIndex, qstrdup(comment), mode, file, line);
2187}
2188
2189/*!
2190 \internal
2191
2192 Executes qFail() following a failed QVERIFY_THROWS_EXCEPTION or
2193 QVERIFY_THROWS_NO_EXCEPTION, passing a suitable message created from \a expected,
2194 \a what, along with \a file and \a line.
2195
2196 The \a expected parameter contains the type of the exception that is expected to
2197 be thrown, or \nullptr, if no exception was expected.
2198
2199 The \a what parameter contains the result of \c{std::exception::what()}, or nullptr,
2200 if a non-\c{std::exception}-derived exception was caught.
2201
2202 The \a file and \a line parameters hold expansions of the \c{__FILE__} and \c{__LINE__}
2203 macros, respectively.
2204*/
2205void QTest::qCaught(const char *expected, const char *what, const char *file, int line)
2206{
2207 auto message = [&] {
2208 const auto exType = what ? "std::" : "unknown ";
2209 const auto ofType = expected ? " of type " : "";
2210 const auto no = expected ? "an" : "no";
2211 const auto withMsg = what ? " with message " : "";
2212 const auto protect = [](const char *s) { return s ? s : ""; };
2213
2214 return QString::asprintf("Expected %s exception%s%s to be thrown, "
2215 "but caught %sexception%s%s",
2216 no, ofType, protect(expected),
2217 exType, withMsg, protect(what));
2218 };
2219 qFail(message().toUtf8().constData(), file, line);
2220}
2221
2222/*!
2223 \internal
2224
2225 Contains the implementation of the catch(...) block of
2226 QVERIFY_THROWS_EXCEPTION.
2227
2228 The function inspects std::current_exception() by rethrowing it using
2229 std::rethrow_exception().
2230
2231 The function must be called from a catch handler.
2232
2233 If the exception inherits std::exception, its what() message is logged and
2234 this function returns normally. The caller of this function must then
2235 execute a \c{QTEST_FAIL_ACTION} to exit from the test function.
2236
2237 Otherwise, a message saying an unknown exception was caught is logged and
2238 this function rethrows the exception, skipping the \c{QTEST_FAIL_ACTION}
2239 that follows this function call in the caller.
2240*/
2241void QTest::qCaught(const char *expected, const char *file, int line)
2242{
2243 try {
2244 // let's see what the cat brought us:
2245 std::rethrow_exception(std::current_exception());
2246 } catch (const std::exception &e) {
2247 qCaught(expected, e.what(), file, line);
2248 } catch (...) {
2249 qCaught(expected, nullptr, file, line);
2250 throw;
2251 }
2252 // caller shall invoke `QTEST_FAIL_ACTION` if control reached here
2253}
2254
2255
2256#if QT_DEPRECATED_SINCE(6, 3)
2257/*!
2258 \internal
2259 \deprecated [6.3] Use qWarning() instead.
2260*/
2261void QTest::qWarn(const char *message, const char *file, int line)
2262{
2263 QTestLog::warn(message, file, line);
2264}
2265#endif
2266
2267/*!
2268 Ignores messages created by qDebug(), qInfo() or qWarning(). If the \a message
2269 with the corresponding \a type is outputted, it will be removed from the
2270 test log. If the test finished and the \a message was not outputted,
2271 a test failure is appended to the test log.
2272
2273 \note Invoking this function will only ignore one message. If the message
2274 you want to ignore is output twice, you have to call ignoreMessage() twice,
2275 too.
2276
2277 Example:
2278 \snippet code/src_qtestlib_qtestcase.cpp 19
2279
2280 The example above tests that QDir::mkdir() outputs the right warning when invoked
2281 with an invalid file name.
2282
2283 \note \a message will be interpreted as UTF-8.
2284*/
2285void QTest::ignoreMessage(QtMsgType type, const char *message)
2286{
2287 QTestLog::ignoreMessage(type, message);
2288}
2289
2290#if QT_CONFIG(regularexpression)
2291/*!
2292 \overload
2293
2294 Ignores messages created by qDebug(), qInfo() or qWarning(). If the message
2295 matching \a messagePattern
2296 with the corresponding \a type is outputted, it will be removed from the
2297 test log. If the test finished and the message was not outputted,
2298 a test failure is appended to the test log.
2299
2300 \note Invoking this function will only ignore one message. If the message
2301 you want to ignore is output twice, you have to call ignoreMessage() twice,
2302 too.
2303
2304 \since 5.3
2305*/
2306void QTest::ignoreMessage(QtMsgType type, const QRegularExpression &messagePattern)
2307{
2308 QTestLog::ignoreMessage(type, messagePattern);
2309}
2310#endif // QT_CONFIG(regularexpression)
2311
2312/*!
2313 \since 6.8
2314 \overload failOnWarning()
2316 Appends a test failure to the test log if any warning is output.
2317
2318 \sa failOnWarning(const char *)
2319*/
2321{
2322 return QTestLog::failOnWarning();
2323}
2324
2325/*!
2326 \since 6.3
2327 \overload failOnWarning()
2329 Appends a test failure to the test log if the \a message is output.
2330
2331 \sa failOnWarning()
2332*/
2333void QTest::failOnWarning(const char *message)
2334{
2335 return QTestLog::failOnWarning(message);
2336}
2337
2338#if QT_CONFIG(regularexpression)
2339/*!
2340 \since 6.3
2341
2342 Appends a test failure to the test log for each warning that matches
2343 \a messagePattern.
2344
2345 The test function will continue execution when a failure is added. To abort
2346 the test instead, you can check \l currentTestFailed() and return early if
2347 it's \c true.
2348
2349 For each warning, the first pattern that matches will cause a failure,
2350 and the remaining patterns will be ignored.
2351
2352 All patterns are cleared at the end of each test function.
2353
2354 \code
2355 void FileTest::loadFiles()
2356 {
2357 QTest::failOnWarning(QRegularExpression("^Failed to load"));
2358
2359 // Each of these will cause a test failure:
2360 qWarning() << "Failed to load image";
2361 qWarning() << "Failed to load video";
2362 }
2363 \endcode
2364
2365 To fail every test that triggers a given warning, pass a suitable regular
2366 expression to this function in \l {Creating a Test}{init()}:
2367
2368 \code
2369 void FileTest::init()
2370 {
2371 QTest::failOnWarning(
2372 QRegularExpression("QFile::.*: File(.*) already open"));
2373 }
2374 \endcode
2375
2376 For the common case of failing on \e any warning pass no parameter:
2377
2378 \code
2379 void FileTest::init()
2380 {
2381 QTest::failOnWarning();
2382 }
2383 \endcode
2384
2385 \note \l ignoreMessage() takes precedence over this function, so any
2386 warnings that match a pattern given to both \c ignoreMessage() and
2387 \c failOnWarning() will be ignored.
2388
2389 \sa {Qt Test Environment Variables}{QTEST_FATAL_FAIL}
2390*/
2391void QTest::failOnWarning(const QRegularExpression &messagePattern)
2392{
2393 QTestLog::failOnWarning(messagePattern);
2394}
2395#endif // QT_CONFIG(regularexpression)
2396
2397/*! \internal
2398*/
2399
2400#ifdef Q_OS_WIN
2401static inline bool isWindowsBuildDirectory(const QString &dirName)
2402{
2403 return dirName.compare("Debug"_L1, Qt::CaseInsensitive) == 0
2404 || dirName.compare("Release"_L1, Qt::CaseInsensitive) == 0;
2405}
2406#endif
2407
2408#if QT_CONFIG(temporaryfile)
2409/*!
2410 Extracts a directory from resources to disk. The content is extracted
2411 recursively to a temporary folder. The extracted content is removed
2412 automatically once the last reference to the return value goes out of scope.
2413
2414 \a dirName is the name of the directory to extract from resources.
2415
2416 Returns the temporary directory where the data was extracted or null in case of
2417 errors.
2418*/
2419QSharedPointer<QTemporaryDir> QTest::qExtractTestData(const QString &dirName)
2420{
2421 QSharedPointer<QTemporaryDir> result; // null until success, then == tempDir
2422
2423 QSharedPointer<QTemporaryDir> tempDir = QSharedPointer<QTemporaryDir>::create();
2424
2425 tempDir->setAutoRemove(true);
2426
2427 if (!tempDir->isValid())
2428 return result;
2429
2430 const QString dataPath = tempDir->path();
2431 const QString resourcePath = u':' + dirName;
2432 const QFileInfo fileInfo(resourcePath);
2433
2434 if (!fileInfo.isDir()) {
2435 qWarning("Resource path '%s' is not a directory.", qPrintable(resourcePath));
2436 return result;
2437 }
2438
2439 bool isResourceDirEmpty = true;
2440 for (const auto &dirEntry : QDirListing(resourcePath, QDirListing::IteratorFlag::Recursive)) {
2441 isResourceDirEmpty = false;
2442 if (!dirEntry.isDir()) {
2443 const QString &filePath = dirEntry.filePath();
2444 const QString destination =
2445 dataPath + u'/' + QStringView{filePath}.sliced(resourcePath.size());
2446 QFileInfo destinationFileInfo(destination);
2447 QDir().mkpath(destinationFileInfo.path());
2448 QFile file(filePath);
2449 if (!file.copy(destination, QFile::ReadUser | QFile::WriteUser | QFile::ReadGroup)) {
2450 qWarning("Failed to copy '%ls': %ls.", qUtf16Printable(filePath),
2451 qUtf16Printable(file.errorString()));
2452 return result;
2453 }
2454 }
2455 }
2456
2457 if (isResourceDirEmpty) {
2458 qWarning("Resource directory '%s' is empty.", qPrintable(resourcePath));
2459 return result;
2460 }
2461
2462 result = std::move(tempDir);
2463
2464 return result;
2465}
2466#endif // QT_CONFIG(temporaryfile)
2467
2468/*! \internal
2469*/
2470
2471QString QTest::qFindTestData(const QString& base, const char *file, int line, const char *builddir,
2472 const char *sourcedir)
2473{
2474 QString found;
2475
2476 // Testdata priorities:
2477
2478 // 1. relative to test binary.
2479 if (qApp) {
2480 QDir binDirectory(QCoreApplication::applicationDirPath());
2481 if (binDirectory.exists(base)) {
2482 found = binDirectory.absoluteFilePath(base);
2483 }
2484#ifdef Q_OS_WIN
2485 // Windows: The executable is typically located in one of the
2486 // 'Release' or 'Debug' directories.
2487 else if (isWindowsBuildDirectory(binDirectory.dirName())
2488 && binDirectory.cdUp() && binDirectory.exists(base)) {
2489 found = binDirectory.absoluteFilePath(base);
2490 }
2491#endif // Q_OS_WIN
2492 else if (QTestLog::verboseLevel() >= 2) {
2493 const QString candidate = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + u'/' + base);
2494 QTestLog::info(qPrintable("testdata %1 not found relative to test binary [%2]; "
2495 "checking next location"_L1.arg(base, candidate)),
2496 file, line);
2497 }
2498 }
2499
2500 // 2. installed path.
2501 if (found.isEmpty()) {
2502 const char *testObjectName = QTestResult::currentTestObjectName();
2503 if (testObjectName) {
2504 const QStringList testsPaths = QLibraryInfo::paths(QLibraryInfo::TestsPath);
2505 for (const QString &testsPath : testsPaths) {
2506 const QString candidate = "%1/%2/%3"_L1
2507 .arg(testsPath, QFile::decodeName(testObjectName).toLower(), base);
2508 if (QFileInfo::exists(candidate)) {
2509 found = candidate;
2510 } else if (QTestLog::verboseLevel() >= 2) {
2511 QTestLog::info(qPrintable("testdata %1 not found in tests install path [%2]; "
2512 "checking next location"_L1
2513 .arg(base, QDir::toNativeSeparators(candidate))),
2514 file, line);
2515 }
2516 }
2517 }
2518 }
2519
2520 // 3. relative to test source.
2521 if (found.isEmpty() && qstrncmp(file, ":/", 2) != 0) {
2522 // srcdir is the directory containing the calling source file.
2523 QFileInfo srcdir(QFileInfo(QFile::decodeName(file)).path());
2524
2525 // If the srcdir is relative, that means it is relative to the current working
2526 // directory of the compiler at compile time, which should be passed in as `builddir'.
2527 if (!srcdir.isAbsolute() && builddir)
2528 srcdir.setFile(QFile::decodeName(builddir) + u'/' + srcdir.filePath());
2529
2530 const QString canonicalPath = srcdir.canonicalFilePath();
2531 const QString candidate = "%1/%2"_L1.arg(canonicalPath, base);
2532 if (!canonicalPath.isEmpty() && QFileInfo::exists(candidate)) {
2533 found = candidate;
2534 } else if (QTestLog::verboseLevel() >= 2) {
2535 QTestLog::info(qPrintable(
2536 "testdata %1 not found relative to source path [%2]"_L1
2537 .arg(base, QDir::toNativeSeparators(candidate))),
2538 file, line);
2539 }
2540 }
2541
2542 // 4. Try resources
2543 if (found.isEmpty()) {
2544 const QString candidate = ":/%1"_L1.arg(base);
2545 if (QFileInfo::exists(candidate)) {
2546 found = candidate;
2547 } else if (QTestLog::verboseLevel() >= 2) {
2548 QTestLog::info(qPrintable(
2549 "testdata %1 not found in resources [%2]"_L1
2550 .arg(base, QDir::toNativeSeparators(candidate))),
2551 file, line);
2552 }
2553 }
2554
2555 // 5. Try current directory
2556 if (found.isEmpty()) {
2557 const QString candidate = QDir::currentPath() + u'/' + base;
2558 if (QFileInfo::exists(candidate)) {
2559 found = candidate;
2560 } else if (QTestLog::verboseLevel() >= 2) {
2561 QTestLog::info(qPrintable(
2562 "testdata %1 not found in current directory [%2]"_L1
2563 .arg(base, QDir::toNativeSeparators(candidate))),
2564 file, line);
2565 }
2566 }
2567
2568 // 6. Try main source directory
2569 if (found.isEmpty()) {
2570 const QString candidate = QTest::mainSourcePath % u'/' % base;
2571 if (QFileInfo::exists(candidate)) {
2572 found = candidate;
2573 } else if (QTestLog::verboseLevel() >= 2) {
2574 QTestLog::info(qPrintable(
2575 "testdata %1 not found in main source directory [%2]"_L1
2576 .arg(base, QDir::toNativeSeparators(candidate))),
2577 file, line);
2578 }
2579 }
2580
2581 // 7. Try the supplied source directory
2582 if (found.isEmpty() && sourcedir) {
2583 const QString candidate = QFile::decodeName(sourcedir) % u'/' % base;
2584 if (QFileInfo::exists(candidate)) {
2585 found = candidate;
2586 } else if (QTestLog::verboseLevel() >= 2) {
2587 QTestLog::info(qPrintable(
2588 "testdata %1 not found in supplied source directory [%2]"_L1
2589 .arg(base, QDir::toNativeSeparators(candidate))),
2590 file, line);
2591 }
2592 }
2593
2594
2595 if (found.isEmpty()) {
2596 QTestLog::warn(qPrintable(
2597 "testdata %1 could not be located!"_L1.arg(base)),
2598 file, line);
2599 } else if (QTestLog::verboseLevel() >= 1) {
2600 QTestLog::info(qPrintable(
2601 "testdata %1 was located at %2"_L1.arg(base, QDir::toNativeSeparators(found))),
2602 file, line);
2603 }
2604
2605 return found;
2606}
2607
2608/*! \internal
2609*/
2610QString QTest::qFindTestData(const char *base, const char *file, int line, const char *builddir,
2611 const char *sourcedir)
2612{
2613 return qFindTestData(QFile::decodeName(base), file, line, builddir, sourcedir);
2614}
2615
2616/*! \internal
2617*/
2618void *QTest::qData(const char *tagName, int typeId)
2619{
2620 return fetchData(QTestResult::currentTestData(), tagName, typeId);
2621}
2622
2623/*! \internal
2624*/
2625void *QTest::qGlobalData(const char *tagName, int typeId)
2626{
2627 return fetchData(QTestResult::currentGlobalTestData(), tagName, typeId);
2628}
2629
2630/*! \internal
2631*/
2632void *QTest::qElementData(const char *tagName, int metaTypeId)
2633{
2634 QTEST_ASSERT(tagName);
2635 QTestData *data = QTestResult::currentTestData();
2636 QTEST_ASSERT(data);
2637 QTEST_ASSERT(data->parent());
2638
2639 int idx = data->parent()->indexOf(tagName);
2640 QTEST_ASSERT(idx != -1);
2641 QTEST_ASSERT(data->parent()->elementTypeId(idx) == metaTypeId);
2642
2643 return data->data(data->parent()->indexOf(tagName));
2644}
2645
2646/*! \internal
2647*/
2648void QTest::addColumnInternal(int id, const char *name)
2649{
2650 QTestTable *tbl = QTestTable::currentTestTable();
2651 QTEST_ASSERT_X(tbl, "QTest::addColumn()", "Cannot add testdata outside of a _data slot.");
2652
2653 tbl->addColumn(id, name);
2654}
2655
2656/*!
2657 Appends a new row to the current test data.
2658
2659 The test output will identify the test run with this test data using the
2660 name \a dataTag.
2661
2662 Returns a QTestData reference that can be used to stream in data, one value
2663 for each column in the table.
2664
2665 Example:
2666 \snippet code/src_qtestlib_qtestcase.cpp 20
2667
2668 \note This function can only be called as part of a test's data function
2669 that is invoked by the test framework.
2670
2671 See \l {Chapter 2: Data Driven Testing}{Data Driven Testing} for
2672 a more extensive example.
2673
2674 \sa addRow(), addColumn(), QFETCH()
2675*/
2676QTestData &QTest::newRow(const char *dataTag)
2677{
2678 QTEST_ASSERT_X(dataTag, "QTest::newRow()", "Data tag cannot be null");
2679 QTestTable *tbl = QTestTable::currentTestTable();
2680 QTEST_ASSERT_X(tbl, "QTest::newRow()", "Cannot add testdata outside of a _data slot.");
2681 QTEST_ASSERT_X(tbl->elementCount(), "QTest::newRow()",
2682 "Must add columns before attempting to add rows.");
2683
2684 return *tbl->newData(dataTag);
2685}
2686
2687/*!
2688 \since 5.9
2689
2690 Appends a new row to the current test data.
2691
2692 The function's arguments are passed to std::snprintf() for
2693 formatting according to \a format. See the
2694 \l{https://en.cppreference.com/w/cpp/io/c/fprintf}{std::snprintf()
2695 documentation} for caveats and limitations.
2696
2697 The test output will identify the test run with this test data using the
2698 name that results from this formatting.
2699
2700 Returns a QTestData reference that can be used to stream in data, one value
2701 for each column in the table.
2702
2703 Example:
2704 \snippet code/src_qtestlib_qtestcase.cpp addRow
2705
2706 \note This function can only be called as part of a test's data function
2707 that is invoked by the test framework.
2708
2709 See \l {Chapter 2: Data Driven Testing}{Data Driven Testing} for
2710 a more extensive example.
2711
2712 \sa newRow(), addColumn(), QFETCH()
2713*/
2714QTestData &QTest::addRow(const char *format, ...)
2715{
2716 QTEST_ASSERT_X(format, "QTest::addRow()", "Format string cannot be null");
2717 QTestTable *tbl = QTestTable::currentTestTable();
2718 QTEST_ASSERT_X(tbl, "QTest::addRow()", "Cannot add testdata outside of a _data slot.");
2719 QTEST_ASSERT_X(tbl->elementCount(), "QTest::addRow()",
2720 "Must add columns before attempting to add rows.");
2721
2722 char buf[1024];
2723
2724 va_list va;
2725 va_start(va, format);
2726 // we don't care about failures, we accept truncation, as well as trailing garbage.
2727 // Names with more than 1K characters are nonsense, anyway.
2728 std::vsnprintf(buf, sizeof buf, format, va);
2729 va_end(va);
2730
2731 return *tbl->newData(buf);
2732}
2733
2734/*! \fn template <typename T> void QTest::addColumn(const char *name, T *dummy = 0)
2735
2736 Adds a column with type \c{T} to the current test data.
2737 \a name is the name of the column. \a dummy is a workaround
2738 for buggy compilers and can be ignored.
2739
2740 To populate the column with values, newRow() can be used. Use
2741 \l QFETCH() to fetch the data in the actual test.
2742
2743 Example:
2744 \snippet code/src_qtestlib_qtestcase.cpp 21
2745
2746 \note This function can only be used called as part of a test's data
2747 function that is invoked by the test framework.
2748
2749 See \l {Chapter 2: Data Driven Testing}{Data Driven Testing} for
2750 a more extensive example.
2751
2752 \sa QTest::newRow(), QFETCH(), QMetaType
2753*/
2754
2755/*!
2756 Returns the name of the binary that is currently executed.
2757*/
2758const char *QTest::currentAppName()
2759{
2760 return QTestResult::currentAppName();
2761}
2762
2763/*!
2764 Returns the name of the test function that is currently executed.
2765
2766 Example:
2767
2768 \snippet code/src_qtestlib_qtestcase.cpp 22
2769*/
2771{
2772 return QTestResult::currentTestFunction();
2773}
2774
2775/*!
2776 Returns the name of the current test data. If the test doesn't
2777 have any assigned testdata, the function returns \nullptr.
2778*/
2779const char *QTest::currentDataTag()
2780{
2781 return QTestResult::currentDataTag();
2782}
2783
2784/*!
2785 Returns the name of the current global test data. If the test doesn't
2786 have any assigned global testdata, the function returns \nullptr.
2787
2788 \since 6.11
2789*/
2791{
2792 return QTestResult::currentGlobalDataTag();
2793}
2794
2795/*!
2796 Returns \c true if the current test function has failed, otherwise false.
2797
2798 \sa QTest::currentTestResolved()
2799*/
2801{
2802 return QTestResult::currentTestFailed();
2803}
2804
2805/*!
2806 \since 6.5
2807 Returns \c true if the current test function has failed or skipped.
2808
2809 This applies if the test has failed or exercised a skip. When it is true,
2810 the test function should return early. In particular, the \c{QTRY_*} macros
2811 and the test event loop terminate their loops early if executed during the
2812 test function (but not its cleanup()). After a test has called a helper
2813 function that uses this module's macros, it can use this function to test
2814 whether to return early.
2815
2816 \sa QTest::currentTestFailed()
2817*/
2819{
2820 return QTestResult::currentTestFailed() || QTestResult::skipCurrentTest();
2821}
2822
2823/*!
2824 \internal
2825 \since 6.4
2826 Returns \c true during the run of the test-function and its set-up.
2827
2828 Used by the \c{QTRY_*} macros and \l QTestEventLoop to check whether to
2829 return when QTest::currentTestResolved() is true.
2830*/
2832{
2833 return QTest::inTestFunction;
2834}
2835
2836/*! \internal
2837*/
2838QObject *QTest::testObject()
2839{
2840 return currentTestObject;
2841}
2842
2843/*! \internal
2844*/
2845void QTest::setMainSourcePath(const char *file, const char *builddir)
2846{
2847 QString mainSourceFile = QFile::decodeName(file);
2848 QFileInfo fi;
2849 if (builddir)
2850 fi.setFile(QDir(QFile::decodeName(builddir)), mainSourceFile);
2851 else
2852 fi.setFile(mainSourceFile);
2853 QTest::mainSourcePath = fi.absolutePath();
2854}
2855
2856#if QT_DEPRECATED_SINCE(6, 4)
2857/*! \internal
2858 \deprecated [6.4]
2859 This function is called by various specializations of QTest::qCompare
2860 to decide whether to report a failure and to produce verbose test output.
2861
2862 The failureMsg parameter can be null, in which case a default message
2863 will be output if the compare fails. If the compare succeeds, failureMsg
2864 will not be output.
2865
2866 Using this function is not optimal, because it requires the string
2867 representations of \a actualVal and \a expectedVal to be pre-calculated,
2868 even though they will be used only if the comparison fails. Prefer using the
2869 \l compare_helper() overload that takes qxp::function_ref() for such cases.
2870
2871 If the caller creates a custom failure message showing the compared values,
2872 or if those values cannot be stringified, use the overload of the function
2873 that takes no \a actualVal and \a expectedVal parameters.
2874*/
2875bool QTest::compare_helper(bool success, const char *failureMsg,
2876 char *actualVal, char *expectedVal,
2877 const char *actual, const char *expected,
2878 const char *file, int line)
2879{
2880 return QTestResult::compare(success, failureMsg, actualVal, expectedVal,
2881 actual, expected, file, line);
2882}
2883#endif // QT_DEPRECATED_SINCE(6, 4)
2884
2885#if QT_DEPRECATED_SINCE(6, 8)
2886/*! \internal
2887 \since 6.4
2888 This function is called by various specializations of QTest::qCompare
2889 to decide whether to report a failure and to produce verbose test output.
2890
2891 The \a failureMsg parameter can be \c {nullptr}, in which case a default
2892 message will be output if the compare fails. If the comparison succeeds,
2893 \a failureMsg will not be output.
2894
2895 This overload of the function uses qxp::function_ref to defer conversion of
2896 \a actualVal and \a expectedVal to strings until that is really needed
2897 (when the comparison fails). This speeds up test case execution on success.
2898*/
2899bool QTest::compare_helper(bool success, const char *failureMsg,
2900 qxp::function_ref<const char *()> actualVal,
2901 qxp::function_ref<const char *()> expectedVal,
2902 const char *actual, const char *expected,
2903 const char *file, int line)
2904{
2905 return QTestResult::reportResult(success, &actualVal, &expectedVal,
2906 QTest::functionRefFormatter,
2907 QTest::functionRefFormatter, actual, expected,
2908 QTest::ComparisonOperation::CustomCompare,
2909 file, line, failureMsg);
2910}
2911#endif // QT_DEPRECATED_SINCE(6, 8)
2912
2913/*! \internal
2914 \since 6.8
2915 This function is called by various specializations of QTest::qCompare
2916 to decide whether to report a failure and to produce verbose test output.
2917
2918 The \a failureMsg parameter can be \c {nullptr}, in which case a default
2919 message will be output if the compare fails. If the comparison succeeds,
2920 \a failureMsg will not be output.
2921*/
2922
2923bool QTest::compare_helper(bool success, const char *failureMsg,
2924 const void *actualPtr, const void *expectedPtr,
2925 const char *(*actualFormatter)(const void *),
2926 const char *(*expectedFormatter)(const void *),
2927 const char *actual, const char *expected,
2928 const char *file, int line)
2929{
2930 return QTestResult::reportResult(success, actualPtr, expectedPtr,
2931 actualFormatter, expectedFormatter,
2932 actual, expected,
2933 QTest::ComparisonOperation::CustomCompare,
2934 file, line, failureMsg);
2935}
2936
2937
2938/*! \internal
2939 \since 6.9
2940 This function reports the result of a three-way comparison, when needed.
2941
2942 Aside from logging every check if in verbose mode and reporting an
2943 unexpected pass when failure was expected, if \a success is \c true
2944 this produces no output. Otherwise, a failure is reported. The output
2945 on failure reports the expressions compared, their values, the actual
2946 result of the comparison and the expected result of comparison, along
2947 with the supplied failure message \a failureMsg and the \a file and
2948 \a line number at which the error arose.
2949
2950 The expressions compared are supplied as \a lhsExpression and
2951 \a rhsExpression.
2952 These are combined, with \c{"<=>"}, to obtain the actual comparison
2953 expression. Their actual values are pointed to by \a lhsPtr and
2954 \a rhsPtr, which are formatted by \a lhsFormatter and \a rhsFormatter
2955 as, respectively, \c lhsFormatter(lhsPtr) and \c rhsFormatter(rhsPtr).
2956 The actual comparison expression is contrasted,
2957 in the output, with the expected comparison expression
2958 \a expectedExpression. Their respective values are supplied by
2959 \a actualOrderPtr and \a expectedOrderPtr pointers, which are
2960 formatted by \a actualOrderFormatter and \a expectedOrderFormatter.
2961
2962 If \a failureMsg is \nullptr a default is used. If a formatter
2963 function returns \a nullptr, the text \c{"<null>"} is used.
2964*/
2965bool QTest::compare_3way_helper(bool success, const char *failureMsg,
2966 const void *lhsPtr, const void *rhsPtr,
2967 const char *(*lhsFormatter)(const void*),
2968 const char *(*rhsFormatter)(const void*),
2969 const char *lhsExpression, const char *rhsExpression,
2970 const char *(*actualOrderFormatter)(const void *),
2971 const char *(*expectedOrderFormatter)(const void *),
2972 const void *actualOrderPtr, const void *expectedOrderPtr,
2973 const char *expectedExpression,
2974 const char *file, int line)
2975{
2976 return QTestResult::report3WayResult(success, failureMsg,
2977 lhsPtr, rhsPtr,
2978 lhsFormatter, rhsFormatter,
2979 lhsExpression, rhsExpression,
2980 actualOrderFormatter,
2981 expectedOrderFormatter,
2982 actualOrderPtr, expectedOrderPtr,
2983 expectedExpression,
2984 file, line);
2985}
2986
2987/*! \internal
2988 \since 6.4
2989 This function is called by various specializations of QTest::qCompare
2990 to decide whether to report a failure and to produce verbose test output.
2991
2992 This overload should be used when there is no string representation of
2993 actual and expected values, so only the \a failureMsg is shown when the
2994 comparison fails. Because of that, \a failureMsg can't be \c {nullptr}.
2995 If the comparison succeeds, \a failureMsg will not be output.
2996*/
2997bool QTest::compare_helper(bool success, const char *failureMsg, const char *actual,
2998 const char *expected, const char *file, int line)
2999{
3000 return QTestResult::compare(success, failureMsg, actual, expected, file, line);
3001}
3002
3003template <typename T>
3004static bool floatingCompare(const T &actual, const T &expected)
3005{
3006 switch (qFpClassify(expected))
3007 {
3008 case FP_INFINITE:
3009 return (expected < 0) == (actual < 0) && qFpClassify(actual) == FP_INFINITE;
3010 case FP_NAN:
3011 return qFpClassify(actual) == FP_NAN;
3012 default:
3013 if (!qFuzzyIsNull(expected))
3014 return qFuzzyCompare(actual, expected);
3015 Q_FALLTHROUGH();
3016 case FP_SUBNORMAL: // subnormal is always fuzzily null
3017 case FP_ZERO:
3018 return qFuzzyIsNull(actual);
3019 }
3020}
3021
3022/*! \fn bool QTest::qCompare(const qfloat16 &t1, const qfloat16 &t2, const char *actual, const char *expected, const char *file, int line)
3023 \internal
3024*/
3025bool QTest::qCompare(qfloat16 const &t1, qfloat16 const &t2, const char *actual, const char *expected,
3026 const char *file, int line)
3027{
3028 auto formatter = Internal::genericToString<qfloat16>;
3029 return compare_helper(floatingCompare(t1, t2),
3030 "Compared qfloat16s are not the same (fuzzy compare)",
3031 &t1, &t2, formatter, formatter,
3032 actual, expected, file, line);
3033}
3034
3035/*! \fn bool QTest::qCompare(const float &t1, const float &t2, const char *actual, const char *expected, const char *file, int line)
3036 \internal
3037*/
3038bool QTest::qCompare(float const &t1, float const &t2, const char *actual, const char *expected,
3039 const char *file, int line)
3040{
3041 return QTestResult::compare(floatingCompare(t1, t2),
3042 "Compared floats are not the same (fuzzy compare)",
3043 t1, t2, actual, expected, file, line);
3044}
3045
3046/*! \fn bool QTest::qCompare(const double &t1, const double &t2, const char *actual, const char *expected, const char *file, int line)
3047 \internal
3048*/
3049bool QTest::qCompare(double const &t1, double const &t2, const char *actual, const char *expected,
3050 const char *file, int line)
3051{
3052 return QTestResult::compare(floatingCompare(t1, t2),
3053 "Compared doubles are not the same (fuzzy compare)",
3054 t1, t2, actual, expected, file, line);
3055}
3056
3057/*! \fn bool QTest::qCompare(int t1, int t2, const char *actual, const char *expected, const char *file, int line)
3058 \internal
3059 \since 5.14
3060*/
3061bool QTest::qCompare(int t1, int t2, const char *actual, const char *expected,
3062 const char *file, int line)
3063{
3064 return QTestResult::compare(t1 == t2,
3065 "Compared values are not the same",
3066 t1, t2, actual, expected, file, line);
3067}
3068
3069#if QT_POINTER_SIZE == 8
3070/*! \fn bool QTest::qCompare(qsizetype t1, qsizetype t2, const char *actual, const char *expected, const char *file, int line)
3071 \internal
3072 \since 6.0
3073*/
3074
3075bool QTest::qCompare(qsizetype t1, qsizetype t2, const char *actual, const char *expected,
3076 const char *file, int line)
3077{
3078 return QTestResult::compare(t1 == t2,
3079 "Compared values are not the same",
3080 t1, t2, actual, expected, file, line);
3081}
3082#endif // QT_POINTER_SIZE == 8
3083
3084/*! \fn bool QTest::qCompare(unsigned t1, unsigned t2, const char *actual, const char *expected, const char *file, int line)
3085 \internal
3086 \since 5.14
3087*/
3088bool QTest::qCompare(unsigned t1, unsigned t2, const char *actual, const char *expected,
3089 const char *file, int line)
3090{
3091 return QTestResult::compare(t1 == t2,
3092 "Compared values are not the same",
3093 t1, t2, actual, expected, file, line);
3094}
3095
3096/*! \fn bool QTest::qCompare(QStringView t1, QStringView t2, const char *actual, const char *expected, const char *file, int line)
3097 \internal
3098 \since 5.14
3099*/
3100bool QTest::qCompare(QStringView t1, QStringView t2, const char *actual, const char *expected,
3101 const char *file, int line)
3102{
3103 return QTestResult::compare(t1 == t2,
3104 "Compared values are not the same",
3105 t1, t2, actual, expected, file, line);
3106}
3107
3108/*!
3109 \internal
3110 \since 5.14
3111*/
3112bool QTest::qCompare(QStringView t1, const QLatin1StringView &t2, const char *actual, const char *expected,
3113 const char *file, int line)
3114{
3115 return QTestResult::compare(t1 == t2,
3116 "Compared values are not the same",
3117 t1, t2, actual, expected, file, line);
3118}
3119
3120/*!
3121 \internal
3122 \since 5.14
3123*/
3124bool QTest::qCompare(const QLatin1StringView &t1, QStringView t2, const char *actual, const char *expected,
3125 const char *file, int line)
3126{
3127 return QTestResult::compare(t1 == t2,
3128 "Compared values are not the same",
3129 t1, t2, actual, expected, file, line);
3130}
3131
3132/*! \fn bool QTest::qCompare(const QString &t1, const QString &t2, const char *actual, const char *expected, const char *file, int line)
3133 \internal
3134 \since 5.14
3135*/
3136
3137/*! \fn bool QTest::qCompare(const QString &t1, const QLatin1StringView &t2, const char *actual, const char *expected, const char *file, int line)
3138 \internal
3139 \since 5.14
3140*/
3141
3142/*! \fn bool QTest::qCompare(const QLatin1StringView &t1, const QString &t2, const char *actual, const char *expected, const char *file, int line)
3143 \internal
3144 \since 5.14
3145*/
3146
3147/*! \fn bool QTest::qCompare(const double &t1, const float &t2, const char *actual, const char *expected, const char *file, int line)
3148 \internal
3149*/
3150
3151/*! \fn bool QTest::qCompare(const float &t1, const double &t2, const char *actual, const char *expected, const char *file, int line)
3152 \internal
3153*/
3154
3155#define TO_STRING_IMPL(TYPE, FORMAT) template
3156 <> Q_TESTLIB_EXPORT char *QTest::toString<TYPE>(const TYPE &t) \
3157{
3158 char *msg = new char[128];
3159 std::snprintf(msg, 128, #FORMAT, t);
3160 return msg; \
3161}
3162
3163TO_STRING_IMPL(short, %hd)
3164TO_STRING_IMPL(ushort, %hu)
3165TO_STRING_IMPL(int, %d)
3166TO_STRING_IMPL(uint, %u)
3167TO_STRING_IMPL(long, %ld)
3168TO_STRING_IMPL(ulong, %lu)
3169TO_STRING_IMPL(qint64, %lld)
3170TO_STRING_IMPL(quint64, %llu)
3171TO_STRING_IMPL(bool, %d)
3172TO_STRING_IMPL(signed char, %hhd)
3173TO_STRING_IMPL(unsigned char, %hhu)
3174
3175// Merge of ISO C23 getpayload() and issignaling()
3176template <typename T> static auto decodeNanPayload(T t)
3177{
3178 constexpr int Digits = std::numeric_limits<T>::digits;
3179 constexpr quint64 MantissaMask = (Q_UINT64_C(1) << (Digits - 1)) - 1;
3180 constexpr quint64 IsQuietBit = quint64(QT_CONFIG(signaling_nan)) << (Digits - 2);
3181 constexpr quint64 PayloadMask = MantissaMask & ~IsQuietBit;
3182
3183 struct R {
3184 quint64 payload;
3185 bool isQuiet;
3186 } r;
3187 Q_ASSERT(qIsNaN(t));
3188 quint64 u = qFromUnaligned<typename QIntegerForSizeof<T>::Unsigned>(&t);
3189 r.payload = u & PayloadMask;
3190 r.isQuiet = !QT_CONFIG(signaling_nan) || (u & IsQuietBit);
3191 return r;
3192}
3193
3194// Be consistent about display of infinities and NaNs (snprintf()'s varies,
3195// notably on MinGW, despite POSIX documenting "[-]inf" or "[-]infinity" for %f,
3196// %e and %g, uppercasing for their capital versions; similar for "nan"):
3197template <typename T> static char *toStringFp(T t)
3198{
3199 using std::signbit;
3200 char *msg = new char[128];
3201 bool negative = signbit(t);
3202
3203 switch (qFpClassify(t)) {
3204 case FP_INFINITE:
3205 qstrncpy(msg, (negative ? "-inf" : "inf"), 128);
3206 break;
3207 case FP_NAN:
3208 if (auto r = decodeNanPayload(t); r.payload) {
3209 std::snprintf(msg, 128, "%s%snan(%#llx)",
3210 negative ? "-" : "", r.isQuiet ? "" : "s", r.payload);
3211 } else {
3212 Q_ASSERT(r.isQuiet); // only quiet NaNs can have payload == 0
3213 qstrncpy(msg, (negative ? "-nan" : "nan"), 128);
3214 }
3215 break;
3216 case FP_ZERO:
3217 qstrncpy(msg, (negative ? "-0 (-0x0p+0)" : "0 (0x0p+0)"), 128);
3218 break;
3219 default:
3220 std::snprintf(msg, 128, "%.*g (%a)", std::numeric_limits<T>::digits10 + 1, double(t),
3221 double(t));
3222 break;
3223 }
3224 return msg;
3225}
3226
3227#define TO_STRING_FLOAT(TYPE) template
3228 <> Q_TESTLIB_EXPORT char *QTest::toString<TYPE>(const TYPE &t) \
3229{
3230 return toStringFp(t); \
3231}
3232TO_STRING_FLOAT(qfloat16)
3233TO_STRING_FLOAT(float)
3234TO_STRING_FLOAT(double)
3235
3236template <> Q_TESTLIB_EXPORT char *QTest::toString<char>(const char &t)
3237{
3238 unsigned char c = static_cast<unsigned char>(t);
3239 char *msg = new char[16];
3240 switch (c) {
3241 case 0x00:
3242 qstrcpy(msg, "'\\0'");
3243 break;
3244 case 0x07:
3245 qstrcpy(msg, "'\\a'");
3246 break;
3247 case 0x08:
3248 qstrcpy(msg, "'\\b'");
3249 break;
3250 case 0x09:
3251 qstrcpy(msg, "'\\t'");
3252 break;
3253 case 0x0a:
3254 qstrcpy(msg, "'\\n'");
3255 break;
3256 case 0x0b:
3257 qstrcpy(msg, "'\\v'");
3258 break;
3259 case 0x0c:
3260 qstrcpy(msg, "'\\f'");
3261 break;
3262 case 0x0d:
3263 qstrcpy(msg, "'\\r'");
3264 break;
3265 case 0x22:
3266 qstrcpy(msg, "'\\\"'");
3267 break;
3268 case 0x27:
3269 qstrcpy(msg, "'\\\''");
3270 break;
3271 case 0x5c:
3272 qstrcpy(msg, "'\\\\'");
3273 break;
3274 default:
3275 if (c < 0x20 || c >= 0x7F)
3276 std::snprintf(msg, 16, "'\\x%02x'", c);
3277 else
3278 std::snprintf(msg, 16, "'%c'" , c);
3279 }
3280 return msg;
3281}
3282
3283/*! \internal
3284*/
3285char *QTest::toString(const char *str)
3286{
3287 if (!str) {
3288 char *msg = new char[1];
3289 *msg = '\0';
3290 return msg;
3291 }
3292 char *msg = new char[strlen(str) + 1];
3293 return qstrcpy(msg, str);
3294}
3295
3296/*! \internal
3297*/
3298char *QTest::toString(const volatile void *p) // Use volatile to match compare_ptr_helper()
3299{
3300 char *msg = new char[128];
3301 std::snprintf(msg, 128, "%p", p);
3302 return msg;
3303}
3304
3305/*! \internal
3306*/
3307char *QTest::toString(const volatile QObject *vo)
3308{
3309 if (vo == nullptr)
3310 return qstrdup("<null>");
3311
3312 return QTest::toString(const_cast<const QObject*>(vo));
3313}
3314
3315/*! \internal
3316*/
3317char *QTest::toString(const QObject *o)
3318{
3319 if (o == nullptr)
3320 return qstrdup("<null>");
3321
3322 const QString &name = o->objectName();
3323 const char *className = o->metaObject()->className();
3324 char *msg = new char[256];
3325 if (name.isEmpty())
3326 std::snprintf(msg, 256, "%s/%p", className, o);
3327 else
3328 std::snprintf(msg, 256, "%s/\"%s\"", className, qPrintable(name));
3329 return msg;
3330}
3331
3332
3333/*! \fn char *QTest::toString(const QColor &color)
3334 \internal
3335*/
3336
3337/*! \fn char *QTest::toString(const QRegion &region)
3338 \internal
3339*/
3340
3341/*! \fn char *QTest::toString(const QHostAddress &addr)
3342 \internal
3343*/
3344
3345/*! \fn char *QTest::toString(QNetworkReply::NetworkError code)
3346 \internal
3347*/
3348
3349/*! \fn char *QTest::toString(const QNetworkCookie &cookie)
3350 \internal
3351*/
3352
3353/*! \fn char *QTest::toString(const QList<QNetworkCookie> &list)
3354 \internal
3355*/
3356
3357/*! \internal
3358*/
3359bool QTest::compare_string_helper(const char *t1, const char *t2, const char *actual,
3360 const char *expected, const char *file, int line)
3361{
3362 auto formatter = Internal::genericToString<const char *>;
3363 return compare_helper(qstrcmp(t1, t2) == 0, "Compared strings are not the same",
3364 &t1, &t2, formatter, formatter,
3365 actual, expected, file, line);
3366}
3367
3368/*!
3369 \namespace QTest::Internal
3370 \internal
3371*/
3372
3373/*! \fn bool QTest::compare_ptr_helper(const volatile void *t1, const volatile void *t2, const char *actual, const char *expected, const char *file, int line)
3374 \internal
3375*/
3376
3377/*! \fn bool QTest::compare_ptr_helper(const volatile void *t1, std::nullptr_t, const char *actual, const char *expected, const char *file, int line)
3378 \internal
3379*/
3380
3381/*! \fn bool QTest::compare_ptr_helper(std::nullptr_t, const volatile void *t2, const char *actual, const char *expected, const char *file, int line)
3382 \internal
3383*/
3384
3385/*! \fn template <typename T1, typename T2> bool QTest::qCompare(const T1 &t1, const T2 &t2, const char *actual, const char *expected, const char *file, int line)
3386 \internal
3387*/
3388
3389/*! \fn bool QTest::qCompare(const QIcon &t1, const QIcon &t2, const char *actual, const char *expected, const char *file, int line)
3390 \internal
3391*/
3392
3393/*! \fn bool QTest::qCompare(const QImage &t1, const QImage &t2, const char *actual, const char *expected, const char *file, int line)
3394 \internal
3395*/
3396
3397/*! \fn bool QTest::qCompare(const QPixmap &t1, const QPixmap &t2, const char *actual, const char *expected, const char *file, int line)
3398 \internal
3399*/
3400
3401/*! \fn template <typename T> bool QTest::qCompare(const T &t1, const T &t2, const char *actual, const char *expected, const char *file, int line)
3402 \internal
3403*/
3404
3405/*! \fn template <typename T> bool QTest::qCompare(const T *t1, const T *t2, const char *actual, const char *expected, const char *file, int line)
3406 \internal
3407*/
3408
3409/*! \fn template <typename T> bool QTest::qCompare(T *t, std::nullptr_t, const char *actual, const char *expected, const char *file, int line)
3410 \internal
3411*/
3412
3413/*! \fn template <typename T> bool QTest::qCompare(std::nullptr_t, T *t, const char *actual, const char *expected, const char *file, int line)
3414 \internal
3415*/
3416
3417/*! \fn template <typename T> bool QTest::qCompare(T *t1, T *t2, const char *actual, const char *expected, const char *file, int line)
3418 \internal
3419*/
3420
3421/*! \fn template <typename T1, typename T2> bool QTest::qCompare(const T1 *t1, const T2 *t2, const char *actual, const char *expected, const char *file, int line)
3422 \internal
3423*/
3424
3425/*! \fn template <typename T1, typename T2> bool QTest::qCompare(T1 *t1, T2 *t2, const char *actual, const char *expected, const char *file, int line)
3426 \internal
3427*/
3428
3429/*! \fn bool QTest::qCompare(const char *t1, const char *t2, const char *actual, const char *expected, const char *file, int line)
3430 \internal
3431*/
3432
3433/*! \fn bool QTest::qCompare(char *t1, char *t2, const char *actual, const char *expected, const char *file, int line)
3434 \internal
3435*/
3436
3437/*! \fn bool QTest::qCompare(char *t1, const char *t2, const char *actual, const char *expected, const char *file, int line)
3438 \internal
3439*/
3440
3441/*! \fn bool QTest::qCompare(const char *t1, char *t2, const char *actual, const char *expected, const char *file, int line)
3442 \internal
3443*/
3444
3445/*! \fn bool QTest::qCompare(const QStringList &t1, const QStringList &t2, const char *actual, const char *expected, const char *file, int line)
3446 \internal
3447*/
3448
3449/*! \fn template <typename T> bool QTest::qCompare(const QList<T> &t1, const QList<T> &t2, const char *actual, const char *expected, const char *file, int line)
3450 \internal
3451*/
3452
3453/*! \fn template <typename T> bool QTest::qCompare(const QFlags<T> &t1, const T &t2, const char *actual, const char *expected, const char *file, int line)
3454 \internal
3455*/
3456
3457/*! \fn template <typename T> bool QTest::qCompare(const QFlags<T> &t1, const int &t2, const char *actual, const char *expected, const char *file, int line)
3458 \internal
3459*/
3460
3461/*! \fn bool QTest::qCompare(const qint64 &t1, const qint32 &t2, const char *actual, const char *expected, const char *file, int line)
3462 \internal
3463*/
3464
3465/*! \fn bool QTest::qCompare(const qint64 &t1, const quint32 &t2, const char *actual, const char *expected, const char *file, int line)
3466 \internal
3467*/
3468
3469/*! \fn bool QTest::qCompare(const quint64 &t1, const quint32 &t2, const char *actual, const char *expected, const char *file, int line)
3470 \internal
3471*/
3472
3473/*! \fn bool QTest::qCompare(const qint32 &t1, const qint64 &t2, const char *actual, const char *expected, const char *file, int line)
3474 \internal
3475*/
3476
3477/*! \fn bool QTest::qCompare(const quint32 &t1, const qint64 &t2, const char *actual, const char *expected, const char *file, int line)
3478 \internal
3479*/
3480
3481/*! \fn bool QTest::qCompare(const quint32 &t1, const quint64 &t2, const char *actual, const char *expected, const char *file, int line)
3482 \internal
3483*/
3484
3485/*! \fn template <typename T> bool QTest::qTest(const T& actual, const char *elementName, const char *actualStr, const char *expected, const char *file, int line)
3486 \internal
3487*/
3488
3489/*! \fn void QTest::sendKeyEvent(KeyAction action, QWidget *widget, Qt::Key code, QString text, Qt::KeyboardModifiers modifier, int delay=-1)
3490 \internal
3491*/
3492
3493/*! \fn void QTest::sendKeyEvent(KeyAction action, QWindow *window, Qt::Key code, QString text, Qt::KeyboardModifiers modifier, int delay=-1)
3494 \internal
3495*/
3496
3497/*! \fn void QTest::sendKeyEvent(KeyAction action, QWidget *widget, Qt::Key code, char ascii, Qt::KeyboardModifiers modifier, int delay=-1)
3498 \internal
3499*/
3500
3501/*! \fn void QTest::sendKeyEvent(KeyAction action, QWindow *window, Qt::Key code, char ascii, Qt::KeyboardModifiers modifier, int delay=-1)
3502 \internal
3503*/
3504
3505/*! \fn void QTest::simulateEvent(QWidget *widget, bool press, int code, Qt::KeyboardModifiers modifier, QString text, bool repeat, int delay=-1)
3506 \internal
3507*/
3508
3509/*! \fn void QTest::simulateEvent(QWindow *window, bool press, int code, Qt::KeyboardModifiers modifier, QString text, bool repeat, int delay=-1)
3510 \internal
3511*/
3512
3513QT_END_NAMESPACE
static QMetaMethod findMethod(const QObject *obj, const char *signature)
TestMethods(const QObject *o, MetaMethods m={})
void invokeTests(QObject *testObject) const
Q_TESTLIB_EXPORT int lastMouseTimestamp
Q_TESTLIB_EXPORT void qtest_qParseArgs(int argc, char *argv[], bool qml)
constexpr qsizetype PrettyUnicodeMaxIncrement
void runWithWatchdog(std::optional< WatchDog > &watchDog, Functor &&f)
Q_TESTLIB_EXPORT int qRun()
Q_TESTLIB_EXPORT bool currentTestResolved()
bool reportResult(bool success, const void *lhs, const void *rhs, const char *(*lhsFormatter)(const void *), const char *(*rhsFormatter)(const void *), const char *lhsExpr, const char *rhsExpr, ComparisonOperation op, const char *file, int line)
Q_TESTLIB_EXPORT bool qCompare(unsigned t1, unsigned t2, const char *actual, const char *expected, const char *file, int line)
constexpr qsizetype PrettyUnicodeMaxOutputSize
static void invokeTestMethodIfExists(const char *methodName, QObject *obj=QTest::currentTestObject)
Q_TESTLIB_EXPORT void qtest_qParseArgs(int argc, const char *const argv[], bool qml)
Q_TESTLIB_EXPORT bool compare_3way_helper(bool success, const char *failureMsg, const void *lhsPtr, const void *rhsPtr, const char *(*lhsFormatter)(const void *), const char *(*rhsFormatter)(const void *), const char *lhsStr, const char *rhsStr, const char *(*actualOrderFormatter)(const void *), const char *(*expectedOrderFormatter)(const void *), const void *actualOrderPtr, const void *expectedOrderPtr, const char *expectedExpression, const char *file, int line)
Q_TESTLIB_EXPORT bool qVerify(bool statement, const char *statementStr, const char *description, const char *file, int line)
void * fetchData(QTestData *data, const char *tagName, int typeId)
static QList< QBenchmarkResult > qMedian(const QList< QList< QBenchmarkResult > > &container)
Q_TESTLIB_EXPORT const char * currentTestFunction()
Returns the name of the test function that is currently executed.
Q_TESTLIB_EXPORT bool runningTest()
Q_TESTLIB_EXPORT void setMainSourcePath(const char *file, const char *builddir=nullptr)
static char * writePrettyUnicodeChar(char16_t ch, char *const buffer)
Q_TESTLIB_EXPORT char * toString(const char *)
Q_TESTLIB_EXPORT char * toString(const volatile QObject *)
static int repetitions
static void qPrintDataTags(FILE *stream)
Q_TESTLIB_EXPORT void * qElementData(const char *elementName, int metaTypeId)
Q_TESTLIB_EXPORT bool qCompare(int t1, int t2, const char *actual, const char *expected, const char *file, int line)
static QObject * currentTestObject
void setThrowOnFail(bool enable) noexcept
Q_TESTLIB_EXPORT char * toString(const volatile void *)
Q_TESTLIB_EXPORT bool qExpectFail(const char *dataIndex, const char *comment, TestFailMode mode, const char *file, int line)
static int keyDelay
static bool invokeTestMethodIfValid(QMetaMethod m, QObject *obj=QTest::currentTestObject)
static bool qPrintTestSlots(FILE *stream, const char *filter=nullptr, const char *preamble="")
Q_TESTLIB_EXPORT void * qData(const char *tagName, int typeId)
int defaultEventDelay()
Q_TESTLIB_EXPORT bool qCompare(double const &t1, double const &t2, const char *actual, const char *expected, const char *file, int line)
Q_TESTLIB_EXPORT bool currentTestFailed()
Returns true if the current test function has failed, otherwise false.
static bool skipBlacklisted
Q_TESTLIB_EXPORT bool qCompare(float const &t1, float const &t2, const char *actual, const char *expected, const char *file, int line)
void setThrowOnSkip(bool enable) noexcept
char * formatString(const char *prefix, const char *suffix, size_t numArguments,...)
static bool inTestFunction
char * toPrettyCString(const char *p, qsizetype length)
char * toHexRepresentation(const char *ba, qsizetype length)
Returns a pointer to a string that is the string ba represented as a space-separated sequence of hex ...
Q_TESTLIB_EXPORT bool compare_string_helper(const char *t1, const char *t2, const char *actual, const char *expected, const char *file, int line)
static int mouseDelay
static void printUnknownDataTagError(QLatin1StringView name, QLatin1StringView tag, const QTestTable &lTable, const QTestTable &gTable)
Q_TESTLIB_EXPORT bool qCompare(const QLatin1StringView &t1, QStringView t2, const char *actual, const char *expected, const char *file, int line)
Q_TESTLIB_EXPORT const char * currentGlobalDataTag()
Returns the name of the current global test data.
Q_TESTLIB_EXPORT void failOnWarning()
Q_DECL_COLD_FUNCTION Q_TESTLIB_EXPORT void qCaught(const char *expected, const char *what, const char *file, int line)
Q_TESTLIB_EXPORT bool printAvailableFunctions
Q_TESTLIB_EXPORT void ignoreMessage(QtMsgType type, const char *message)
Ignores messages created by qDebug(), qInfo() or qWarning().
Q_TESTLIB_EXPORT void failOnWarning(const char *message)
char * toString(std::chrono::duration< Rep, Period > duration)
Q_TESTLIB_EXPORT void qSkip(const char *message, const char *file, int line)
bool qCompare(QString const &t1, QLatin1StringView const &t2, const char *actual, const char *expected, const char *file, int line)
Definition qtest.h:32
static int qToInt(const char *str)
Q_TESTLIB_EXPORT char * toString(const QObject *)
char * toPrettyUnicode(QStringView string)
Q_DECL_COLD_FUNCTION Q_TESTLIB_EXPORT void qCaught(const char *expected, const char *file, int line)
Q_TESTLIB_EXPORT const char * currentDataTag()
Returns the name of the current test data.
Q_TESTLIB_EXPORT bool compare_helper(bool success, const char *failureMsg, const void *actualPtr, const void *expectedPtr, const char *(*actualFormatter)(const void *), const char *(*expectedFormatter)(const void *), const char *actual, const char *expected, const char *file, int line)
Q_TESTLIB_EXPORT bool compare_helper(bool success, const char *failureMsg, const char *actual, const char *expected, const char *file, int line)
Q_TESTLIB_EXPORT void qCleanup()
Q_TESTLIB_EXPORT void addColumnInternal(int id, const char *name)
static int eventDelay
static QString mainSourcePath
Q_DECL_COLD_FUNCTION Q_TESTLIB_EXPORT void qFail(const char *message, const char *file, int line)
static void terminateHandler()
Q_TESTLIB_EXPORT void * qGlobalData(const char *tagName, int typeId)
Q_TESTLIB_EXPORT bool qCompare(QStringView t1, const QLatin1StringView &t2, const char *actual, const char *expected, const char *file, int line)
Q_TESTLIB_EXPORT const char * currentAppName()
Returns the name of the binary that is currently executed.
static char * toStringFp(T t)
static bool floatingCompare(const T &actual, const T &expected)
#define TO_STRING_IMPL(TYPE, FORMAT)
static bool installCoverageTool(const char *appname, const char *testname)
#define TO_STRING_FLOAT(TYPE)
static bool isValidSlot(const QMetaMethod &sl)
static void initEnvironment()
static auto decodeNanPayload(T t)
QTestDataSetter(QTestData *data)