1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtTest module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include <QtTest/qtestcase.h>
43 #include <QtTest/qtestassert.h>
45 #include <QtCore/qbytearray.h>
46 #include <QtCore/qmetaobject.h>
47 #include <QtCore/qobject.h>
48 #include <QtCore/qstringlist.h>
49 #include <QtCore/qvector.h>
50 #include <QtCore/qvarlengtharray.h>
51 #include <QtCore/qcoreapplication.h>
52 #include <QtCore/qfile.h>
53 #include <QtCore/qfileinfo.h>
54 #include <QtCore/qdir.h>
55 #include <QtCore/qprocess.h>
56 #include <QtCore/qdebug.h>
57 #include <QtCore/qlibraryinfo.h>
59 #include <QtTest/private/qtestlog_p.h>
60 #include <QtTest/private/qtesttable_p.h>
61 #include <QtTest/qtestdata.h>
62 #include <QtTest/private/qtestresult_p.h>
63 #include <QtTest/private/qsignaldumper_p.h>
64 #include <QtTest/private/qbenchmark_p.h>
65 #include <QtTest/private/cycle_p.h>
75 #include <windows.h> // for Sleep
84 #include <Carbon/Carbon.h> // for SetFrontProcess
85 #include <IOKit/pwr_mgt/IOPMLib.h>
95 \brief The QTest namespace contains all the functions and
96 declarations that are related to the QTestLib tool.
98 Please refer to the \l{QTestLib Manual} documentation for information on
99 how to write unit tests.
102 /*! \macro QVERIFY(condition)
106 The QVERIFY() macro checks whether the \a condition is true or not. If it is
107 true, execution continues. If not, a failure is recorded in the test log
108 and the test won't be executed further.
110 \bold {Note:} This macro can only be used in a test function that is invoked
111 by the test framework.
114 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 0
116 \sa QCOMPARE(), QTRY_VERIFY()
119 /*! \macro QVERIFY2(condition, message)
123 The QVERIFY2() macro behaves exactly like QVERIFY(), except that it outputs
124 a verbose \a message when \a condition is false. The \a message is a plain
128 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 1
130 \sa QVERIFY(), QCOMPARE()
133 /*! \macro QCOMPARE(actual, expected)
137 The QCOMPARE macro compares an \a actual value to an \a expected value using
138 the equals operator. If \a actual and \a expected are identical, execution
139 continues. If not, a failure is recorded in the test log and the test
140 won't be executed further.
142 In the case of comparing floats and doubles, qFuzzyCompare() is used for
143 comparing. This means that comparing to 0 will likely fail. One solution
144 to this is to compare to 1, and add 1 to the produced output.
146 QCOMPARE tries to output the contents of the values if the comparison fails,
147 so it is visible from the test log why the comparison failed.
149 QCOMPARE is very strict on the data types. Both \a actual and \a expected
150 have to be of the same type, otherwise the test won't compile. This prohibits
151 unspecified behavior from being introduced; that is behavior that usually
152 occurs when the compiler implicitly casts the argument.
154 For your own classes, you can use \l QTest::toString() to format values for
155 outputting into the test log.
157 \note This macro can only be used in a test function that is invoked
158 by the test framework.
161 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 2
163 \sa QVERIFY(), QTRY_COMPARE(), QTest::toString()
166 /*! \macro QTRY_VERIFY_WITH_TIMEOUT(condition, timeout)
170 The QTRY_VERIFY_WITH_TIMEOUT() macro is similar to QVERIFY(), but checks the \a condition
171 repeatedly, until either the condition becomes true or the \a timeout is
172 reached. Between each evaluation, events will be processed. If the timeout
173 is reached, a failure is recorded in the test log and the test won't be
176 \note This macro can only be used in a test function that is invoked
177 by the test framework.
179 \sa QTRY_VERIFY(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
183 /*! \macro QTRY_VERIFY(condition)
187 Invokes QTRY_VERIFY_WITH_TIMEOUT() with a timeout of five seconds.
189 \note This macro can only be used in a test function that is invoked
190 by the test framework.
192 \sa QTRY_VERIFY_WITH_TIMEOUT(), QVERIFY(), QCOMPARE(), QTRY_COMPARE()
195 /*! \macro QTRY_COMPARE_WITH_TIMEOUT(actual, expected, timeout)
199 The QTRY_COMPARE_WITH_TIMEOUT() macro is similar to QCOMPARE(), but performs the comparison
200 of the \a actual and \a expected values repeatedly, until either the two values
201 are equal or the \a timeout is reached. Between each comparison, events
202 will be processed. If the timeout is reached, a failure is recorded in the
203 test log and the test won't be executed further.
205 \note This macro can only be used in a test function that is invoked
206 by the test framework.
208 \sa QTRY_COMPARE(), QCOMPARE(), QVERIFY(), QTRY_VERIFY()
211 /*! \macro QTRY_COMPARE(actual, expected)
215 Invokes QTRY_COMPARE_WITH_TIMEOUT() with a timeout of five seconds.
217 \note This macro can only be used in a test function that is invoked
218 by the test framework.
220 \sa QTRY_COMPARE_WITH_TIMEOUT(), QCOMPARE(), QVERIFY(), QTRY_VERIFY()
223 /*! \macro QFETCH(type, name)
227 The fetch macro creates a local variable named \a name with the type \a type
228 on the stack. \a name has to match the element name from the test's data.
229 If no such element exists, the test will assert.
231 Assuming a test has the following data:
233 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 3
235 The test data has two elements, a QString called \c aString and an integer
236 called \c expected. To fetch these values in the actual test:
238 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 4
240 \c aString and \c expected are variables on the stack that are initialized with
241 the current test data.
243 \bold {Note:} This macro can only be used in a test function that is invoked
244 by the test framework. The test function must have a _data function.
247 /*! \macro QWARN(message)
252 Appends \a message as a warning to the test log. This macro can be used anywhere
256 /*! \macro QFAIL(message)
260 This macro can be used to force a test failure. The test stops
261 executing and the failure \a message is appended to the test log.
263 \bold {Note:} This macro can only be used in a test function that is invoked
264 by the test framework.
268 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 5
271 /*! \macro QTEST(actual, testElement)
275 QTEST() is a convenience macro for \l QCOMPARE() that compares
276 the value \a actual with the element \a testElement from the test's data.
277 If there is no such element, the test asserts.
279 Apart from that, QTEST() behaves exactly as \l QCOMPARE().
283 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 6
287 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 7
292 /*! \macro QSKIP(description)
296 If called from a test function, the QSKIP() macro stops execution of the test
297 without adding a failure to the test log. You can use it to skip tests that
298 wouldn't make sense in the current configuration. The text \a description is
299 appended to the test log and should contain an explanation of why the test
300 couldn't be executed.
302 If the test is data-driven, each call to QSKIP() will skip only the current
303 row of test data, so an unconditional call to QSKIP will produce one skip
304 message in the test log for each row of test data.
306 If called from an _data function, the QSKIP() macro will stop execution of
307 the _data function and will prevent execution of the associated test
310 If called from initTestCase() or initTestCase_data(), the QSKIP() macro will
311 skip all test and _data functions.
313 \bold {Note:} This macro can only be used in a test function or _data
314 function that is invoked by the test framework.
317 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 8
320 /*! \macro QEXPECT_FAIL(dataIndex, comment, mode)
324 The QEXPECT_FAIL() macro marks the next \l QCOMPARE() or \l QVERIFY() as an
325 expected failure. Instead of adding a failure to the test log, an expected
326 failure will be reported.
328 If a \l QVERIFY() or \l QCOMPARE() is marked as an expected failure,
329 but passes instead, an unexpected pass (XPASS) is written to the test log.
331 The parameter \a dataIndex describes for which entry in the test data the
332 failure is expected. Pass an empty string (\c{""}) if the failure
333 is expected for all entries or if no test data exists.
335 \a comment will be appended to the test log for the expected failure.
337 \a mode is a \l QTest::TestFailMode and sets whether the test should
338 continue to execute or not.
340 \bold {Note:} This macro can only be used in a test function that is invoked
341 by the test framework.
344 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 9
346 In the example above, an expected fail will be written into the test output
347 if the variable \c i is not 42. If the variable \c i is 42, an unexpected pass
348 is written instead. The QEXPECT_FAIL() has no influence on the second QCOMPARE()
349 statement in the example.
352 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 10
354 The above testfunction will not continue executing for the test data
357 \sa QTest::TestFailMode, QVERIFY(), QCOMPARE()
360 /*! \macro QFINDTESTDATA(filename)
364 Returns a QString for the testdata file referred to by \a filename, or an
365 empty QString if the testdata file could not be found.
367 This macro allows the test to load data from an external file without
368 hardcoding an absolute filename into the test, or using relative paths
369 which may be error prone.
371 The returned path will be the first path from the following list which
372 resolves to an existing file or directory:
375 \o \a filename relative to QCoreApplication::applicationDirPath()
376 (only if a QCoreApplication or QApplication object has been created).
377 \o \a filename relative to the test's standard install directory
378 (QLibraryInfo::TestsPath with the lowercased testcase name appended).
379 \o \a filename relative to the directory containing the source file from which
380 QFINDTESTDATA is invoked.
383 If the named file/directory does not exist at any of these locations,
384 a warning is printed to the test log.
386 For example, in this code:
387 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 26
389 The testdata file will be resolved as the first existing file from:
392 \o \c{/home/user/build/myxmlparser/tests/tst_myxmlparser/testxml/simple1.xml}
393 \o \c{/usr/local/Qt-5.0.0/tests/tst_myxmlparser/testxml/simple1.xml}
394 \o \c{/home/user/sources/myxmlparser/tests/tst_myxmlparser/testxml/simple1.xml}
397 This allows the test to find its testdata regardless of whether the
398 test has been installed, and regardless of whether the test's build tree
399 is equal to the test's source tree.
401 \bold {Note:} reliable detection of testdata from the source directory requires
402 either that qmake is used, or the \c{QT_TESTCASE_BUILDDIR} macro is defined to
403 point to the working directory from which the compiler is invoked, or only
404 absolute paths to the source files are passed to the compiler. Otherwise, the
405 absolute path of the source directory cannot be determined.
408 /*! \macro QTEST_MAIN(TestClass)
412 Implements a main() function that instantiates an application object and
413 the \a TestClass, and executes all tests in the order they were defined.
414 Use this macro to build stand-alone executables.
416 If \c QT_WIDGETS_LIB is defined, the application object will be a QApplication,
417 if \c QT_GUI_LIB is defined, the application object will be a QGuiApplication,
418 otherwise it will be a QCoreApplication. If qmake is used and the configuration
419 includes \c{QT += widgets}, then \c QT_WIDGETS_LIB will be defined automatically.
420 Similarly, if qmake is used and the configuration includes \c{QT += gui}, then
421 \c QT_GUI_LIB will be defined automatically.
423 \bold {Note:} On platforms that have keypad navigation enabled by default,
424 this macro will forcefully disable it if \c QT_WIDGETS_LIB is defined. This is done
425 to simplify the usage of key events when writing autotests. If you wish to write a
426 test case that uses keypad navigation, you should enable it either in the
427 \c {initTestCase()} or \c {init()} functions of your test case by calling
428 \l {QApplication::setNavigationMode()}.
431 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 11
433 \sa QTEST_APPLESS_MAIN(), QTEST_GUILESS_MAIN(), QTest::qExec(),
434 QApplication::setNavigationMode()
437 /*! \macro QTEST_APPLESS_MAIN(TestClass)
441 Implements a main() function that executes all tests in \a TestClass.
443 Behaves like \l QTEST_MAIN(), but doesn't instantiate a QApplication
444 object. Use this macro for really simple stand-alone non-GUI tests.
449 /*! \macro QTEST_GUILESS_MAIN(TestClass)
453 Implements a main() function that instantiates a QCoreApplication object
454 and the \a TestClass, and executes all tests in the order they were
455 defined. Use this macro to build stand-alone executables.
457 Behaves like \l QTEST_MAIN(), but instantiates a QCoreApplication instead
458 of the QApplication object. Use this macro if your test case doesn't need
459 functionality offered by QApplication, but the event loop is still necessary.
469 This macro is used to measure the performance of code within a test.
470 The code to be benchmarked is contained within a code block following
475 \snippet examples/qtestlib/tutorial5/benchmarking.cpp 0
477 \sa {QTestLib Manual#Creating a Benchmark}{Creating a Benchmark},
478 {Chapter 5: Writing a Benchmark}{Writing a Benchmark}
482 \macro QBENCHMARK_ONCE
487 \brief The QBENCHMARK_ONCE macro is for measuring performance of a
488 code block by running it once.
490 This macro is used to measure the performance of code within a test.
491 The code to be benchmarked is contained within a code block following
494 Unlike QBENCHMARK, the contents of the contained code block is only run
495 once. The elapsed time will be reported as "0" if it's to short to
496 be measured by the selected backend. (Use)
498 \sa {QTestLib Manual#Creating a Benchmark}{Creating a Benchmark},
499 {Chapter 5: Writing a Benchmark}{Writing a Benchmark}
502 /*! \enum QTest::TestFailMode
504 This enum describes the modes for handling an expected failure of the
505 \l QVERIFY() or \l QCOMPARE() macros.
507 \value Abort Aborts the execution of the test. Use this mode when it
508 doesn't make sense to execute the test any further after the
511 \value Continue Continues execution of the test after the expected failure.
516 /*! \enum QTest::KeyAction
518 This enum describes possible actions for key handling.
520 \value Press The key is pressed.
521 \value Release The key is released.
522 \value Click The key is clicked (pressed and released).
525 /*! \enum QTest::MouseAction
527 This enum describes possible actions for mouse handling.
529 \value MousePress A mouse button is pressed.
530 \value MouseRelease A mouse button is released.
531 \value MouseClick A mouse button is clicked (pressed and released).
532 \value MouseDClick A mouse button is double clicked (pressed and released twice).
533 \value MouseMove The mouse pointer has moved.
536 /*! \fn void QTest::keyClick(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
540 Simulates clicking of \a key with an optional \a modifier on a \a widget.
541 If \a delay is larger than 0, the test will wait for \a delay milliseconds
542 before clicking the key.
545 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 13
547 The example above simulates clicking \c a on \c myWidget without
548 any keyboard modifiers and without delay of the test.
550 \sa QTest::keyClicks()
553 /*! \fn void QTest::keyClick(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
555 Simulates clicking of \a key with an optional \a modifier on a \a widget.
556 If \a delay is larger than 0, the test will wait for \a delay milliseconds
557 before clicking the key.
560 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 14
562 The first example above simulates clicking the \c escape key on \c
563 myWidget without any keyboard modifiers and without delay. The
564 second example simulates clicking \c shift-escape on \c myWidget
565 following a 200 ms delay of the test.
567 \sa QTest::keyClicks()
570 /*! \fn void QTest::keyEvent(KeyAction action, QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
572 Sends a Qt key event to \a widget with the given \a key and an associated \a action.
573 Optionally, a keyboard \a modifier can be specified, as well as a \a delay
574 (in milliseconds) of the test before sending the event.
577 /*! \fn void QTest::keyEvent(KeyAction action, QWidget *widget, char ascii, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
581 Sends a Qt key event to \a widget with the given key \a ascii and an associated \a action.
582 Optionally, a keyboard \a modifier can be specified, as well as a \a delay
583 (in milliseconds) of the test before sending the event.
587 /*! \fn void QTest::keyPress(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
589 Simulates pressing a \a key with an optional \a modifier on a \a widget. If \a delay
590 is larger than 0, the test will wait for \a delay milliseconds before pressing the key.
592 \bold {Note:} At some point you should release the key using \l keyRelease().
594 \sa QTest::keyRelease(), QTest::keyClick()
597 /*! \fn void QTest::keyPress(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
601 Simulates pressing a \a key with an optional \a modifier on a \a widget.
602 If \a delay is larger than 0, the test will wait for \a delay milliseconds
603 before pressing the key.
605 \bold {Note:} At some point you should release the key using \l keyRelease().
607 \sa QTest::keyRelease(), QTest::keyClick()
610 /*! \fn void QTest::keyRelease(QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
612 Simulates releasing a \a key with an optional \a modifier on a \a widget.
613 If \a delay is larger than 0, the test will wait for \a delay milliseconds
614 before releasing the key.
616 \sa QTest::keyPress(), QTest::keyClick()
619 /*! \fn void QTest::keyRelease(QWidget *widget, char key, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
623 Simulates releasing a \a key with an optional \a modifier on a \a widget.
624 If \a delay is larger than 0, the test will wait for \a delay milliseconds
625 before releasing the key.
627 \sa QTest::keyClick()
631 /*! \fn void QTest::keyClicks(QWidget *widget, const QString &sequence, Qt::KeyboardModifiers modifier = Qt::NoModifier, int delay=-1)
633 Simulates clicking a \a sequence of keys on a \a
634 widget. Optionally, a keyboard \a modifier can be specified as
635 well as a \a delay (in milliseconds) of the test before each key
639 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 15
641 The example above simulates clicking the sequence of keys
642 representing "hello world" on \c myWidget without any keyboard
643 modifiers and without delay of the test.
645 \sa QTest::keyClick()
648 /*! \fn void QTest::mousePress(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay=-1)
650 Simulates pressing a mouse \a button with an optional \a modifier
651 on a \a widget. The position is defined by \a pos; the default
652 position is the center of the widget. If \a delay is specified,
653 the test will wait for the specified amount of milliseconds before
656 \sa QTest::mouseRelease(), QTest::mouseClick()
659 /*! \fn void QTest::mouseRelease(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay=-1)
661 Simulates releasing a mouse \a button with an optional \a modifier
662 on a \a widget. The position of the release is defined by \a pos;
663 the default position is the center of the widget. If \a delay is
664 specified, the test will wait for the specified amount of
665 milliseconds before releasing the button.
667 \sa QTest::mousePress(), QTest::mouseClick()
670 /*! \fn void QTest::mouseClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay=-1)
672 Simulates clicking a mouse \a button with an optional \a modifier
673 on a \a widget. The position of the click is defined by \a pos;
674 the default position is the center of the widget. If \a delay is
675 specified, the test will wait for the specified amount of
676 milliseconds before pressing and before releasing the button.
678 \sa QTest::mousePress(), QTest::mouseRelease()
681 /*! \fn void QTest::mouseDClick(QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers modifier = 0, QPoint pos = QPoint(), int delay=-1)
683 Simulates double clicking a mouse \a button with an optional \a
684 modifier on a \a widget. The position of the click is defined by
685 \a pos; the default position is the center of the widget. If \a
686 delay is specified, the test will wait for the specified amount of
687 milliseconds before each press and release.
689 \sa QTest::mouseClick()
692 /*! \fn void QTest::mouseMove(QWidget *widget, QPoint pos = QPoint(), int delay=-1)
694 Moves the mouse pointer to a \a widget. If \a pos is not
695 specified, the mouse pointer moves to the center of the widget. If
696 a \a delay (in milliseconds) is given, the test will wait before
697 moving the mouse pointer.
701 \fn char *QTest::toString(const T &value)
703 Returns a textual representation of \a value. This function is used by
704 \l QCOMPARE() to output verbose information in case of a test failure.
706 You can add specializations of this function to your test to enable
709 \bold {Note:} The caller of toString() must delete the returned data
710 using \c{delete[]}. Your implementation should return a string
711 created with \c{new[]} or qstrdup().
715 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 16
717 The example above defines a toString() specialization for a class
718 called \c MyPoint. Whenever a comparison of two instances of \c
719 MyPoint fails, \l QCOMPARE() will call this function to output the
720 contents of \c MyPoint to the test log.
726 \fn char *QTest::toString(const QLatin1String &string)
729 Returns a textual representation of the given \a string.
733 \fn char *QTest::toString(const QString &string)
736 Returns a textual representation of the given \a string.
740 \fn char *QTest::toString(const QByteArray &ba)
743 Returns a textual representation of the byte array \a ba.
745 \sa QTest::toHexRepresentation()
749 \fn char *QTest::toString(const QTime &time)
752 Returns a textual representation of the given \a time.
756 \fn char *QTest::toString(const QDate &date)
759 Returns a textual representation of the given \a date.
763 \fn char *QTest::toString(const QDateTime &dateTime)
766 Returns a textual representation of the date and time specified by
771 \fn char *QTest::toString(const QChar &character)
774 Returns a textual representation of the given \a character.
778 \fn char *QTest::toString(const QPoint &point)
781 Returns a textual representation of the given \a point.
785 \fn char *QTest::toString(const QSize &size)
788 Returns a textual representation of the given \a size.
792 \fn char *QTest::toString(const QRect &rectangle)
795 Returns a textual representation of the given \a rectangle.
799 \fn char *QTest::toString(const QUrl &url)
803 Returns a textual representation of the given \a url.
807 \fn char *QTest::toString(const QPointF &point)
810 Returns a textual representation of the given \a point.
814 \fn char *QTest::toString(const QSizeF &size)
817 Returns a textual representation of the given \a size.
821 \fn char *QTest::toString(const QRectF &rectangle)
824 Returns a textual representation of the given \a rectangle.
828 \fn char *QTest::toString(const QVariant &variant)
831 Returns a textual representation of the given \a variant.
834 /*! \fn void QTest::qWait(int ms)
836 Waits for \a ms milliseconds. While waiting, events will be processed and
837 your test will stay responsive to user interface events or network communication.
840 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 17
842 The code above will wait until the network server is responding for a
843 maximum of about 12.5 seconds.
848 /*! \fn bool QTest::qWaitForWindowShown(QWidget *window)
851 Waits until the \a window is shown in the screen. This is mainly useful for
852 asynchronous systems like X11, where a window will be mapped to screen some
853 time after being asked to show itself on the screen. Returns true.
856 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 24
860 \class QTest::QTouchEventSequence
864 \brief The QTouchEventSequence class is used to simulate a sequence of touch events.
866 To simulate a sequence of touch events on a specific device for a widget, call
867 QTest::touchEvent to create a QTouchEventSequence instance. Add touch events to
868 the sequence by calling press(), move(), release() and stationary(), and let the
869 instance run out of scope to commit the sequence to the event system.
872 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 25
876 \fn QTest::QTouchEventSequence::~QTouchEventSequence()
878 Commits this sequence of touch events and frees allocated resources.
882 \fn QTouchEventSequence &QTest::QTouchEventSequence::press(int touchId, const QPoint &pt, QWidget *widget)
884 Adds a press event for touchpoint \a touchId at position \a pt to this sequence and returns
885 a reference to this QTouchEventSequence.
887 The position \a pt is interpreted as relative to \a widget. If \a widget is the null pointer, then
888 \a pt is interpreted as relative to the widget provided when instantiating this QTouchEventSequence.
890 Simulates that the user pressed the touch screen or pad with the finger identified by \a touchId.
894 \fn QTouchEventSequence &QTest::QTouchEventSequence::move(int touchId, const QPoint &pt, QWidget *widget)
896 Adds a move event for touchpoint \a touchId at position \a pt to this sequence and returns
897 a reference to this QTouchEventSequence.
899 The position \a pt is interpreted as relative to \a widget. If \a widget is the null pointer, then
900 \a pt is interpreted as relative to the widget provided when instantiating this QTouchEventSequence.
902 Simulates that the user moved the finger identified by \a touchId.
906 \fn QTouchEventSequence &QTest::QTouchEventSequence::release(int touchId, const QPoint &pt, QWidget *widget)
908 Adds a release event for touchpoint \a touchId at position \a pt to this sequence and returns
909 a reference to this QTouchEventSequence.
911 The position \a pt is interpreted as relative to \a widget. If \a widget is the null pointer, then
912 \a pt is interpreted as relative to the widget provided when instantiating this QTouchEventSequence.
914 Simulates that the user lifted the finger identified by \a touchId.
918 \fn QTouchEventSequence &QTest::QTouchEventSequence::stationary(int touchId)
920 Adds a stationary event for touchpoint \a touchId to this sequence and returns
921 a reference to this QTouchEventSequence.
923 Simulates that the user did not move the finger identified by \a touchId.
927 \fn QTouchEventSequence QTest::touchEvent(QWidget *widget, QTouchEvent::DeviceType deviceType)
929 Creates and returns a QTouchEventSequence for the device \a deviceType to
930 simulate events for \a widget.
932 When adding touch events to the sequence, \a widget will also be used to translate
933 the position provided to screen coordinates, unless another widget is provided in the
934 respective calls to press(), move() etc.
936 The touch events are committed to the event system when the destructor of the
937 QTouchEventSequence is called (ie when the object returned runs out of scope).
940 static bool installCoverageTool(const char * appname, const char * testname)
942 #ifdef __COVERAGESCANNER__
943 if (!qgetenv("QT_TESTCOCOON_ACTIVE").isEmpty())
945 // Set environment variable QT_TESTCOCOON_ACTIVE to prevent an eventual subtest from
946 // being considered as a stand-alone test regarding the coverage analysis.
947 qputenv("QT_TESTCOCOON_ACTIVE", "1");
949 // Install Coverage Tool
950 __coveragescanner_install(appname);
951 __coveragescanner_testname(testname);
952 __coveragescanner_clear();
963 static QObject *currentTestObject = 0;
967 TestFunction() : function_(-1), data_(0) {}
968 void set(int function, char *data) { function_ = function; data_ = data; }
969 char *data() const { return data_; }
970 int function() const { return function_; }
971 ~TestFunction() { delete[] data_; }
977 * Contains the list of test functions that was supplied
978 * on the command line, if any. Hence, if not empty,
979 * those functions should be run instead of
980 * all appearing in the test case.
982 static TestFunction * testFuncs = 0;
983 static int testFuncCount = 0;
985 /** Don't leak testFuncs on exit even on error */
986 static struct TestFuncCleanup
995 ~TestFuncCleanup() { cleanup(); }
998 static int keyDelay = -1;
999 static int mouseDelay = -1;
1000 static int eventDelay = -1;
1001 #if defined(Q_OS_UNIX)
1002 static bool noCrashHandler = false;
1006 Invoke a method of the object without generating warning if the method does not exist
1008 static void invokeMethod(QObject *obj, const char *methodName)
1010 const QMetaObject *metaObject = obj->metaObject();
1011 int funcIndex = metaObject->indexOfMethod(methodName);
1012 if (funcIndex >= 0) {
1013 QMetaMethod method = metaObject->method(funcIndex);
1014 method.invoke(obj, Qt::DirectConnection);
1018 int defaultEventDelay()
1020 if (eventDelay == -1) {
1021 if (!qgetenv("QTEST_EVENT_DELAY").isEmpty())
1022 eventDelay = atoi(qgetenv("QTEST_EVENT_DELAY"));
1029 int Q_TESTLIB_EXPORT defaultMouseDelay()
1031 if (mouseDelay == -1) {
1032 if (!qgetenv("QTEST_MOUSEEVENT_DELAY").isEmpty())
1033 mouseDelay = atoi(qgetenv("QTEST_MOUSEEVENT_DELAY"));
1035 mouseDelay = defaultEventDelay();
1040 int Q_TESTLIB_EXPORT defaultKeyDelay()
1042 if (keyDelay == -1) {
1043 if (!qgetenv("QTEST_KEYEVENT_DELAY").isEmpty())
1044 keyDelay = atoi(qgetenv("QTEST_KEYEVENT_DELAY").constData());
1046 keyDelay = defaultEventDelay();
1051 static bool isValidSlot(const QMetaMethod &sl)
1053 if (sl.access() != QMetaMethod::Private || !sl.parameterTypes().isEmpty()
1054 || qstrlen(sl.typeName()) || sl.methodType() != QMetaMethod::Slot)
1056 const char *sig = sl.signature();
1057 int len = qstrlen(sig);
1060 if (sig[len - 2] != '(' || sig[len - 1] != ')')
1062 if (len > 7 && strcmp(sig + (len - 7), "_data()") == 0)
1064 if (strcmp(sig, "initTestCase()") == 0 || strcmp(sig, "cleanupTestCase()") == 0
1065 || strcmp(sig, "cleanup()") == 0 || strcmp(sig, "init()") == 0)
1070 Q_TESTLIB_EXPORT bool printAvailableFunctions = false;
1071 Q_TESTLIB_EXPORT QStringList testFunctions;
1072 Q_TESTLIB_EXPORT QStringList testTags;
1074 static void qPrintTestSlots(FILE *stream)
1076 for (int i = 0; i < QTest::currentTestObject->metaObject()->methodCount(); ++i) {
1077 QMetaMethod sl = QTest::currentTestObject->metaObject()->method(i);
1078 if (isValidSlot(sl))
1079 fprintf(stream, "%s\n", sl.signature());
1083 static void qPrintDataTags(FILE *stream)
1085 // Avoid invoking the actual test functions, and also avoid printing irrelevant output:
1086 QTestLog::setPrintAvailableTagsMode();
1088 // Get global data tags:
1089 QTestTable::globalTestTable();
1090 invokeMethod(QTest::currentTestObject, "initTestCase_data()");
1091 const QTestTable *gTable = QTestTable::globalTestTable();
1093 const QMetaObject *currTestMetaObj = QTest::currentTestObject->metaObject();
1095 // Process test functions:
1096 for (int i = 0; i < currTestMetaObj->methodCount(); ++i) {
1097 QMetaMethod tf = currTestMetaObj->method(i);
1099 if (isValidSlot(tf)) {
1101 // Retrieve local tags:
1102 QStringList localTags;
1104 char *slot = qstrdup(tf.signature());
1105 slot[strlen(slot) - 2] = '\0';
1107 member.resize(qstrlen(slot) + qstrlen("_data()") + 1);
1108 qsnprintf(member.data(), member.size(), "%s_data()", slot);
1109 invokeMethod(QTest::currentTestObject, member.constData());
1110 for (int j = 0; j < table.dataCount(); ++j)
1111 localTags << QLatin1String(table.testData(j)->dataTag());
1113 // Print all tag combinations:
1114 if (gTable->dataCount() == 0) {
1115 if (localTags.count() == 0) {
1116 // No tags at all, so just print the test function:
1117 fprintf(stream, "%s %s\n", currTestMetaObj->className(), slot);
1119 // Only local tags, so print each of them:
1120 for (int k = 0; k < localTags.size(); ++k)
1122 stream, "%s %s %s\n",
1123 currTestMetaObj->className(), slot, localTags.at(k).toLatin1().data());
1126 for (int j = 0; j < gTable->dataCount(); ++j) {
1127 if (localTags.count() == 0) {
1128 // Only global tags, so print the current one:
1130 stream, "%s %s __global__ %s\n",
1131 currTestMetaObj->className(), slot, gTable->testData(j)->dataTag());
1133 // Local and global tags, so print each of the local ones and
1134 // the current global one:
1135 for (int k = 0; k < localTags.size(); ++k)
1137 stream, "%s %s %s __global__ %s\n", currTestMetaObj->className(), slot,
1138 localTags.at(k).toLatin1().data(), gTable->testData(j)->dataTag());
1148 static int qToInt(char *str)
1151 int l = (int)strtol(str, &pEnd, 10);
1153 fprintf(stderr, "Invalid numeric parameter: '%s'\n", str);
1159 Q_TESTLIB_EXPORT void qtest_qParseArgs(int argc, char *argv[], bool qml)
1161 QTestLog::LogMode logFormat = QTestLog::Plain;
1162 const char *logFilename = 0;
1164 const char *testOptions =
1165 " New-style logging options:\n"
1166 " -o filename,format : Output results to file in the specified format\n"
1167 " Use - to output to stdout\n"
1168 " Valid formats are:\n"
1169 " txt : Plain text\n"
1170 " xunitxml : XML XUnit document\n"
1171 " xml : XML document\n"
1172 " lightxml : A stream of XML tags\n"
1174 " *** Multiple loggers can be specified, but at most one can log to stdout.\n"
1176 " Old-style logging options:\n"
1177 " -o filename : Write the output into file\n"
1178 " -txt : Output results in Plain Text\n"
1179 " -xunitxml : Output results as XML XUnit document\n"
1180 " -xml : Output results as XML document\n"
1181 " -lightxml : Output results as stream of XML tags\n"
1183 " *** If no output file is specified, stdout is assumed.\n"
1184 " *** If no output format is specified, -txt is assumed.\n"
1186 " Detail options:\n"
1187 " -silent : Only outputs warnings and failures\n"
1188 " -v1 : Print enter messages for each testfunction\n"
1189 " -v2 : Also print out each QVERIFY/QCOMPARE/QTEST\n"
1190 " -vs : Print every signal emitted\n"
1192 " Testing options:\n"
1193 " -functions : Returns a list of current testfunctions\n"
1194 " -datatags : Returns a list of current data tags.\n"
1195 " A global data tag is preceded by ' __global__ '.\n"
1196 " -eventdelay ms : Set default delay for mouse and keyboard simulation to ms milliseconds\n"
1197 " -keydelay ms : Set default delay for keyboard simulation to ms milliseconds\n"
1198 " -mousedelay ms : Set default delay for mouse simulation to ms milliseconds\n"
1199 " -maxwarnings n : Sets the maximum amount of messages to output.\n"
1200 " 0 means unlimited, default: 2000\n"
1201 #if defined(Q_OS_UNIX)
1202 " -nocrashhandler : Disables the crash handler\n"
1205 " Benchmarking options:\n"
1206 #ifdef QTESTLIB_USE_VALGRIND
1207 " -callgrind : Use callgrind to time benchmarks\n"
1209 #ifdef HAVE_TICK_COUNTER
1210 " -tickcounter : Use CPU tick counters to time benchmarks\n"
1212 " -eventcounter : Counts events received during benchmarks\n"
1213 " -minimumvalue n : Sets the minimum acceptable measurement value\n"
1214 " -iterations n : Sets the number of accumulation iterations.\n"
1215 " -median n : Sets the number of median iterations.\n"
1216 " -vb : Print out verbose benchmarking information.\n";
1218 for (int i = 1; i < argc; ++i) {
1219 if (strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--help") == 0
1220 || strcmp(argv[i], "/?") == 0) {
1221 printf(" Usage: %s [options] [testfunction[:testdata]]...\n"
1222 " By default, all testfunctions will be run.\n\n"
1223 "%s", argv[0], testOptions);
1227 " QmlTest options:\n"
1228 " -import dir : Specify an import directory.\n"
1229 " -input dir/file : Specify the root directory for test cases or a single test case file.\n"
1230 " -qtquick1 : Run with QtQuick 1 rather than QtQuick 2.\n"
1231 " -translation file : Specify the translation file.\n"
1236 " -help : This help\n");
1238 } else if (strcmp(argv[i], "-functions") == 0) {
1240 QTest::printAvailableFunctions = true;
1242 qPrintTestSlots(stdout);
1245 } else if (strcmp(argv[i], "-datatags") == 0) {
1247 qPrintDataTags(stdout);
1250 } else if (strcmp(argv[i], "-txt") == 0) {
1251 logFormat = QTestLog::Plain;
1252 } else if (strcmp(argv[i], "-xunitxml") == 0) {
1253 logFormat = QTestLog::XunitXML;
1254 } else if (strcmp(argv[i], "-xml") == 0) {
1255 logFormat = QTestLog::XML;
1256 } else if (strcmp(argv[i], "-lightxml") == 0) {
1257 logFormat = QTestLog::LightXML;
1258 } else if (strcmp(argv[i], "-silent") == 0) {
1259 QTestLog::setVerboseLevel(-1);
1260 } else if (strcmp(argv[i], "-v1") == 0) {
1261 QTestLog::setVerboseLevel(1);
1262 } else if (strcmp(argv[i], "-v2") == 0) {
1263 QTestLog::setVerboseLevel(2);
1264 } else if (strcmp(argv[i], "-vs") == 0) {
1265 QSignalDumper::startDump();
1266 } else if (strcmp(argv[i], "-o") == 0) {
1267 if (i + 1 >= argc) {
1268 fprintf(stderr, "-o needs an extra parameter specifying the filename and optional format\n");
1272 // Do we have the old or new style -o option?
1273 char *filename = new char[strlen(argv[i])+1];
1274 char *format = new char[strlen(argv[i])+1];
1275 if (sscanf(argv[i], "%[^,],%s", filename, format) == 1) {
1277 logFilename = argv[i];
1280 if (strcmp(format, "txt") == 0)
1281 logFormat = QTestLog::Plain;
1282 else if (strcmp(format, "lightxml") == 0)
1283 logFormat = QTestLog::LightXML;
1284 else if (strcmp(format, "xml") == 0)
1285 logFormat = QTestLog::XML;
1286 else if (strcmp(format, "xunitxml") == 0)
1287 logFormat = QTestLog::XunitXML;
1289 fprintf(stderr, "output format must be one of txt, lightxml, xml or xunitxml\n");
1292 if (strcmp(filename, "-") == 0 && QTestLog::loggerUsingStdout()) {
1293 fprintf(stderr, "only one logger can log to stdout\n");
1296 QTestLog::addLogger(logFormat, filename);
1300 } else if (strcmp(argv[i], "-eventdelay") == 0) {
1301 if (i + 1 >= argc) {
1302 fprintf(stderr, "-eventdelay needs an extra parameter to indicate the delay(ms)\n");
1305 QTest::eventDelay = qToInt(argv[++i]);
1307 } else if (strcmp(argv[i], "-keydelay") == 0) {
1308 if (i + 1 >= argc) {
1309 fprintf(stderr, "-keydelay needs an extra parameter to indicate the delay(ms)\n");
1312 QTest::keyDelay = qToInt(argv[++i]);
1314 } else if (strcmp(argv[i], "-mousedelay") == 0) {
1315 if (i + 1 >= argc) {
1316 fprintf(stderr, "-mousedelay needs an extra parameter to indicate the delay(ms)\n");
1319 QTest::mouseDelay = qToInt(argv[++i]);
1321 } else if (strcmp(argv[i], "-maxwarnings") == 0) {
1322 if (i + 1 >= argc) {
1323 fprintf(stderr, "-maxwarnings needs an extra parameter with the amount of warnings\n");
1326 QTestLog::setMaxWarnings(qToInt(argv[++i]));
1328 #if defined(Q_OS_UNIX)
1329 } else if (strcmp(argv[i], "-nocrashhandler") == 0) {
1330 QTest::noCrashHandler = true;
1332 #ifdef QTESTLIB_USE_VALGRIND
1333 } else if (strcmp(argv[i], "-callgrind") == 0) {
1334 if (QBenchmarkValgrindUtils::haveValgrind())
1335 if (QFileInfo(QDir::currentPath()).isWritable()) {
1336 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::CallgrindParentProcess);
1338 fprintf(stderr, "WARNING: Current directory not writable. Using the walltime measurer.\n");
1341 fprintf(stderr, "WARNING: Valgrind not found or too old. Make sure it is installed and in your path. "
1342 "Using the walltime measurer.\n");
1344 } else if (strcmp(argv[i], "-callgrindchild") == 0) { // "private" option
1345 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::CallgrindChildProcess);
1346 QBenchmarkGlobalData::current->callgrindOutFileBase =
1347 QBenchmarkValgrindUtils::outFileBase();
1349 #ifdef HAVE_TICK_COUNTER
1350 } else if (strcmp(argv[i], "-tickcounter") == 0) {
1351 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::TickCounter);
1353 } else if (strcmp(argv[i], "-eventcounter") == 0) {
1354 QBenchmarkGlobalData::current->setMode(QBenchmarkGlobalData::EventCounter);
1355 } else if (strcmp(argv[i], "-minimumvalue") == 0) {
1356 if (i + 1 >= argc) {
1357 fprintf(stderr, "-minimumvalue needs an extra parameter to indicate the minimum time(ms)\n");
1360 QBenchmarkGlobalData::current->walltimeMinimum = qToInt(argv[++i]);
1362 } else if (strcmp(argv[i], "-iterations") == 0) {
1363 if (i + 1 >= argc) {
1364 fprintf(stderr, "-iterations needs an extra parameter to indicate the number of iterations\n");
1367 QBenchmarkGlobalData::current->iterationCount = qToInt(argv[++i]);
1369 } else if (strcmp(argv[i], "-median") == 0) {
1370 if (i + 1 >= argc) {
1371 fprintf(stderr, "-median needs an extra parameter to indicate the number of median iterations\n");
1374 QBenchmarkGlobalData::current->medianIterationCount = qToInt(argv[++i]);
1377 } else if (strcmp(argv[i], "-vb") == 0) {
1378 QBenchmarkGlobalData::current->verboseOutput = true;
1379 } else if (argv[i][0] == '-') {
1380 fprintf(stderr, "Unknown option: '%s'\n\n%s", argv[i], testOptions);
1382 fprintf(stderr, "\nqmltest related options:\n"
1383 " -import : Specify an import directory.\n"
1384 " -input : Specify the root directory for test cases.\n"
1385 " -qtquick1 : Run with QtQuick 1 rather than QtQuick 2.\n"
1389 fprintf(stderr, "\n"
1390 " -help : This help\n");
1393 // We can't check the availability of test functions until
1394 // we load the QML files. So just store the data for now.
1397 for (offset = 0; *(argv[i]+offset); ++offset) {
1398 if (*(argv[i]+offset) == ':') {
1399 if (*(argv[i]+offset+1) == ':') {
1400 // "::" is used as a test name separator.
1401 // e.g. "ClickTests::test_click:row1".
1410 QTest::testFunctions += QString::fromLatin1(argv[i]);
1411 QTest::testTags += QString();
1413 QTest::testFunctions +=
1414 QString::fromLatin1(argv[i], colon);
1416 QString::fromLatin1(argv[i] + colon + 1);
1419 if (!QTest::testFuncs) {
1420 QTest::testFuncs = new QTest::TestFunction[512];
1424 char buf[512], *data=0;
1426 for (off = 0; *(argv[i]+off); ++off) {
1427 if (*(argv[i]+off) == ':') {
1433 data = qstrdup(argv[i]+colon+1);
1435 qsnprintf(buf, qMin(512, off + 1), "%s", argv[i]); // copy text before the ':' into buf
1436 qsnprintf(buf + off, qMin(512 - off, 3), "()"); // append "()"
1437 int idx = QTest::currentTestObject->metaObject()->indexOfMethod(buf);
1438 if (idx < 0 || !isValidSlot(QTest::currentTestObject->metaObject()->method(idx))) {
1439 fprintf(stderr, "Unknown testfunction: '%s'\n", buf);
1440 fprintf(stderr, "Available testfunctions:\n");
1441 qPrintTestSlots(stderr);
1444 testFuncs[testFuncCount].set(idx, data);
1446 QTEST_ASSERT(QTest::testFuncCount < 512);
1450 // If no loggers were created by the long version of the -o command-line
1451 // option, create a logger using whatever filename and format were
1452 // set using the old-style command-line options.
1453 if (QTestLog::loggerCount() == 0)
1454 QTestLog::addLogger(logFormat, logFilename);
1457 QBenchmarkResult qMedian(const QList<QBenchmarkResult> &container)
1459 const int count = container.count();
1461 return QBenchmarkResult();
1464 return container.at(0);
1466 QList<QBenchmarkResult> containerCopy = container;
1467 qSort(containerCopy);
1469 const int middle = count / 2;
1471 // ### handle even-sized containers here by doing an aritmetic mean of the two middle items.
1472 return containerCopy.at(middle);
1475 struct QTestDataSetter
1477 QTestDataSetter(QTestData *data)
1479 QTestResult::setCurrentTestData(data);
1483 QTestResult::setCurrentTestData(0);
1487 static void qInvokeTestMethodDataEntry(char *slot)
1489 /* Benchmarking: for each median iteration*/
1491 int i = (QBenchmarkGlobalData::current->measurer->needsWarmupIteration()) ? -1 : 0;
1493 QList<QBenchmarkResult> results;
1495 QBenchmarkTestMethodData::current->beginDataRun();
1497 /* Benchmarking: for each accumulation iteration*/
1500 QTestResult::setCurrentTestLocation(QTestResult::InitFunc);
1501 invokeMethod(QTest::currentTestObject, "init()");
1502 if (QTestResult::skipCurrentTest())
1505 QTestResult::setCurrentTestLocation(QTestResult::Func);
1507 QBenchmarkTestMethodData::current->result = QBenchmarkResult();
1508 QBenchmarkTestMethodData::current->resultAccepted = false;
1510 QBenchmarkGlobalData::current->context.tag =
1512 QTestResult::currentDataTag()
1513 ? QTestResult::currentDataTag() : "");
1515 invokeOk = QMetaObject::invokeMethod(QTest::currentTestObject, slot,
1516 Qt::DirectConnection);
1518 QTestResult::addFailure("Unable to execute slot", __FILE__, __LINE__);
1520 QTestResult::finishedCurrentTestData();
1522 QTestResult::setCurrentTestLocation(QTestResult::CleanupFunc);
1523 invokeMethod(QTest::currentTestObject, "cleanup()");
1524 QTestResult::finishedCurrentTestDataCleanup();
1525 QTestResult::setCurrentTestLocation(QTestResult::NoWhere);
1527 // If this test method has a benchmark, repeat until all measurements are
1529 // The QBENCHMARK macro increases the number of iterations for each run until
1532 && QBenchmarkTestMethodData::current->isBenchmark()
1533 && QBenchmarkTestMethodData::current->resultsAccepted() == false);
1535 QBenchmarkTestMethodData::current->endDataRun();
1536 if (i > -1) // iteration -1 is the warmup iteration.
1537 results.append(QBenchmarkTestMethodData::current->result);
1539 if (QBenchmarkTestMethodData::current->isBenchmark() &&
1540 QBenchmarkGlobalData::current->verboseOutput) {
1542 QTestLog::info(qPrintable(
1543 QString::fromLatin1("warmup stage result : %1")
1544 .arg(QBenchmarkTestMethodData::current->result.value)), 0, 0);
1546 QTestLog::info(qPrintable(
1547 QString::fromLatin1("accumulation stage result: %1")
1548 .arg(QBenchmarkTestMethodData::current->result.value)), 0, 0);
1551 } while (QBenchmarkTestMethodData::current->isBenchmark()
1552 && (++i < QBenchmarkGlobalData::current->adjustMedianIterationCount()));
1554 if (QBenchmarkTestMethodData::current->isBenchmark()
1555 && QBenchmarkTestMethodData::current->resultsAccepted())
1556 QTestLog::addBenchmarkResult(qMedian(results));
1562 Call slot_data(), init(), slot(), cleanup(), init(), slot(), cleanup(), ...
1563 If data is set then it is the only test that is performed
1565 If the function was successfully called, true is returned, otherwise
1568 static bool qInvokeTestMethod(const char *slotName, const char *data=0)
1570 QTEST_ASSERT(slotName);
1572 QBenchmarkTestMethodData benchmarkData;
1573 QBenchmarkTestMethodData::current = &benchmarkData;
1575 QBenchmarkGlobalData::current->context.slotName = QLatin1String(slotName);
1580 char *slot = qstrdup(slotName);
1581 slot[strlen(slot) - 2] = '\0';
1582 QTestResult::setCurrentTestFunction(slot);
1584 const QTestTable *gTable = QTestTable::globalTestTable();
1585 const int globalDataCount = gTable->dataCount();
1586 int curGlobalDataIndex = 0;
1588 /* For each test function that has a *_data() table/function, do: */
1590 if (!gTable->isEmpty())
1591 QTestResult::setCurrentGlobalTestData(gTable->testData(curGlobalDataIndex));
1593 if (curGlobalDataIndex == 0) {
1594 QTestResult::setCurrentTestLocation(QTestResult::DataFunc);
1595 qsnprintf(member, 512, "%s_data()", slot);
1596 invokeMethod(QTest::currentTestObject, member);
1599 bool foundFunction = false;
1600 if (!QTestResult::skipCurrentTest()) {
1601 int curDataIndex = 0;
1602 const int dataCount = table.dataCount();
1604 // Data tag requested but none available?
1605 if (data && !dataCount) {
1606 // Let empty data tag through.
1610 fprintf(stderr, "Unknown testdata for function %s: '%s'\n", slotName, data);
1611 fprintf(stderr, "Function has no testdata.\n");
1616 /* For each entry in the data table, do: */
1618 QTestResult::setSkipCurrentTest(false);
1619 if (!data || !qstrcmp(data, table.testData(curDataIndex)->dataTag())) {
1620 foundFunction = true;
1621 QTestDataSetter s(curDataIndex >= dataCount ? static_cast<QTestData *>(0)
1622 : table.testData(curDataIndex));
1624 qInvokeTestMethodDataEntry(slot);
1630 } while (curDataIndex < dataCount);
1633 if (data && !foundFunction) {
1634 fprintf(stderr, "Unknown testdata for function %s: '%s'\n", slotName, data);
1635 fprintf(stderr, "Available testdata:\n");
1636 for (int i = 0; i < table.dataCount(); ++i)
1637 fprintf(stderr, "%s\n", table.testData(i)->dataTag());
1641 QTestResult::setCurrentGlobalTestData(0);
1642 ++curGlobalDataIndex;
1643 } while (curGlobalDataIndex < globalDataCount);
1645 QTestResult::finishedCurrentTestFunction();
1646 QTestResult::setSkipCurrentTest(false);
1647 QTestResult::setCurrentTestData(0);
1653 void *fetchData(QTestData *data, const char *tagName, int typeId)
1655 QTEST_ASSERT(typeId);
1656 QTEST_ASSERT_X(data, "QTest::fetchData()", "Test data requested, but no testdata available.");
1657 QTEST_ASSERT(data->parent());
1659 int idx = data->parent()->indexOf(tagName);
1661 if (idx == -1 || idx >= data->dataCount()) {
1662 qFatal("QFETCH: Requested testdata '%s' not available, check your _data function.",
1666 if (typeId != data->parent()->elementTypeId(idx)) {
1667 qFatal("Requested type '%s' does not match available type '%s'.",
1668 QMetaType::typeName(typeId),
1669 QMetaType::typeName(data->parent()->elementTypeId(idx)));
1672 return data->data(idx);
1676 \fn char* QTest::toHexRepresentation(const char *ba, int length)
1678 Returns a pointer to a string that is the string \a ba represented
1679 as a space-separated sequence of hex characters. If the input is
1680 considered too long, it is truncated. A trucation is indicated in
1681 the returned string as an ellipsis at the end.
1683 \a length is the length of the string \a ba.
1685 char *toHexRepresentation(const char *ba, int length)
1690 /* We output at maximum about maxLen characters in order to avoid
1691 * running out of memory and flooding things when the byte array
1694 * maxLen can't be for example 200 because QTestLib is sprinkled with fixed
1697 const int maxLen = 50;
1698 const int len = qMin(maxLen, length);
1701 if (length > maxLen) {
1702 const int size = len * 3 + 4;
1703 result = new char[size];
1705 char *const forElipsis = result + size - 5;
1706 forElipsis[0] = ' ';
1707 forElipsis[1] = '.';
1708 forElipsis[2] = '.';
1709 forElipsis[3] = '.';
1710 result[size - 1] = '\0';
1713 const int size = len * 3;
1714 result = new char[size];
1715 result[size - 1] = '\0';
1718 const char toHex[] = "0123456789ABCDEF";
1723 const char at = ba[i];
1725 result[o] = toHex[(at >> 4) & 0x0F];
1727 result[o] = toHex[at & 0x0F];
1742 static void qInvokeTestMethods(QObject *testObject)
1744 const QMetaObject *metaObject = testObject->metaObject();
1745 QTEST_ASSERT(metaObject);
1746 QTestLog::startLogging();
1747 QTestResult::setCurrentTestFunction("initTestCase");
1748 QTestResult::setCurrentTestLocation(QTestResult::DataFunc);
1749 QTestTable::globalTestTable();
1750 invokeMethod(testObject, "initTestCase_data()");
1752 if (!QTestResult::skipCurrentTest() && !QTest::currentTestFailed()) {
1753 QTestResult::setCurrentTestLocation(QTestResult::InitFunc);
1754 invokeMethod(testObject, "initTestCase()");
1756 // finishedCurrentTestDataCleanup() resets QTestResult::currentTestFailed(), so use a local copy.
1757 const bool previousFailed = QTestResult::currentTestFailed();
1758 QTestResult::finishedCurrentTestData();
1759 QTestResult::finishedCurrentTestDataCleanup();
1760 QTestResult::finishedCurrentTestFunction();
1762 if (!QTestResult::skipCurrentTest() && !previousFailed) {
1764 if (QTest::testFuncs) {
1765 for (int i = 0; i != QTest::testFuncCount; i++) {
1766 if (!qInvokeTestMethod(metaObject->method(QTest::testFuncs[i].function()).signature(),
1767 QTest::testFuncs[i].data())) {
1771 testFuncCleaner.cleanup();
1773 int methodCount = metaObject->methodCount();
1774 QMetaMethod *testMethods = new QMetaMethod[methodCount];
1775 for (int i = 0; i != methodCount; i++)
1776 testMethods[i] = metaObject->method(i);
1777 for (int i = 0; i != methodCount; i++) {
1778 if (!isValidSlot(testMethods[i]))
1780 if (!qInvokeTestMethod(testMethods[i].signature()))
1783 delete[] testMethods;
1788 QTestResult::setSkipCurrentTest(false);
1789 QTestResult::setCurrentTestFunction("cleanupTestCase");
1790 invokeMethod(testObject, "cleanupTestCase()");
1791 QTestResult::finishedCurrentTestData();
1792 QTestResult::finishedCurrentTestDataCleanup();
1794 QTestResult::finishedCurrentTestFunction();
1795 QTestResult::setCurrentTestFunction(0);
1796 QTestTable::clearGlobalTestTable();
1798 QTestLog::stopLogging();
1801 #if defined(Q_OS_UNIX)
1802 class FatalSignalHandler
1805 FatalSignalHandler();
1806 ~FatalSignalHandler();
1809 static void signal(int);
1810 sigset_t handledSignals;
1813 void FatalSignalHandler::signal(int signum)
1815 qFatal("Received signal %d", signum);
1816 #if defined(Q_OS_INTEGRITY)
1818 struct sigaction act;
1819 memset(&act, 0, sizeof(struct sigaction));
1820 act.sa_handler = SIG_DFL;
1821 sigaction(signum, &act, NULL);
1826 FatalSignalHandler::FatalSignalHandler()
1828 sigemptyset(&handledSignals);
1830 const int fatalSignals[] = {
1831 SIGHUP, SIGINT, SIGQUIT, SIGILL, SIGFPE, SIGSEGV, SIGPIPE, SIGTERM, 0 };
1833 struct sigaction act;
1834 memset(&act, 0, sizeof(act));
1835 act.sa_handler = FatalSignalHandler::signal;
1837 // Remove the handler after it is invoked.
1838 #if !defined(Q_OS_INTEGRITY)
1839 act.sa_flags = SA_RESETHAND;
1841 // Block all fatal signals in our signal handler so we don't try to close
1842 // the testlog twice.
1843 sigemptyset(&act.sa_mask);
1844 for (int i = 0; fatalSignals[i]; ++i)
1845 sigaddset(&act.sa_mask, fatalSignals[i]);
1847 struct sigaction oldact;
1849 for (int i = 0; fatalSignals[i]; ++i) {
1850 sigaction(fatalSignals[i], &act, &oldact);
1852 // Don't overwrite any non-default handlers
1853 // however, we need to replace the default QWS handlers
1856 oldact.sa_flags & SA_SIGINFO ||
1858 oldact.sa_handler != SIG_DFL) {
1859 sigaction(fatalSignals[i], &oldact, 0);
1863 sigaddset(&handledSignals, fatalSignals[i]);
1869 FatalSignalHandler::~FatalSignalHandler()
1871 // Unregister any of our remaining signal handlers
1872 struct sigaction act;
1873 memset(&act, 0, sizeof(act));
1874 act.sa_handler = SIG_DFL;
1876 struct sigaction oldact;
1878 for (int i = 1; i < 32; ++i) {
1879 if (!sigismember(&handledSignals, i))
1881 sigaction(i, &act, &oldact);
1883 // If someone overwrote it in the mean time, put it back
1884 if (oldact.sa_handler != FatalSignalHandler::signal)
1885 sigaction(i, &oldact, 0);
1895 Executes tests declared in \a testObject. In addition, the private slots
1896 \c{initTestCase()}, \c{cleanupTestCase()}, \c{init()} and \c{cleanup()}
1897 are executed if they exist. See \l{Creating a Test} for more details.
1899 Optionally, the command line arguments \a argc and \a argv can be provided.
1900 For a list of recognized arguments, read \l {QTestLib Command Line Arguments}.
1902 The following example will run all tests in \c MyTestObject:
1904 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 18
1906 This function returns 0 if no tests failed, or a value other than 0 if one
1907 or more tests failed or in case of unhandled exceptions. (Skipped tests do
1908 not influence the return value.)
1910 For stand-alone test applications, the convenience macro \l QTEST_MAIN() can
1911 be used to declare a main() function that parses the command line arguments
1912 and executes the tests, avoiding the need to call this function explicitly.
1914 The return value from this function is also the exit code of the test
1915 application when the \l QTEST_MAIN() macro is used.
1917 For stand-alone test applications, this function should not be called more
1918 than once, as command-line options for logging test output to files and
1919 executing individual test functions will not behave correctly.
1921 Note: This function is not reentrant, only one test can run at a time. A
1922 test that was executed with qExec() can't run another test via qExec() and
1923 threads are not allowed to call qExec() simultaneously.
1925 If you have programatically created the arguments, as opposed to getting them
1926 from the arguments in \c main(), it is likely of interest to use
1927 QTest::qExec(QObject *, const QStringList &) since it is Unicode safe.
1932 int QTest::qExec(QObject *testObject, int argc, char **argv)
1934 QBenchmarkGlobalData benchmarkData;
1935 QBenchmarkGlobalData::current = &benchmarkData;
1937 #ifdef QTESTLIB_USE_VALGRIND
1938 int callgrindChildExitCode = 0;
1942 bool macNeedsActivate = qApp && (qstrcmp(qApp->metaObject()->className(), "QApplication") == 0);
1943 IOPMAssertionID powerID;
1945 #ifndef QT_NO_EXCEPTIONS
1949 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
1950 _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
1951 SetErrorMode(SetErrorMode(0) | SEM_NOGPFAULTERRORBOX);
1955 // Starting with Qt 4.4, applications launched from the command line
1956 // no longer get focus automatically. Since some tests might depend
1957 // on this, call SetFrontProcess here to get the pre 4.4 behavior.
1958 if (macNeedsActivate) {
1959 ProcessSerialNumber psn = { 0, kCurrentProcess };
1960 SetFrontProcess(&psn);
1961 IOReturn ok = IOPMAssertionCreate(kIOPMAssertionTypeNoDisplaySleep, kIOPMAssertionLevelOn, &powerID);
1962 if (ok != kIOReturnSuccess)
1963 macNeedsActivate = false; // no need to release the assertion on exit.
1967 QTestResult::reset();
1969 QTEST_ASSERT(testObject);
1970 QTEST_ASSERT(!currentTestObject);
1971 currentTestObject = testObject;
1973 const QMetaObject *metaObject = testObject->metaObject();
1974 QTEST_ASSERT(metaObject);
1976 QTestResult::setCurrentTestObject(metaObject->className());
1977 QTestResult::setCurrentAppname(argv[0]);
1979 qtest_qParseArgs(argc, argv, false);
1981 bool installedTestCoverage = installCoverageTool(argv[0], metaObject->className());
1982 QTestLog::setInstalledTestCoverage(installedTestCoverage);
1984 #ifdef QTESTLIB_USE_VALGRIND
1985 if (QBenchmarkGlobalData::current->mode() == QBenchmarkGlobalData::CallgrindParentProcess) {
1986 const QStringList origAppArgs(QCoreApplication::arguments());
1987 if (!QBenchmarkValgrindUtils::rerunThroughCallgrind(origAppArgs, callgrindChildExitCode))
1990 QBenchmarkValgrindUtils::cleanup();
1995 #if defined(Q_OS_UNIX)
1996 QScopedPointer<FatalSignalHandler> handler;
1997 if (!noCrashHandler)
1998 handler.reset(new FatalSignalHandler);
2000 qInvokeTestMethods(testObject);
2003 #ifndef QT_NO_EXCEPTIONS
2005 QTestResult::addFailure("Caught unhandled exception", __FILE__, __LINE__);
2006 if (QTestResult::currentTestFunction()) {
2007 QTestResult::finishedCurrentTestFunction();
2008 QTestResult::setCurrentTestFunction(0);
2011 QTestLog::stopLogging();
2013 if (macNeedsActivate) {
2014 IOPMAssertionRelease(powerID);
2017 currentTestObject = 0;
2019 // Rethrow exception to make debugging easier.
2025 currentTestObject = 0;
2027 QSignalDumper::endDump();
2030 if (macNeedsActivate) {
2031 IOPMAssertionRelease(powerID);
2035 #ifdef QTESTLIB_USE_VALGRIND
2036 if (QBenchmarkGlobalData::current->mode() == QBenchmarkGlobalData::CallgrindParentProcess)
2037 return callgrindChildExitCode;
2039 // make sure our exit code is never going above 127
2040 // since that could wrap and indicate 0 test fails
2041 return qMin(QTestLog::failCount(), 127);
2048 Behaves identically to qExec(QObject *, int, char**) but takes a
2049 QStringList of \a arguments instead of a \c char** list.
2051 int QTest::qExec(QObject *testObject, const QStringList &arguments)
2053 const int argc = arguments.count();
2054 QVarLengthArray<char *> argv(argc);
2056 QVector<QByteArray> args;
2059 for (int i = 0; i < argc; ++i)
2061 args.append(arguments.at(i).toLocal8Bit().constData());
2062 argv[i] = args.last().data();
2065 return qExec(testObject, argc, argv.data());
2070 void QTest::qFail(const char *statementStr, const char *file, int line)
2072 QTestResult::addFailure(statementStr, file, line);
2077 bool QTest::qVerify(bool statement, const char *statementStr, const char *description,
2078 const char *file, int line)
2080 return QTestResult::verify(statement, statementStr, description, file, line);
2083 /*! \fn void QTest::qSkip(const char *message, const char *file, int line)
2086 void QTest::qSkip(const char *message, const char *file, int line)
2088 QTestResult::addSkip(message, file, line);
2089 QTestResult::setSkipCurrentTest(true);
2092 /*! \fn bool QTest::qExpectFail(const char *dataIndex, const char *comment, TestFailMode mode, const char *file, int line)
2095 bool QTest::qExpectFail(const char *dataIndex, const char *comment,
2096 QTest::TestFailMode mode, const char *file, int line)
2098 return QTestResult::expectFail(dataIndex, qstrdup(comment), mode, file, line);
2103 void QTest::qWarn(const char *message, const char *file, int line)
2105 QTestLog::warn(message, file, line);
2109 Ignores messages created by qDebug() or qWarning(). If the \a message
2110 with the corresponding \a type is outputted, it will be removed from the
2111 test log. If the test finished and the \a message was not outputted,
2112 a test failure is appended to the test log.
2114 \bold {Note:} Invoking this function will only ignore one message.
2115 If the message you want to ignore is outputted twice, you have to
2116 call ignoreMessage() twice, too.
2119 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 19
2121 The example above tests that QDir::mkdir() outputs the right warning when invoked
2122 with an invalid file name.
2124 void QTest::ignoreMessage(QtMsgType type, const char *message)
2126 QTestLog::ignoreMessage(type, message);
2133 static inline bool isWindowsBuildDirectory(const QString &dirName)
2135 return dirName.compare(QStringLiteral("Debug"), Qt::CaseInsensitive) == 0
2136 || dirName.compare(QStringLiteral("Release"), Qt::CaseInsensitive) == 0;
2140 QString QTest::qFindTestData(const QString& base, const char *file, int line, const char *builddir)
2144 // Testdata priorities:
2146 // 1. relative to test binary.
2148 QDir binDirectory(QCoreApplication::applicationDirPath());
2149 if (binDirectory.exists(base)) {
2150 found = binDirectory.absoluteFilePath(base);
2153 // Windows: The executable is typically located in one of the
2154 // 'Release' or 'Debug' directories.
2155 else if (isWindowsBuildDirectory(binDirectory.dirName())
2156 && binDirectory.cdUp() && binDirectory.exists(base)) {
2157 found = binDirectory.absoluteFilePath(base);
2160 else if (QTestLog::verboseLevel() >= 2) {
2161 const QString candidate = QDir::toNativeSeparators(QCoreApplication::applicationDirPath() + QLatin1Char('/') + base);
2162 QTestLog::info(qPrintable(
2163 QString::fromLatin1("testdata %1 not found relative to test binary [%2]; "
2164 "checking next location").arg(base, candidate)),
2169 // 2. installed path.
2170 if (found.isEmpty()) {
2171 const char *testObjectName = QTestResult::currentTestObjectName();
2172 if (testObjectName) {
2173 QString testsPath = QLibraryInfo::location(QLibraryInfo::TestsPath);
2174 QString candidate = QString::fromLatin1("%1/%2/%3")
2175 .arg(testsPath, QFile::decodeName(testObjectName).toLower(), base);
2176 if (QFileInfo(candidate).exists()) {
2179 else if (QTestLog::verboseLevel() >= 2) {
2180 QTestLog::info(qPrintable(
2181 QString::fromLatin1("testdata %1 not found in tests install path [%2]; "
2182 "checking next location")
2183 .arg(base, QDir::toNativeSeparators(candidate))),
2189 // 3. relative to test source.
2190 if (found.isEmpty()) {
2191 // srcdir is the directory containing the calling source file.
2192 QFileInfo srcdir = QFileInfo(QFile::decodeName(file)).path();
2194 // If the srcdir is relative, that means it is relative to the current working
2195 // directory of the compiler at compile time, which should be passed in as `builddir'.
2196 if (!srcdir.isAbsolute() && builddir) {
2197 srcdir.setFile(QFile::decodeName(builddir) + QLatin1String("/") + srcdir.filePath());
2200 QString candidate = QString::fromLatin1("%1/%2").arg(srcdir.canonicalFilePath(), base);
2201 if (QFileInfo(candidate).exists()) {
2204 else if (QTestLog::verboseLevel() >= 2) {
2205 QTestLog::info(qPrintable(
2206 QString::fromLatin1("testdata %1 not found relative to source path [%2]")
2207 .arg(base, QDir::toNativeSeparators(candidate))),
2212 if (found.isEmpty()) {
2213 QTest::qWarn(qPrintable(
2214 QString::fromLatin1("testdata %1 could not be located!").arg(base)),
2217 else if (QTestLog::verboseLevel() >= 1) {
2218 QTestLog::info(qPrintable(
2219 QString::fromLatin1("testdata %1 was located at %2").arg(base, QDir::toNativeSeparators(found))),
2228 QString QTest::qFindTestData(const char *base, const char *file, int line, const char *builddir)
2230 return qFindTestData(QFile::decodeName(base), file, line, builddir);
2235 void *QTest::qData(const char *tagName, int typeId)
2237 return fetchData(QTestResult::currentTestData(), tagName, typeId);
2242 void *QTest::qGlobalData(const char *tagName, int typeId)
2244 return fetchData(QTestResult::currentGlobalTestData(), tagName, typeId);
2249 void *QTest::qElementData(const char *tagName, int metaTypeId)
2251 QTEST_ASSERT(tagName);
2252 QTestData *data = QTestResult::currentTestData();
2254 QTEST_ASSERT(data->parent());
2256 int idx = data->parent()->indexOf(tagName);
2257 QTEST_ASSERT(idx != -1);
2258 QTEST_ASSERT(data->parent()->elementTypeId(idx) == metaTypeId);
2260 return data->data(data->parent()->indexOf(tagName));
2265 void QTest::addColumnInternal(int id, const char *name)
2267 QTestTable *tbl = QTestTable::currentTestTable();
2268 QTEST_ASSERT_X(tbl, "QTest::addColumn()", "Cannot add testdata outside of a _data slot.");
2270 tbl->addColumn(id, name);
2274 Appends a new row to the current test data. \a dataTag is the name of
2275 the testdata that will appear in the test output. Returns a QTestData reference
2276 that can be used to stream in data.
2279 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 20
2281 \bold {Note:} This macro can only be used in a test's data function
2282 that is invoked by the test framework.
2284 See \l {Chapter 2: Data Driven Testing}{Data Driven Testing} for
2285 a more extensive example.
2287 \sa addColumn(), QFETCH()
2289 QTestData &QTest::newRow(const char *dataTag)
2291 QTEST_ASSERT_X(dataTag, "QTest::newRow()", "Data tag can not be null");
2292 QTestTable *tbl = QTestTable::currentTestTable();
2293 QTEST_ASSERT_X(tbl, "QTest::newRow()", "Cannot add testdata outside of a _data slot.");
2294 QTEST_ASSERT_X(tbl->elementCount(), "QTest::newRow()", "Must add columns before attempting to add rows.");
2296 return *tbl->newData(dataTag);
2299 /*! \fn void QTest::addColumn(const char *name, T *dummy = 0)
2301 Adds a column with type \c{T} to the current test data.
2302 \a name is the name of the column. \a dummy is a workaround
2303 for buggy compilers and can be ignored.
2305 To populate the column with values, newRow() can be used. Use
2306 \l QFETCH() to fetch the data in the actual test.
2309 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 21
2311 To add custom types to the testdata, the type must be registered with
2312 QMetaType via \l Q_DECLARE_METATYPE().
2314 \bold {Note:} This macro can only be used in a test's data function
2315 that is invoked by the test framework.
2317 See \l {Chapter 2: Data Driven Testing}{Data Driven Testing} for
2318 a more extensive example.
2320 \sa QTest::newRow(), QFETCH(), QMetaType
2324 Returns the name of the test function that is currently executed.
2328 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 22
2330 const char *QTest::currentTestFunction()
2332 return QTestResult::currentTestFunction();
2336 Returns the name of the current test data. If the test doesn't
2337 have any assigned testdata, the function returns 0.
2339 const char *QTest::currentDataTag()
2341 return QTestResult::currentDataTag();
2345 Returns true if the current test function failed, otherwise false.
2347 bool QTest::currentTestFailed()
2349 return QTestResult::currentTestFailed();
2353 Sleeps for \a ms milliseconds, blocking execution of the
2354 test. qSleep() will not do any event processing and leave your test
2355 unresponsive. Network communication might time out while
2356 sleeping. Use \l qWait() to do non-blocking sleeping.
2358 \a ms must be greater than 0.
2360 \bold {Note:} The qSleep() function calls either \c nanosleep() on
2361 unix or \c Sleep() on windows, so the accuracy of time spent in
2362 qSleep() depends on the operating system.
2365 \snippet doc/src/snippets/code/src_qtestlib_qtestcase.cpp 23
2369 void QTest::qSleep(int ms)
2371 QTEST_ASSERT(ms > 0);
2376 struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
2377 nanosleep(&ts, NULL);
2383 QObject *QTest::testObject()
2385 return currentTestObject;
2390 bool QTest::compare_helper(bool success, const char *msg, const char *file, int line)
2392 return QTestResult::compare(success, msg, file, line);
2397 bool QTest::compare_helper(bool success, const char *msg, char *val1, char *val2,
2398 const char *actual, const char *expected, const char *file, int line)
2400 return QTestResult::compare(success, msg, val1, val2, actual, expected, file, line);
2403 /*! \fn bool QTest::qCompare<float>(float const &t1, float const &t2, const char *actual, const char *expected, const char *file, int line)
2407 Q_TESTLIB_EXPORT bool QTest::qCompare<float>(float const &t1, float const &t2, const char *actual, const char *expected,
2408 const char *file, int line)
2410 return qFuzzyCompare(t1, t2)
2411 ? compare_helper(true, "COMPARE()", file, line)
2412 : compare_helper(false, "Compared floats are not the same (fuzzy compare)",
2413 toString(t1), toString(t2), actual, expected, file, line);
2416 /*! \fn bool QTest::qCompare<double>(double const &t1, double const &t2, const char *actual, const char *expected, const char *file, int line)
2420 Q_TESTLIB_EXPORT bool QTest::qCompare<double>(double const &t1, double const &t2, const char *actual, const char *expected,
2421 const char *file, int line)
2423 return qFuzzyCompare(t1, t2)
2424 ? compare_helper(true, "COMPARE()", file, line)
2425 : compare_helper(false, "Compared doubles are not the same (fuzzy compare)",
2426 toString(t1), toString(t2), actual, expected, file, line);
2429 #define TO_STRING_IMPL(TYPE, FORMAT) \
2430 template <> Q_TESTLIB_EXPORT char *QTest::toString<TYPE >(const TYPE &t) \
2432 char *msg = new char[128]; \
2433 qsnprintf(msg, 128, #FORMAT, t); \
2437 TO_STRING_IMPL(short, %hd)
2438 TO_STRING_IMPL(ushort, %hu)
2439 TO_STRING_IMPL(int, %d)
2440 TO_STRING_IMPL(uint, %u)
2441 TO_STRING_IMPL(long, %ld)
2442 TO_STRING_IMPL(ulong, %lu)
2443 #if defined(Q_OS_WIN)
2444 TO_STRING_IMPL(qint64, %I64d)
2445 TO_STRING_IMPL(quint64, %I64u)
2447 TO_STRING_IMPL(qint64, %lld)
2448 TO_STRING_IMPL(quint64, %llu)
2450 TO_STRING_IMPL(bool, %d)
2451 TO_STRING_IMPL(char, %c)
2452 TO_STRING_IMPL(float, %g)
2453 TO_STRING_IMPL(double, %lg)
2457 char *QTest::toString(const char *str)
2461 char *msg = new char[strlen(str) + 1];
2462 return qstrcpy(msg, str);
2467 char *QTest::toString(const void *p)
2469 char *msg = new char[128];
2470 qsnprintf(msg, 128, "%p", p);
2476 bool QTest::compare_string_helper(const char *t1, const char *t2, const char *actual,
2477 const char *expected, const char *file, int line)
2479 return (qstrcmp(t1, t2) == 0)
2480 ? compare_helper(true, "COMPARE()", file, line)
2481 : compare_helper(false, "Compared strings are not the same",
2482 toString(t1), toString(t2), actual, expected, file, line);
2485 /*! \fn bool QTest::compare_ptr_helper(const void *t1, const void *t2, const char *actual, const char *expected, const char *file, int line);
2489 /*! \fn bool QTest::qCompare(T1 const &, T2 const &, const char *, const char *, const char *, int);
2494 /*! \fn void QTest::mouseEvent(MouseAction action, QWidget *widget, Qt::MouseButton button, Qt::KeyboardModifiers stateKey, QPoint pos, int delay=-1)
2498 /*! \fn bool QTest::qCompare(QIcon const &t1, QIcon const &t2, const char *actual, const char *expected, const char *file, int line)
2502 /*! \fn bool QTest::qCompare(QPixmap const &t1, QPixmap const &t2, const char *actual, const char *expected, const char *file, int line)
2506 /*! \fn bool QTest::qCompare(T const &t1, T const &t2, const char *actual, const char *expected, const char *file, int line)
2510 /*! \fn bool QTest::qCompare(const T *t1, const T *t2, const char *actual, const char *expected, const char *file, int line)
2514 /*! \fn bool QTest::qCompare(T *t1, T *t2, const char *actual, const char *expected, const char *file, int line)
2518 /*! \fn bool QTest::qCompare(const T1 *t1, const T2 *t2, const char *actual, const char *expected, const char *file, int line)
2522 /*! \fn bool QTest::qCompare(T1 *t1, T2 *t2, const char *actual, const char *expected, const char *file, int line)
2526 /*! \fn bool QTest::qCompare(const char *t1, const char *t2, const char *actual, const char *expected, const char *file, int line)
2530 /*! \fn bool QTest::qCompare(char *t1, char *t2, const char *actual, const char *expected, const char *file, int line)
2534 /*! \fn bool QTest::qCompare(char *t1, const char *t2, const char *actual, const char *expected, const char *file, int line)
2538 /*! \fn bool QTest::qCompare(const char *t1, char *t2, const char *actual, const char *expected, const char *file, int line)
2542 /*! \fn bool QTest::qCompare(QString const &t1, QLatin1String const &t2, const char *actual, const char *expected, const char *file, int line)
2546 /*! \fn bool QTest::qCompare(QLatin1String const &t1, QString const &t2, const char *actual, const char *expected, const char *file, int line)
2550 /*! \fn bool QTest::qCompare(QStringList const &t1, QStringList const &t2, const char *actual, const char *expected, const char *file, int line)
2554 /*! \fn bool QTest::qCompare(QFlags<T> const &t1, T const &t2, const char *actual, const char *expected, const char *file, int line)
2558 /*! \fn bool QTest::qCompare(QFlags<T> const &t1, int const &t2, const char *actual, const char *expected, const char *file, int line)
2562 /*! \fn bool QTest::qCompare(bool const &t1, int const &t2, const char *actual, const char *expected, const char *file, int line)
2566 /*! \fn bool QTest::qTest(const T& actual, const char *elementName, const char *actualStr, const char *expected, const char *file, int line)
2570 /*! \fn void QTest::sendKeyEvent(KeyAction action, QWidget *widget, Qt::Key code, QString text, Qt::KeyboardModifiers modifier, int delay=-1)
2574 /*! \fn void QTest::sendKeyEvent(KeyAction action, QWidget *widget, Qt::Key code, char ascii, Qt::KeyboardModifiers modifier, int delay=-1)
2578 /*! \fn void QTest::simulateEvent(QWidget *widget, bool press, int code, Qt::KeyboardModifiers modifier, QString text, bool repeat, int delay=-1)