5#include <QtTest/qtestcase.h>
6#include <QtTest/private/qtestcase_p.h>
7#include <QtTest/qtestassert.h>
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>
15#include <QtCore/qexception.h>
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>
32#include <QtCore/qtestsupport_core.h>
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>
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>
50#include <QtTest/private/qtestutil_macos_p.h>
53#if defined(Q_OS_DARWIN)
54#include <QtTest/private/qappletestlogger_p.h>
59#if !defined(Q_OS_INTEGRITY) || __GHS_VERSION_NUMBER > 202014
63# undef __cpp_lib_to_chars
78#if defined(Q_OS_LINUX)
85# if !defined(Q_CC_MINGW) || (defined(Q_CC_MINGW) && defined(__MINGW64_VERSION_MAJOR))
88#include <qt_windows.h>
91#include <QtCore/private/qcore_unix_p.h>
94#if __has_include(<paths.h>)
102# if !defined(Q_OS_INTEGRITY)
103# include <sys/resource.h>
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>
114#if defined(Q_OS_WASM)
115#include <emscripten.h>
119#include <QtCore/QStandardPaths>
126using namespace Qt::StringLiterals;
128using QtMiscUtils::toHexUpper;
129using QtMiscUtils::fromHex;
133#if defined(__COVERAGESCANNER__) && !QT_CONFIG(testlib_selfcover)
134 if (!qEnvironmentVariableIsEmpty(
"QT_TESTCOCOON_ACTIVE"))
138 qputenv(
"QT_TESTCOCOON_ACTIVE",
"1");
141 __coveragescanner_install(appname);
142 __coveragescanner_testname(testname);
143 __coveragescanner_clear();
154 if (sl.access() != QMetaMethod::Private || sl.parameterCount() != 0
155 || sl.returnType() != QMetaType::Void || sl.methodType() != QMetaMethod::Slot)
157 const QByteArray name = sl.name();
158 return !(name.isEmpty() || name.endsWith(
"_data")
159 || name ==
"initTestCase" || name ==
"cleanupTestCase"
160 || name ==
"init" || name ==
"cleanup");
170#if !QT_CONFIG(future)
171using QException = std::exception;
174class TestFailedException :
public QException
177 TestFailedException() =
default;
178 ~TestFailedException() override =
default;
180 const char *what()
const noexcept override {
return "QtTest: test failed"; }
183 TestFailedException *clone()
const override {
return new TestFailedException(); }
184 void raise()
const override {
throw TestFailedException(); }
188class TestSkippedException :
public QException
191 TestSkippedException() =
default;
192 ~TestSkippedException() override =
default;
194 const char *what()
const noexcept override {
return "QtTest: test was skipped"; }
197 TestSkippedException *clone()
const override {
return new TestSkippedException(); }
198 void raise()
const override {
throw TestSkippedException(); }
226
227
228
229
230
231
232
233
234
235
238
239
240
241
242
243
244
245
246
249
250
251
252
253
254
255
256
257
260
261
262
263
264
265
267
268
269
270
272
273
274
275
278
279
280
281
282
283
285
286
287
288
290
291
292
293
296
297
298
299
300
301
303
304
305
306
308
309
310
311
314
315
316
317
318
319
321
322
323
324
326
327
328
329
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
352 g_throwOnFail.fetchAndAddRelaxed(enable ? 1 : -1);
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
376 g_throwOnSkip.fetchAndAddRelaxed(enable ? 1 : -1);
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
396#if defined(Q_OS_MACOS)
414 void invokeTest(
int index, QLatin1StringView tag,
std::optional<
WatchDog> &watchDog)
const;
415 void invokeTestOnData(
int index)
const;
417 QMetaMethod m_initTestCaseMethod;
418 QMetaMethod m_initTestCaseDataMethod;
419 QMetaMethod m_cleanupTestCaseMethod;
420 QMetaMethod m_initMethod;
421 QMetaMethod m_cleanupMethod;
423 MetaMethods m_methods;
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);
441 m_methods.push_back(me);
446QMetaMethod
TestMethods::findMethod(
const QObject *obj,
const char *signature)
448 const QMetaObject *metaObject = obj->metaObject();
449 const int funcIndex = metaObject->indexOfMethod(signature);
450 return funcIndex >= 0 ? metaObject->method(funcIndex) : QMetaMethod();
471 try { ok = m.invoke(obj, Qt ::DirectConnection); }
472 catch (
const TestFailedException &) {}
473 catch (
const TestSkippedException &) {}
480 const QMetaObject *metaObject = obj->metaObject();
481 int funcIndex = metaObject->indexOfMethod(methodName);
483 invokeTestMethodIfValid(metaObject->method(funcIndex), obj);
489 const QByteArray env = qgetenv(
"QTEST_EVENT_DELAY");
539static bool qPrintTestSlots(FILE *stream,
const char *filter =
nullptr,
const char *preamble =
"")
541 const auto matches = [filter](
const QByteArray &s) {
542 return !filter || QLatin1StringView(s).contains(QLatin1StringView(filter),
543 Qt::CaseInsensitive);
545 bool matched =
false;
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());
563 QTestLog::setPrintAvailableTagsMode();
566 QTestTable::globalTestTable();
568 const QTestTable *gTable = QTestTable::globalTestTable();
570 const QMetaObject *currTestMetaObj = QTest::currentTestObject->metaObject();
573 for (
int i = 0; i < currTestMetaObj->methodCount(); ++i) {
574 QMetaMethod tf = currTestMetaObj->method(i);
576 if (isValidSlot(tf)) {
579 QStringList localTags;
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());
590 if (gTable->dataCount() == 0) {
591 if (localTags.size() == 0) {
593 std::fprintf(stream,
"%s %s\n", currTestMetaObj->className(), slot.data());
596 for (
int k = 0; k < localTags.size(); ++k)
597 std::fprintf(stream,
"%s %s %s\n",
598 currTestMetaObj->className(),
600 localTags.at(k).toLatin1().data());
603 for (
int j = 0; j < gTable->dataCount(); ++j) {
604 if (localTags.size() == 0) {
606 std::fprintf(stream,
"%s %s __global__ %s\n",
607 currTestMetaObj->className(),
609 gTable->testData(j)->dataTag());
613 for (
int k = 0; k < localTags.size(); ++k)
614 std::fprintf(stream,
"%s %s %s __global__ %s\n",
615 currTestMetaObj->className(),
617 localTags.at(k).toLatin1().data(),
618 gTable->testData(j)->dataTag());
629 int l =
static_cast<
int>(strtol(str, &pEnd, 10));
631 std::fprintf(stderr,
"Invalid numeric parameter: '%s'\n", str);
640 const char *logFilename =
nullptr;
644 QTest::testFunctions.clear();
645 QTest::testTags.clear();
647#if defined(Q_OS_DARWIN) && defined(HAVE_XCTEST)
648 if (QXcodeTestLogger::canLogTestProgress())
649 logFormat = QTestLog::XCTest;
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"
665 " *** Multiple loggers can be specified, but at most one can log to stdout.\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"
677 " *** If no output file is specified, stdout is assumed.\n"
678 " *** If no output format is specified, -txt is assumed.\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"
686 " *** The -silent and -v1 options only affect plain text output.\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"
706 " Benchmarking options:\n"
707#if QT_CONFIG(valgrind)
708 " -callgrind : Use callgrind to time benchmarks\n"
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"
715#ifdef HAVE_TICK_COUNTER
716 " -tickcounter : Use CPU tick counters to time benchmarks\n"
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";
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);
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");
743 " -help : This help\n");
745 }
else if (strcmp(argv[i],
"-functions") == 0) {
752 }
else if (strcmp(argv[i],
"-datatags") == 0) {
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) {
784 std::fprintf(stderr,
"-o needs an extra parameter specifying the filename and optional format\n");
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) {
793 logFilename = argv[i];
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;
814 std::fprintf(stderr,
"output format must be one of txt, csv, lightxml, xml, tap, teamcity or junitxml\n");
817 if (strcmp(filename,
"-") == 0 && QTestLog::loggerUsingStdout()) {
818 std::fprintf(stderr,
"only one logger can log to stdout\n");
821 QTestLog::addLogger(QTestLog::LogMode(logFormat), filename);
825 }
else if (strcmp(argv[i],
"-eventdelay") == 0) {
827 std::fprintf(stderr,
"-eventdelay needs an extra parameter to indicate the delay(ms)\n");
832 }
else if (strcmp(argv[i],
"-keydelay") == 0) {
834 std::fprintf(stderr,
"-keydelay needs an extra parameter to indicate the delay(ms)\n");
839 }
else if (strcmp(argv[i],
"-mousedelay") == 0) {
841 std::fprintf(stderr,
"-mousedelay needs an extra parameter to indicate the delay(ms)\n");
846 }
else if (strcmp(argv[i],
"-maxwarnings") == 0) {
848 std::fprintf(stderr,
"-maxwarnings needs an extra parameter with the amount of warnings\n");
851 QTestLog::setMaxWarnings(qToInt(argv[++i]));
853 }
else if (strcmp(argv[i],
"-repeat") == 0) {
855 std::fprintf(stderr,
"-repeat needs an extra parameter for the number of repetitions\n");
860 }
else if (strcmp(argv[i],
"-nocrashhandler") == 0) {
862 }
else if (strcmp(argv[i],
"-skipblacklisted") == 0) {
864 }
else if (strcmp(argv[i],
"-trytimeout") == 0) {
866 std::fprintf(stderr,
"-trytimeout needs an extra parameter to indicate the timeout(ms)\n");
869 QTest::defaultTryTimeout.store(std::chrono::milliseconds{qToInt(argv[++i])},
870 std::memory_order_relaxed);
872#if QT_CONFIG(valgrind)
873 }
else if (strcmp(argv[i],
"-callgrind") == 0) {
874 if (!QBenchmarkValgrindUtils::haveValgrind()) {
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);
884 "WARNING: Current directory not writable. "
885 "Using the walltime measurer.\n");
887 }
else if (strcmp(argv[i],
"-callgrindchild") == 0) {
888 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::CallgrindChildProcess);
889 QBenchmarkGlobalData::current->callgrindOutFileBase =
890 QBenchmarkValgrindUtils::outFileBase();
892#ifdef QTESTLIB_USE_PERF_EVENTS
893 }
else if (strcmp(argv[i],
"-perf") == 0) {
894 if (QBenchmarkPerfEventsMeasurer::isAvailable()) {
896 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::PerfCounter);
898 std::fprintf(stderr,
"WARNING: Linux perf events not available. Using the walltime measurer.\n");
900 }
else if (strcmp(argv[i],
"-perfcounter") == 0) {
902 std::fprintf(stderr,
"-perfcounter needs an extra parameter with the name of the counter\n");
905 QBenchmarkPerfEventsMeasurer::setCounter(argv[++i]);
907 }
else if (strcmp(argv[i],
"-perfcounterlist") == 0) {
908 QBenchmarkPerfEventsMeasurer::listCounters();
911#ifdef HAVE_TICK_COUNTER
912 }
else if (strcmp(argv[i],
"-tickcounter") == 0) {
913 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::TickCounter);
915 }
else if (strcmp(argv[i],
"-eventcounter") == 0) {
916 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::EventCounter);
917 }
else if (strcmp(argv[i],
"-minimumvalue") == 0) {
919 std::fprintf(stderr,
"-minimumvalue needs an extra parameter to indicate the minimum time(ms)\n");
922 QBenchmarkGlobalData::current->walltimeMinimum = qToInt(argv[++i]);
924 }
else if (strcmp(argv[i],
"-minimumtotal") == 0) {
926 std::fprintf(stderr,
"-minimumtotal needs an extra parameter to indicate the minimum total measurement\n");
929 QBenchmarkGlobalData::current->minimumTotal = qToInt(argv[++i]);
931 }
else if (strcmp(argv[i],
"-iterations") == 0) {
933 std::fprintf(stderr,
"-iterations needs an extra parameter to indicate the number of iterations\n");
936 QBenchmarkGlobalData::current->iterationCount = qToInt(argv[++i]);
938 }
else if (strcmp(argv[i],
"-median") == 0) {
940 std::fprintf(stderr,
"-median needs an extra parameter to indicate the number of median iterations\n");
943 QBenchmarkGlobalData::current->medianIterationCount = qToInt(argv[++i]);
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) {
952# if defined(HAVE_XCTEST)
953 }
else if (
int skip = QXcodeTestLogger::parseCommandLineArgument(argv[i])) {
958 }
else if (argv[i][0] ==
'-') {
959 std::fprintf(stderr,
"Unknown option: '%s'\n\n%s", argv[i], testOptions);
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");
967 std::fprintf(stderr,
"\n"
968 " -help : This help\n");
975 for (offset = 0; argv[i][offset]; ++offset) {
976 if (argv[i][offset] ==
':') {
977 if (argv[i][offset + 1] ==
':') {
988 QTest::testFunctions += QString::fromLatin1(argv[i]);
989 QTest::testTags += QString();
991 QTest::testFunctions += QString::fromLatin1(argv[i], colon);
992 QTest::testTags += QString::fromLatin1(argv[i] + colon + 1);
997 bool installedTestCoverage = installCoverageTool(QTestResult::currentAppName(), QTestResult::currentTestObjectName());
998 QTestLog::setInstalledTestCoverage(installedTestCoverage);
1002 const bool explicitLoggerRequested = logFormat != -1;
1003 if (!QTestLog::hasLoggers() && explicitLoggerRequested)
1004 QTestLog::addLogger(QTestLog::LogMode(logFormat), logFilename);
1006 bool addFallbackLogger = !explicitLoggerRequested;
1008#if defined(QT_USE_APPLE_UNIFIED_LOGGING)
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;
1018 if (addFallbackLogger)
1019 QTestLog::addLogger(QTestLog::Plain, logFilename);
1021 if (repetitions != 1 && !QTestLog::isRepeatSupported()) {
1022 std::fprintf(stderr,
"-repeat is only supported with plain text logger\n");
1029 qtest_qParseArgs(argc,
const_cast<
const char *
const *>(argv), qml);
1034 const int count = container.size();
1039 return container.front();
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();
1047 const int middle = count / 2;
1050 return containerCopy.at(middle);
1057 QTestResult::setCurrentTestData(data);
1061 QTestResult::setCurrentTestData(
nullptr);
1065void TestMethods::invokeTestOnData(
int index)
const
1069 bool isBenchmark =
false;
1070 int i = (QBenchmarkGlobalData::current->measurer->needsWarmupIteration()) ? -1 : 0;
1072 QList<QList<QBenchmarkResult>> resultsList;
1073 bool minimumTotalReached =
false;
1075 QBenchmarkTestMethodData::current->beginDataRun();
1077 QBenchmarkTestMethodData::current->iterationCount = 1;
1083 invokeTestMethodIfValid(m_initMethod);
1085 const bool initQuit = QTest::currentTestResolved();
1087 QBenchmarkTestMethodData::current->results.clear();
1088 QBenchmarkTestMethodData::current->resultAccepted =
false;
1089 QBenchmarkTestMethodData::current->valid =
false;
1091 QBenchmarkGlobalData::current->context.tag = QLatin1StringView(
1092 QTestResult::currentDataTag() ? QTestResult::currentDataTag() :
"");
1094 invokeOk = invokeTestMethodIfValid(m_methods[index]);
1096 QTestResult::addFailure(
"Unable to execute slot", __FILE__, __LINE__);
1098 isBenchmark = QBenchmarkTestMethodData::current->isBenchmark();
1104 QTestResult::finishedCurrentTestData();
1107 invokeTestMethodIfValid(m_cleanupMethod);
1111 if (QCoreApplication::instance())
1112 QCoreApplication::sendPostedEvents(
nullptr, QEvent::DeferredDelete);
1117 QTestResult::finishedCurrentTestDataCleanup();
1123 }
while (invokeOk && !QTest::currentTestResolved() && isBenchmark
1124 && !QBenchmarkTestMethodData::current->resultsAccepted());
1126 QBenchmarkTestMethodData::current->endDataRun();
1127 if (!QTest::currentTestResolved()) {
1129 resultsList.append(QBenchmarkTestMethodData::current->results);
1131 if (isBenchmark && QBenchmarkGlobalData::current->verboseOutput &&
1132 !QBenchmarkTestMethodData::current->results.isEmpty()) {
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)),
1145 if (QBenchmarkGlobalData::current->minimumTotal == -1) {
1146 minimumTotalReached =
true;
1148 auto addResult = [](qreal current,
const QList<QBenchmarkResult> &r) {
1150 current += r.first().measurement.value;
1153 const qreal total =
std::accumulate(resultsList.begin(), resultsList.end(), 0.0, addResult);
1154 minimumTotalReached = (total >= QBenchmarkGlobalData::current->minimumTotal);
1156 }
while (isBenchmark && !QTest::currentTestResolved()
1157 && (++i < QBenchmarkGlobalData::current->adjustMedianIterationCount()
1159 || !minimumTotalReached));
1163 bool testPassed = !QTest::currentTestResolved();
1164 QTestResult::finishedCurrentTestDataCleanup();
1166 if (testPassed && QBenchmarkTestMethodData::current->resultsAccepted())
1167 QTestLog::addBenchmarkResults(qMedian(resultsList));
1171#if QT_CONFIG(thread)
1268 qFatal(
"Test function timed out");
1291template <
typename Functor>
1295 watchDog->beginTest();
1300 watchDog->testFinished();
1304 const QTestTable &lTable,
const QTestTable &gTable)
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());
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());
1319 if (localDataCount == 0 && globalDataCount == 0)
1320 std::fputs(
"Function has no data tags\n", stderr);
1324
1325
1326
1327
1328
1331 QBenchmarkTestMethodData benchmarkData;
1332 QBenchmarkTestMethodData::current = &benchmarkData;
1334 const QByteArray &name = m_methods[index].name();
1335 QBenchmarkGlobalData::current->context.slotName = QLatin1StringView(name) +
"()"_L1;
1340 QTestResult::setCurrentTestFunction(name.constData());
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;
1349 const auto dataTagMatches = [](QLatin1StringView tag, QLatin1StringView local,
1350 QLatin1StringView global) {
1353 if (tag == local || tag == global)
1356 return tag.startsWith(global) && tag.endsWith(local) &&
1357 tag.size() == global.size() + 1 + local.size() &&
1358 tag[global.size()] ==
':';
1360 bool foundFunction =
false;
1361 bool blacklisted =
false;
1365 if (!gTable->isEmpty())
1366 QTestResult::setCurrentGlobalTestData(gTable->testData(curGlobalDataIndex));
1368 if (curGlobalDataIndex == 0) {
1369 std::snprintf(member, 512,
"%s_data()", name.constData());
1370 runWithWatchdog(watchDog, [&member] {
1373 if (QTestResult::skipCurrentTest())
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;
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));
1393 QTestResult::setBlacklistCurrentTest(
true);
1396 QTest::qSkip(
"Skipping blacklisted test since -skipblacklisted option is set.",
1398 QTestResult::finishedCurrentTestData();
1399 QTestResult::finishedCurrentTestDataCleanup();
1402 curDataIndex >= dataCount ?
nullptr : table.testData(curDataIndex));
1404 QTestPrivate::qtestMouseButtons = Qt::NoButton;
1410 runWithWatchdog(watchDog, [
this, index] {
1411 invokeTestOnData(index);
1415 if (!tag.isEmpty() && !globalDataCount)
1419 }
while (curDataIndex < dataCount);
1421 QTestResult::setCurrentGlobalTestData(
nullptr);
1422 ++curGlobalDataIndex;
1423 }
while (curGlobalDataIndex < globalDataCount);
1425 if (!tag.isEmpty() && !foundFunction) {
1426 printUnknownDataTagError(QLatin1StringView(name), tag, table, *gTable);
1427 QTestResult::addFailure(qPrintable(
"Data tag not found: %1"_L1.arg(tag)));
1429 QTestResult::finishedCurrentTestFunction();
1430 QTestResult::setSkipCurrentTest(
false);
1431 QTestResult::setBlacklistCurrentTest(
false);
1434void *
fetchData(QTestData *data,
const char *tagName,
int typeId)
1436 QTEST_ASSERT(typeId);
1437 QTEST_ASSERT_X(data,
"QTest::fetchData()",
"Test data requested, but no testdata available.");
1438 QTEST_ASSERT(data->parent());
1440 int idx = data->parent()->indexOf(tagName);
1442 if (Q_UNLIKELY(idx == -1 || idx >= data->dataCount())) {
1443 qFatal(
"QFETCH: Requested testdata '%s' not available, check your _data function.",
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());
1453 return data->data(idx);
1457
1458
1459char *
formatString(
const char *prefix,
const char *suffix, size_t numArguments, ...)
1462 va_start(ap, numArguments);
1464 QByteArray arguments;
1465 arguments += prefix;
1467 if (numArguments > 0) {
1468 arguments += va_arg(ap,
const char *);
1470 for (size_t i = 1; i < numArguments; ++i) {
1472 arguments += va_arg(ap,
const char *);
1477 arguments += suffix;
1478 return qstrdup(arguments.constData());
1482
1483
1484
1485
1486
1487
1488
1489
1490
1497
1498
1499
1500
1501
1502
1503 const qsizetype maxLen = 50;
1504 const qsizetype len = qMin(maxLen, length);
1505 char *result =
nullptr;
1507 if (length > maxLen) {
1508 const qsizetype size = len * 3 + 4;
1509 result =
new char[size];
1511 char *
const forElipsis = result + size - 5;
1512 forElipsis[0] =
' ';
1513 forElipsis[1] =
'.';
1514 forElipsis[2] =
'.';
1515 forElipsis[3] =
'.';
1516 result[size - 1] =
'\0';
1519 const qsizetype size = len * 3;
1520 result =
new char[size];
1521 result[size - 1] =
'\0';
1528 const char at = ba[i];
1530 result[o] = toHexUpper(at >> 4);
1532 result[o] = toHexUpper(at);
1546
1547
1548
1549
1552 bool trimmed =
false;
1553 auto buffer =
std::make_unique<
char[]>(256);
1554 const char *end = p + length;
1555 char *dst = buffer.get();
1557 bool lastWasHexEscape =
false;
1559 for ( ; p != end; ++p) {
1565 if (dst - buffer.get() > 246) {
1572 if (Q_UNLIKELY(lastWasHexEscape)) {
1573 if (fromHex(*p) != -1) {
1578 lastWasHexEscape =
false;
1581 if (*p < 0x7f && *p >= 0x20 && *p !=
'\\' && *p !=
'"') {
1612 *dst++ = toHexUpper(uchar(*p) >> 4);
1613 *dst++ = toHexUpper(uchar(*p));
1614 lastWasHexEscape =
true;
1626 return buffer.release();
1630
1631
1632
1633
1634
1635
1636
1645 auto first = [&](
int n) { Q_ASSERT(dst - buffer == n);
return dst; };
1646 if (ch < 0x7f && ch >= 0x20 && ch !=
'\\' && ch !=
'"') {
1675 *dst++ = toHexUpper(ch >> 12);
1676 *dst++ = toHexUpper(ch >> 8);
1677 *dst++ = toHexUpper(ch >> 4);
1678 *dst++ = toHexUpper(ch);
1686 auto p = string.utf16();
1687 auto length = string.size();
1689 bool trimmed =
false;
1690 auto buffer =
std::make_unique<
char[]>(PrettyUnicodeMaxOutputSize);
1691 const auto end = p + length;
1692 char *dst = buffer.get();
1695 for ( ; p != end; ++p) {
1696 if (dst - buffer.get() > PrettyUnicodeMaxOutputSize - PrettyUnicodeMaxIncrement) {
1700 dst = writePrettyUnicodeChar(*p, dst);
1710 return buffer.release();
1715 const QMetaObject *metaObject = testObject->metaObject();
1716 QTEST_ASSERT(metaObject);
1719 if (!CrashHandler::alreadyDebugging()
1720#if QT_CONFIG(valgrind)
1721 && QBenchmarkGlobalData::current->mode() != QBenchmarkGlobalData::CallgrindChildProcess
1727 QTestResult::setCurrentTestFunction(
"initTestCase");
1728 runWithWatchdog(watchDog, [
this, testObject] {
1729 invokeTestMethodIfValid(m_initTestCaseDataMethod, testObject);
1732 QSignalDumper::startDump();
1734 if (!QTest::currentTestResolved()) {
1736 runWithWatchdog(watchDog, [
this, testObject] {
1737 invokeTestMethodIfValid(m_initTestCaseMethod, testObject);
1741 const bool previousFailed = QTestResult::currentTestFailed();
1742 QTestResult::finishedCurrentTestData();
1743 QTestResult::finishedCurrentTestDataCleanup();
1744 QTestResult::finishedCurrentTestFunction();
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);
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);
1764 QTestResult::finishedCurrentTestData();
1766 QTestResult::setSkipCurrentTest(wasSkipped || QTestResult::skipCurrentTest());
1767 QTestResult::finishedCurrentTestDataCleanup();
1769 QTestResult::finishedCurrentTestFunction();
1770 QTestResult::setCurrentTestFunction(
nullptr);
1772 QSignalDumper::endDump();
1775#if QT_DEPRECATED_SINCE(6
, 8
)
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)
1799 return QTestResult::reportResult(success, lhs, rhs, lhsFormatter, rhsFormatter,
1800 lhsExpr, rhsExpr, op, file, line);
1806 Q_CONSTINIT
static std::atomic_flag terminationLatch = ATOMIC_FLAG_INIT;
1807 if (terminationLatch.test_and_set(std::memory_order_relaxed)) {
1810 qSleep(std::chrono::milliseconds::max());
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);
1824 const std::terminate_handler next = oldTerminateHandler;
1833 qputenv(
"QT_QTESTLIB_RUNNING",
"1");
1837static QFile androidExitCodeFile()
1839 const QString testHome = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
1840 return QFile(testHome +
"/qtest_last_exit_code"_L1);
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1883int QTest::qExec(QObject *testObject,
int argc,
char **argv)
1889 qInit(testObject, argc, argv);
1893#if defined(Q_OS_WASM)
1895 if (
typeof Module !=
"undefined" &&
typeof Module.notifyTestFinished !=
"undefined")
1896 Module.notifyTestFinished($0);
1904
1905void QTest::qInit(QObject *testObject,
int argc,
char **argv)
1908 CrashHandler::maybeDisableCoreDump();
1909 QBenchmarkGlobalData::current =
new QBenchmarkGlobalData;
1911#if defined(Q_OS_MACOS)
1913 QTestPrivate::disableWindowRestore();
1916 if (!appNapDisabler)
1917 appNapDisabler.emplace();
1919 IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
1920 kIOPMAssertionLevelOn, CFSTR(
"QtTest running tests"),
1921 &macPowerSavingDisabled);
1924 QTestPrivate::parseBlackList();
1925 QTestResult::reset();
1927 QTEST_ASSERT(testObject);
1928 QTEST_ASSERT(!currentTestObject);
1931 const QMetaObject *metaObject = testObject->metaObject();
1932 QTEST_ASSERT(metaObject);
1934 QTestResult::setCurrentTestObject(metaObject->className());
1936 QTestResult::setCurrentAppName(argv[0]);
1940#if QT_CONFIG(valgrind)
1941 if (QBenchmarkGlobalData::current->mode() != QBenchmarkGlobalData::CallgrindParentProcess)
1943 QTestLog::startLogging();
1946 androidExitCodeFile().remove();
1949 oldTerminateHandler = std::get_terminate();
1954
1957 QTEST_ASSERT(currentTestObject);
1959#if QT_CONFIG(valgrind)
1960 int callgrindChildExitCode = 0;
1963#if defined(Q_OS_WIN) && !defined(QT_NO_EXCEPTIONS)
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");
1973 const QStringList origAppArgs(QCoreApplication::arguments());
1974 if (!QBenchmarkValgrindUtils::rerunThroughCallgrind(origAppArgs, callgrindChildExitCode))
1977 QBenchmarkValgrindUtils::cleanup();
1982 std::optional<CrashHandler::FatalSignalHandler> handler;
1983 CrashHandler::prepareStackTrace();
1987 TestMethods::MetaMethods commandLineMethods;
1988 commandLineMethods.reserve(
static_cast<size_t>(QTest::testFunctions.size()));
1989 std::vector<size_t> badFunctionIndices;
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);
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();
2005 badFunctionIndices.insert(badFunctionIndices.begin(), index);
2009 if (badFunctionIndices.size() > 0) {
2011 std::fprintf(stderr,
"\n%s -functions\nlists all available test functions.\n\n",
2012 QTestResult::currentAppName());
2013 if (commandLineMethods.empty())
2019 for (size_t i : std::as_const(badFunctionIndices)) {
2026 QTest::testFunctions.removeAt(i);
2027 QTest::testTags.removeAt(i);
2035 const int badArgCount = QTestLog::failCount();
2036 while (!(QTestLog::failCount() > badArgCount)
2037 && (repeatForever || remainingRepetitions-- > 0)) {
2038 QTestTable::globalTestTable();
2039 test.invokeTests(currentTestObject);
2040 QTestTable::clearGlobalTestTable();
2044#if defined(Q_OS_WIN) && !defined(QT_NO_EXCEPTIONS)
2046 QTestResult::addFailure(
"Caught unhandled exception", __FILE__, __LINE__);
2047 if (QTestResult::currentTestFunction()) {
2048 QTestResult::finishedCurrentTestFunction();
2049 QTestResult::setCurrentTestFunction(
nullptr);
2060#if QT_CONFIG(valgrind)
2061 if (QBenchmarkGlobalData::current->mode() == QBenchmarkGlobalData::CallgrindParentProcess)
2062 return callgrindChildExitCode;
2066 const int exitCode = qMin(QTestLog::failCount(), 127);
2069 QFile exitCodeFile = androidExitCodeFile();
2070 if (exitCodeFile.open(QIODevice::WriteOnly)) {
2071 exitCodeFile.write(qPrintable(QString::number(exitCode)));
2073 qWarning(
"Failed to open %s for writing test exit code: %s",
2074 qPrintable(exitCodeFile.fileName()), qPrintable(exitCodeFile.errorString()));
2082
2086 std::set_terminate(oldTerminateHandler);
2087 oldTerminateHandler =
nullptr;
2090#if QT_CONFIG(valgrind)
2091 if (QBenchmarkGlobalData::current->mode() != QBenchmarkGlobalData::CallgrindParentProcess)
2093 QTestLog::stopLogging();
2095 delete QBenchmarkGlobalData::current;
2096 QBenchmarkGlobalData::current =
nullptr;
2098#if defined(Q_OS_MACOS)
2099 IOPMAssertionRelease(macPowerSavingDisabled);
2100 appNapDisabler = std::nullopt;
2104#if QT_CONFIG(batch_test_support) || defined(Q_QDOC)
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115void QTest::qRegisterTestCase(
const QString &name, TestEntryFunction entryFunction)
2117 QTest::TestRegistry::instance()->registerTest(name, entryFunction);
2120QList<QString> QTest::qGetTestCaseNames()
2122 return QTest::TestRegistry::instance()->getAllTestNames();
2125QTest::TestEntryFunction QTest::qGetTestCaseEntryFunction(
const QString& name)
2127 return QTest::TestRegistry::instance()->getTestEntryFunction(name);
2133
2134
2135
2136
2137
2138
2139int QTest::qExec(QObject *testObject,
const QStringList &arguments)
2141 const int argc = arguments.size();
2142 QVarLengthArray<
char *> argv(argc);
2144 QList<QByteArray> args;
2147 for (
int i = 0; i < argc; ++i)
2149 args.append(arguments.at(i).toLocal8Bit().constData());
2150 argv[i] = args.last().data();
2153 return qExec(testObject, argc, argv.data());
2157
2158void QTest::
qFail(
const char *message,
const char *file,
int line)
2160 QTestResult::fail(message, file, line);
2164
2165bool QTest::
qVerify(
bool statement,
const char *statementStr,
const char *description,
2166 const char *file,
int line)
2168 return QTestResult::verify(statement, statementStr, description, file, line);
2172
2173
2174void QTest::
qSkip(
const char *message,
const char *file,
int line)
2176 QTestResult::addSkip(message, file, line);
2177 QTestResult::setSkipCurrentTest(
true);
2181
2182
2184 QTest::TestFailMode mode,
const char *file,
int line)
2186 return QTestResult::expectFail(dataIndex, qstrdup(comment), mode, file, line);
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205void QTest::
qCaught(
const char *expected,
const char *what,
const char *file,
int line)
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 :
""; };
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));
2219 qFail(message().toUtf8().constData(), file, line);
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2245 std::rethrow_exception(
std::current_exception());
2246 }
catch (
const std::exception &e) {
2247 qCaught(expected, e.what(), file, line);
2249 qCaught(expected,
nullptr, file, line);
2256#if QT_DEPRECATED_SINCE(6
, 3
)
2258
2259
2260
2261void QTest::qWarn(
const char *message,
const char *file,
int line)
2263 QTestLog::warn(message, file, line);
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2287 QTestLog::ignoreMessage(type, message);
2290#if QT_CONFIG(regularexpression)
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306void QTest::ignoreMessage(QtMsgType type,
const QRegularExpression &messagePattern)
2308 QTestLog::ignoreMessage(type, messagePattern);
2313
2314
2316
2317
2318
2319
2322 return QTestLog::failOnWarning();
2326
2327
2329
2330
2331
2332
2335 return QTestLog::failOnWarning(message);
2338#if QT_CONFIG(regularexpression)
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391void QTest::failOnWarning(
const QRegularExpression &messagePattern)
2393 QTestLog::failOnWarning(messagePattern);
2398
2401static inline bool isWindowsBuildDirectory(
const QString &dirName)
2403 return dirName.compare(
"Debug"_L1, Qt::CaseInsensitive) == 0
2404 || dirName.compare(
"Release"_L1, Qt::CaseInsensitive) == 0;
2408#if QT_CONFIG(temporaryfile)
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419QSharedPointer<QTemporaryDir> QTest::qExtractTestData(
const QString &dirName)
2421 QSharedPointer<QTemporaryDir> result;
2423 QSharedPointer<QTemporaryDir> tempDir = QSharedPointer<QTemporaryDir>::create();
2425 tempDir->setAutoRemove(
true);
2427 if (!tempDir->isValid())
2430 const QString dataPath = tempDir->path();
2431 const QString resourcePath = u':' + dirName;
2432 const QFileInfo fileInfo(resourcePath);
2434 if (!fileInfo.isDir()) {
2435 qWarning(
"Resource path '%s' is not a directory.", qPrintable(resourcePath));
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()));
2457 if (isResourceDirEmpty) {
2458 qWarning(
"Resource directory '%s' is empty.", qPrintable(resourcePath));
2462 result = std::move(tempDir);
2469
2471QString
QTest::qFindTestData(
const QString& base,
const char *file,
int line,
const char *builddir,
2472 const char *sourcedir)
2480 QDir binDirectory(QCoreApplication::applicationDirPath());
2481 if (binDirectory.exists(base)) {
2482 found = binDirectory.absoluteFilePath(base);
2487 else if (isWindowsBuildDirectory(binDirectory.dirName())
2488 && binDirectory.cdUp() && binDirectory.exists(base)) {
2489 found = binDirectory.absoluteFilePath(base);
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)),
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)) {
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))),
2521 if (found.isEmpty() && qstrncmp(file,
":/", 2) != 0) {
2523 QFileInfo srcdir(QFileInfo(QFile::decodeName(file)).path());
2527 if (!srcdir.isAbsolute() && builddir)
2528 srcdir.setFile(QFile::decodeName(builddir) + u'/' + srcdir.filePath());
2530 const QString canonicalPath = srcdir.canonicalFilePath();
2531 const QString candidate =
"%1/%2"_L1.arg(canonicalPath, base);
2532 if (!canonicalPath.isEmpty() && QFileInfo::exists(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))),
2543 if (found.isEmpty()) {
2544 const QString candidate =
":/%1"_L1.arg(base);
2545 if (QFileInfo::exists(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))),
2556 if (found.isEmpty()) {
2557 const QString candidate = QDir::currentPath() + u'/' + base;
2558 if (QFileInfo::exists(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))),
2569 if (found.isEmpty()) {
2570 const QString candidate = QTest::mainSourcePath % u'/' % base;
2571 if (QFileInfo::exists(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))),
2582 if (found.isEmpty() && sourcedir) {
2583 const QString candidate = QFile::decodeName(sourcedir) % u'/' % base;
2584 if (QFileInfo::exists(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))),
2595 if (found.isEmpty()) {
2596 QTestLog::warn(qPrintable(
2597 "testdata %1 could not be located!"_L1.arg(base)),
2599 }
else if (QTestLog::verboseLevel() >= 1) {
2600 QTestLog::info(qPrintable(
2601 "testdata %1 was located at %2"_L1.arg(base, QDir::toNativeSeparators(found))),
2609
2610QString
QTest::qFindTestData(
const char *base,
const char *file,
int line,
const char *builddir,
2611 const char *sourcedir)
2613 return qFindTestData(QFile::decodeName(base), file, line, builddir, sourcedir);
2617
2620 return fetchData(QTestResult::currentTestData(), tagName, typeId);
2624
2627 return fetchData(QTestResult::currentGlobalTestData(), tagName, typeId);
2631
2634 QTEST_ASSERT(tagName);
2635 QTestData *data = QTestResult::currentTestData();
2637 QTEST_ASSERT(data->parent());
2639 int idx = data->parent()->indexOf(tagName);
2640 QTEST_ASSERT(idx != -1);
2641 QTEST_ASSERT(data->parent()->elementTypeId(idx) == metaTypeId);
2643 return data->data(data->parent()->indexOf(tagName));
2647
2650 QTestTable *tbl = QTestTable::currentTestTable();
2651 QTEST_ASSERT_X(tbl,
"QTest::addColumn()",
"Cannot add testdata outside of a _data slot.");
2653 tbl->addColumn(id, name);
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676QTestData &
QTest::newRow(
const char *dataTag)
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.");
2684 return *tbl->newData(dataTag);
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714QTestData &
QTest::addRow(
const char *format, ...)
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.");
2725 va_start(va, format);
2728 std::vsnprintf(buf,
sizeof buf, format, va);
2731 return *tbl->newData(buf);
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2756
2757
2760 return QTestResult::currentAppName();
2764
2765
2766
2767
2768
2769
2772 return QTestResult::currentTestFunction();
2776
2777
2778
2781 return QTestResult::currentDataTag();
2785
2786
2787
2788
2789
2792 return QTestResult::currentGlobalDataTag();
2796
2797
2798
2799
2802 return QTestResult::currentTestFailed();
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2820 return QTestResult::currentTestFailed() || QTestResult::skipCurrentTest();
2824
2825
2826
2827
2828
2829
2830
2837
2840 return currentTestObject;
2844
2847 QString mainSourceFile = QFile::decodeName(file);
2850 fi.setFile(QDir(QFile::decodeName(builddir)), mainSourceFile);
2852 fi.setFile(mainSourceFile);
2856#if QT_DEPRECATED_SINCE(6
, 4
)
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
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)
2880 return QTestResult::compare(success, failureMsg, actualVal, expectedVal,
2881 actual, expected, file, line);
2885#if QT_DEPRECATED_SINCE(6
, 8
)
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
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)
2905 return QTestResult::reportResult(success, &actualVal, &expectedVal,
2906 QTest::functionRefFormatter,
2907 QTest::functionRefFormatter, actual, expected,
2908 QTest::ComparisonOperation::CustomCompare,
2909 file, line, failureMsg);
2914
2915
2916
2917
2918
2919
2920
2921
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)
2930 return QTestResult::reportResult(success, actualPtr, expectedPtr,
2931 actualFormatter, expectedFormatter,
2933 QTest::ComparisonOperation::CustomCompare,
2934 file, line, failureMsg);
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
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)
2976 return QTestResult::report3WayResult(success, failureMsg,
2978 lhsFormatter, rhsFormatter,
2979 lhsExpression, rhsExpression,
2980 actualOrderFormatter,
2981 expectedOrderFormatter,
2982 actualOrderPtr, expectedOrderPtr,
2988
2989
2990
2991
2992
2993
2994
2995
2996
2998 const char *expected,
const char *file,
int line)
3000 return QTestResult::compare(success, failureMsg, actual, expected, file, line);
3003template <
typename T>
3006 switch (qFpClassify(expected))
3009 return (expected < 0) == (actual < 0) && qFpClassify(actual) == FP_INFINITE;
3011 return qFpClassify(actual) == FP_NAN;
3013 if (!qFuzzyIsNull(expected))
3014 return qFuzzyCompare(actual, expected);
3018 return qFuzzyIsNull(actual);
3023
3024
3025bool QTest::
qCompare(qfloat16
const &t1, qfloat16
const &t2,
const char *actual,
const char *expected,
3026 const char *file,
int line)
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);
3036
3037
3038bool QTest::
qCompare(
float const &t1,
float const &t2,
const char *actual,
const char *expected,
3039 const char *file,
int line)
3041 return QTestResult::compare(floatingCompare(t1, t2),
3042 "Compared floats are not the same (fuzzy compare)",
3043 t1, t2, actual, expected, file, line);
3047
3048
3049bool QTest::
qCompare(
double const &t1,
double const &t2,
const char *actual,
const char *expected,
3050 const char *file,
int line)
3052 return QTestResult::compare(floatingCompare(t1, t2),
3053 "Compared doubles are not the same (fuzzy compare)",
3054 t1, t2, actual, expected, file, line);
3058
3059
3060
3062 const char *file,
int line)
3064 return QTestResult::compare(t1 == t2,
3065 "Compared values are not the same",
3066 t1, t2, actual, expected, file, line);
3069#if QT_POINTER_SIZE == 8
3071
3072
3073
3075bool QTest::qCompare(qsizetype t1, qsizetype t2,
const char *actual,
const char *expected,
3076 const char *file,
int line)
3078 return QTestResult::compare(t1 == t2,
3079 "Compared values are not the same",
3080 t1, t2, actual, expected, file, line);
3085
3086
3087
3088bool QTest::
qCompare(
unsigned t1,
unsigned t2,
const char *actual,
const char *expected,
3089 const char *file,
int line)
3091 return QTestResult::compare(t1 == t2,
3092 "Compared values are not the same",
3093 t1, t2, actual, expected, file, line);
3097
3098
3099
3100bool QTest::
qCompare(QStringView t1, QStringView t2,
const char *actual,
const char *expected,
3101 const char *file,
int line)
3103 return QTestResult::compare(t1 == t2,
3104 "Compared values are not the same",
3105 t1, t2, actual, expected, file, line);
3109
3110
3111
3112bool QTest::
qCompare(QStringView t1,
const QLatin1StringView &t2,
const char *actual,
const char *expected,
3113 const char *file,
int line)
3115 return QTestResult::compare(t1 == t2,
3116 "Compared values are not the same",
3117 t1, t2, actual, expected, file, line);
3121
3122
3123
3124bool QTest::
qCompare(
const QLatin1StringView &t1, QStringView t2,
const char *actual,
const char *expected,
3125 const char *file,
int line)
3127 return QTestResult::compare(t1 == t2,
3128 "Compared values are not the same",
3129 t1, t2, actual, expected, file, line);
3133
3134
3135
3138
3139
3140
3143
3144
3145
3148
3149
3152
3153
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);
3161}
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;
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);
3200 char *msg =
new char[128];
3201 bool negative = signbit(t);
3203 switch (qFpClassify(t)) {
3205 qstrncpy(msg, (negative ?
"-inf" :
"inf"), 128);
3208 if (
auto r = decodeNanPayload(t); r.payload) {
3209 std::snprintf(msg, 128,
"%s%snan(%#llx)",
3210 negative ?
"-" :
"", r.isQuiet ?
"" :
"s", r.payload);
3212 Q_ASSERT(r.isQuiet);
3213 qstrncpy(msg, (negative ?
"-nan" :
"nan"), 128);
3217 qstrncpy(msg, (negative ?
"-0 (-0x0p+0)" :
"0 (0x0p+0)"), 128);
3220 std::snprintf(msg, 128,
"%.*g (%a)",
std::numeric_limits<T>::digits10 + 1,
double(t),
3227#define TO_STRING_FLOAT(TYPE) template
3228 <> Q_TESTLIB_EXPORT char *QTest::toString<TYPE>(const TYPE &t) \
3229{
3230 return toStringFp(t); \
3231}
3238 unsigned char c =
static_cast<
unsigned char>(t);
3239 char *msg =
new char[16];
3242 qstrcpy(msg,
"'\\0'");
3245 qstrcpy(msg,
"'\\a'");
3248 qstrcpy(msg,
"'\\b'");
3251 qstrcpy(msg,
"'\\t'");
3254 qstrcpy(msg,
"'\\n'");
3257 qstrcpy(msg,
"'\\v'");
3260 qstrcpy(msg,
"'\\f'");
3263 qstrcpy(msg,
"'\\r'");
3266 qstrcpy(msg,
"'\\\"'");
3269 qstrcpy(msg,
"'\\\''");
3272 qstrcpy(msg,
"'\\\\'");
3275 if (c < 0x20 || c >= 0x7F)
3276 std::snprintf(msg, 16,
"'\\x%02x'", c);
3278 std::snprintf(msg, 16,
"'%c'" , c);
3284
3288 char *msg =
new char[1];
3292 char *msg =
new char[strlen(str) + 1];
3293 return qstrcpy(msg, str);
3297
3300 char *msg =
new char[128];
3301 std::snprintf(msg, 128,
"%p", p);
3306
3310 return qstrdup(
"<null>");
3312 return QTest::toString(
const_cast<
const QObject*>(vo));
3316
3320 return qstrdup(
"<null>");
3322 const QString &name = o->objectName();
3323 const char *className = o->metaObject()->className();
3324 char *msg =
new char[256];
3326 std::snprintf(msg, 256,
"%s/%p", className, o);
3328 std::snprintf(msg, 256,
"%s/\"%s\"", className, qPrintable(name));
3334
3335
3338
3339
3342
3343
3346
3347
3350
3351
3354
3355
3358
3360 const char *expected,
const char *file,
int line)
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);
3369
3370
3371
3374
3375
3378
3379
3382
3383
3386
3387
3390
3391
3394
3395
3398
3399
3402
3403
3406
3407
3410
3411
3414
3415
3418
3419
3422
3423
3426
3427
3430
3431
3434
3435
3438
3439
3442
3443
3446
3447
3450
3451
3454
3455
3458
3459
3462
3463
3466
3467
3470
3471
3474
3475
3478
3479
3482
3483
3486
3487
3490
3491
3494
3495
3498
3499
3502
3503
3506
3507
3510
3511
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 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 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)
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 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)
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 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)