class QTest

The QTest namespace contains all the functions and declarations that are related to Qt Test. More

Synopsis

Static functions

Note

This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE

Detailed Description

See the Qt Test Overview for information about how to write unit tests.

class TestFailMode

This enum describes the modes for handling a check, such as by QVERIFY() or QCOMPARE() macros, that is known to fail. The mode applies regardless of whether the check fails or succeeds.

Constant

Description

QTest.Abort

Aborts the execution of the test. Use this mode when it doesn’t make sense to execute the test any further after the problematic check.

QTest.Continue

Continues execution of the test after the problematic check.

See also

QEXPECT_FAIL()

class ComparisonOperation

Added in version 6.4.

class QBenchmarkMetric

This enum lists all the things that can be benchmarked.

Constant

Description

QTest.FramesPerSecond

Frames per second

QTest.BitsPerSecond

Bits per second

QTest.BytesPerSecond

Bytes per second

QTest.WalltimeMilliseconds

Clock time in milliseconds

QTest.WalltimeNanoseconds

Clock time in nanoseconds

QTest.BytesAllocated

Memory usage in bytes

QTest.Events

Event count

QTest.CPUTicks

CPU time

QTest.CPUMigrations

Process migrations between CPUs

QTest.CPUCycles

CPU cycles

QTest.RefCPUCycles

Reference CPU cycles

QTest.BusCycles

Bus cycles

QTest.StalledCycles

Cycles stalled

QTest.InstructionReads

Instruction reads

QTest.Instructions

Instructions executed

QTest.BranchInstructions

Branch-type instructions

QTest.BranchMisses

Branch instructions that were mispredicted

QTest.CacheReferences

Cache accesses of any type

QTest.CacheMisses

Cache misses of any type

QTest.CacheReads

Cache reads / loads

QTest.CacheReadMisses

Cache read / load misses

QTest.CacheWrites

Cache writes / stores

QTest.CacheWriteMisses

Cache write / store misses

QTest.CachePrefetches

Cache prefetches

QTest.CachePrefetchMisses

Cache prefetch misses

QTest.ContextSwitches

Context switches

QTest.PageFaults

Page faults of any type

QTest.MinorPageFaults

Minor page faults

QTest.MajorPageFaults

Major page faults

QTest.AlignmentFaults

Faults caused due to misalignment

QTest.EmulationFaults

Faults that needed software emulation

Note that WalltimeNanoseconds and BytesAllocated are only provided for use via setBenchmarkResult() , and results in those metrics are not able to be provided automatically by the QTest framework.

See also

benchmarkMetricName() benchmarkMetricUnit()

Added in version 4.7.

static addColumnInternal(id, name)
Parameters:
  • id – int

  • name – str

static asciiToKey(ascii)
Parameters:

ascii – int

Return type:

Key

static compare_ptr_helper(t1, t2, actual, expected, file, line)
Parameters:
  • t1QObject

  • t2QObject

  • actual – str

  • expected – str

  • file – str

  • line – int

Return type:

bool

static compare_ptr_helper(t1, t2, actual, expected, file, line)
Parameters:
  • t1void

  • t2void

  • actual – str

  • expected – str

  • file – str

  • line – int

Return type:

bool

static compare_string_helper(t1, t2, actual, expected, file, line)
Parameters:
  • t1 – str

  • t2 – str

  • actual – str

  • expected – str

  • file – str

  • line – int

Return type:

bool

static currentAppName()
Return type:

str

Returns the name of the binary that is currently executed.

static currentDataTag()
Return type:

str

Returns the name of the current test data. If the test doesn’t have any assigned testdata, the function returns None.

static currentTestFailed()
Return type:

bool

Returns true if the current test function has failed, otherwise false.

static currentTestFunction()
Return type:

str

Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Returns the name of the test function that is currently executed.

Example:

def cleanup(self):

    if qstrcmp(QTest.currentTestFunction(), "myDatabaseTest") == 0:
        # clean up all database connections
        closeAllDatabases()
static currentTestResolved()
Return type:

bool

Returns true if the current test function has failed or skipped.

This applies if the test has failed or exercised a skip. When it is true, the test function should return early. In particular, the QTRY_* macros and the test event loop terminate their loops early if executed during the test function (but not its cleanup()). After a test has called a helper function that uses this module’s macros, it can use this function to test whether to return early.

static failOnWarning()

This function overloads failOnWarning().

Appends a test failure to the test log if any warning is output.

See also

failOnWarning()

static failOnWarning(messagePattern)
Parameters:

messagePatternQRegularExpression

Appends a test failure to the test log for each warning that matches messagePattern.

The test function will continue execution when a failure is added. To abort the test instead, you can check currentTestFailed() and return early if it’s true.

For each warning, the first pattern that matches will cause a failure, and the remaining patterns will be ignored.

All patterns are cleared at the end of each test function.

void FileTest::loadFiles()
{
    QTest::failOnWarning(QRegularExpression("^Failed to load"));

    // Each of these will cause a test failure:
    qWarning() << "Failed to load image";
    qWarning() << "Failed to load video";
}

To fail every test that triggers a given warning, pass a suitable regular expression to this function in init() :

void FileTest::init()
{
    QTest::failOnWarning(
        QRegularExpression("QFile::.*: File(.*) already open"));
}

For the common case of failing on any warning pass no parameter:

void FileTest::init()
{
    QTest::failOnWarning();
}

Note

ignoreMessage() takes precedence over this function, so any warnings that match a pattern given to both ignoreMessage() and failOnWarning() will be ignored.

See also

QTEST_FATAL_FAIL

static failOnWarning(message)
Parameters:

message – str

This function overloads failOnWarning() .

Appends a test failure to the test log if the message is output.

See also

failOnWarning()

static formatString(prefix, suffix, numArguments)
Parameters:
  • prefix – str

  • suffix – str

  • numArguments – int

Return type:

char

static ignoreMessage(type, messagePattern)
Parameters:

This is an overloaded function.

Ignores messages created by qDebug(), qInfo() or qWarning(). If the message matching messagePattern with the corresponding type is outputted, it will be removed from the test log. If the test finished and the message was not outputted, a test failure is appended to the test log.

Note

Invoking this function will only ignore one message. If the message you want to ignore is output twice, you have to call ignoreMessage() twice, too.

static ignoreMessage(type, message)
Parameters:

Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Ignores messages created by qDebug(), qInfo() or qWarning(). If the message with the corresponding type is outputted, it will be removed from the test log. If the test finished and the message was not outputted, a test failure is appended to the test log.

Note

Invoking this function will only ignore one message. If the message you want to ignore is output twice, you have to call ignoreMessage() twice, too.

Example:

dir = QDir()
QTest.ignoreMessage(QtWarningMsg, "QDir.mkdir: Empty or null file name(s)")
dir.mkdir("")

The example above tests that QDir::mkdir() outputs the right warning when invoked with an invalid file name.

static keyToAscii(key)
Parameters:

keyKey

Return type:

int

static qCaught(expected, file, line)
Parameters:
  • expected – str

  • file – str

  • line – int

static qCaught(expected, what, file, line)
Parameters:
  • expected – str

  • what – str

  • file – str

  • line – int

static qCleanup()
static qElementData(elementName, metaTypeId)
Parameters:
  • elementName – str

  • metaTypeId – int

Return type:

void

static qExpectFail(dataIndex, comment, mode, file, line)
Parameters:
  • dataIndex – str

  • comment – str

  • modeTestFailMode

  • file – str

  • line – int

Return type:

bool

static qExtractTestData(dirName)
Parameters:

dirName – str

Return type:

QSharedPointer

Extracts a directory from resources to disk. The content is extracted recursively to a temporary folder. The extracted content is removed automatically once the last reference to the return value goes out of scope.

dirName is the name of the directory to extract from resources.

Returns the temporary directory where the data was extracted or null in case of errors.

static qFindTestData(basepath[, file=None[, line=0[, builddir=None[, sourcedir=None]]]])
Parameters:
  • basepath – str

  • file – str

  • line – int

  • builddir – str

  • sourcedir – str

Return type:

str

static qFindTestData(basepath[, file=None[, line=0[, builddir=None[, sourcedir=None]]]])
Parameters:
  • basepath – str

  • file – str

  • line – int

  • builddir – str

  • sourcedir – str

Return type:

str

static qGlobalData(tagName, typeId)
Parameters:
  • tagName – str

  • typeId – int

Return type:

void

static qRun()
Return type:

int

static qSkip(message, file, line)
Parameters:
  • message – str

  • file – str

  • line – int

static qSleep(ms)
Parameters:

ms – int

This is an overloaded function.

Sleeps for ms milliseconds, blocking execution of the test.

Equivalent to calling:

QTest::qSleep(std::chrono::milliseconds{ms});
static qWait(ms)
Parameters:

ms – int

This is an overloaded function.

Waits for msecs. Equivalent to calling:

QTest::qWait(std::chrono::milliseconds{msecs});
static runningTest()
Return type:

bool

static setBenchmarkResult(result, metric)
Parameters:

Sets the benchmark result for this test function to result.

Use this function if you want to report benchmark results without using the QBENCHMARK macro. Use metric to specify how Qt Test should interpret the results.

The context for the result will be the test function name and any data tag from the _data function. This function can only be called once in each test function, subsequent calls will replace the earlier reported results.

Note that the -iterations command line argument has no effect on test functions without the QBENCHMARK macro.

static setMainSourcePath(file[, builddir=None])
Parameters:
  • file – str

  • builddir – str

static setThrowOnFail(enable)
Parameters:

enable – bool

Enables (enable = true) or disables ( enable = false) throwing on QCOMPARE() / QVERIFY() failures (as opposed to just returning from the immediately-surrounding function context).

The feature is reference-counted: If you call this function N times with true, you need to call it N times with false to get back to where you started.

The default is false, unless the QTEST_THROW_ON_FAIL environment variable is set.

This call has no effect when the QTEST_THROW_ON_FAIL C++ macro is defined.

Note

You must compile your tests with exceptions enabled to use this feature.

See also

setThrowOnSkip() ThrowOnFailEnabler ThrowOnFailDisabler QTEST_THROW_ON_FAIL

static setThrowOnSkip(enable)
Parameters:

enable – bool

Enables (enable = true) or disables ( enable = false) throwing on QSKIP() (as opposed to just returning from the immediately-surrounding function context).

The feature is reference-counted: If you call this function N times with true, you need to call it N times with false to get back to where you started.

The default is false, unless the QTEST_THROW_ON_SKIP environment variable is set.

This call has no effect when the QTEST_THROW_ON_SKIP C++ macro is defined.

Note

You must compile your tests with exceptions enabled to use this feature.

See also

setThrowOnFail() ThrowOnSkipEnabler ThrowOnSkipDisabler QTEST_THROW_ON_SKIP

static testObject()
Return type:

QObject

static toPrettyCString(unicode, length)
Parameters:
  • unicode – str

  • length – int

Return type:

char