Fix qmltestrunner hang bug when no TestCase item
[profile/ivi/qtdeclarative.git] / src / qmltest / quicktest.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the test suite of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "quicktest.h"
43 #include "quicktestresult_p.h"
44 #include <QtTest/qtestsystem.h>
45 #include "qtestoptions_p.h"
46 #include <QApplication>
47 #include <QtDeclarative/qdeclarative.h>
48 #include <QtQuick1/qdeclarativeview.h>
49 #include <QtDeclarative/qdeclarativeengine.h>
50 #include <QtDeclarative/qdeclarativecontext.h>
51 #if defined(QML_VERSION) && QML_VERSION >= 0x020000
52 #include <QtDeclarative/qquickview.h>
53 #define QUICK_TEST_SCENEGRAPH 1
54 #endif
55 #include <QtDeclarative/qjsvalue.h>
56 #include <QtDeclarative/qjsengine.h>
57 #include <QtGui/qopengl.h>
58 #include <QtCore/qurl.h>
59 #include <QtCore/qfileinfo.h>
60 #include <QtCore/qdir.h>
61 #include <QtCore/qdiriterator.h>
62 #include <QtCore/qfile.h>
63 #include <QtCore/qdebug.h>
64 #include <QtCore/qeventloop.h>
65 #include <QtGui/qtextdocument.h>
66 #include <stdio.h>
67 #include <QtGui/QGuiApplication>
68 QT_BEGIN_NAMESPACE
69
70
71 class QTestRootObject : public QObject
72 {
73     Q_OBJECT
74     Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
75     Q_PROPERTY(bool hasTestCase READ hasTestCase WRITE setHasTestCase NOTIFY hasTestCaseChanged)
76 public:
77     QTestRootObject(QObject *parent = 0)
78         : QObject(parent), hasQuit(false), m_hasTestCase(false), m_windowShown(false) {}
79
80     bool hasQuit:1;
81     bool hasTestCase() const { return m_hasTestCase; }
82     void setHasTestCase(bool value) { m_hasTestCase = value; emit hasTestCaseChanged(); }
83
84     bool windowShown() const { return m_windowShown; }
85     void setWindowShown(bool value) { m_windowShown = value; emit windowShownChanged(); }
86
87 Q_SIGNALS:
88     void windowShownChanged();
89     void hasTestCaseChanged();
90
91 private Q_SLOTS:
92     void quit() { hasQuit = true; }
93
94 private:
95     bool m_windowShown : 1;
96     bool m_hasTestCase :1;
97 };
98
99 static inline QString stripQuotes(const QString &s)
100 {
101     if (s.length() >= 2 && s.startsWith(QLatin1Char('"')) && s.endsWith(QLatin1Char('"')))
102         return s.mid(1, s.length() - 2);
103     else
104         return s;
105 }
106
107 int quick_test_main(int argc, char **argv, const char *name, quick_test_viewport_create createViewport, const char *sourceDir)
108 {
109     QGuiApplication* app = 0;
110     if (!QCoreApplication::instance()) {
111         app = new QGuiApplication(argc, argv);
112     }
113
114     // Look for QML-specific command-line options.
115     //      -import dir         Specify an import directory.
116     //      -input dir          Specify the input directory for test cases.
117     //      -qtquick1           Run with QtQuick 1 rather than QtQuick 2.
118     QStringList imports;
119     QString testPath;
120     bool qtQuick2 = true;
121     int outargc = 1;
122     int index = 1;
123     while (index < argc) {
124         if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) {
125             imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
126             index += 2;
127         } else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) {
128             testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
129             index += 2;
130         } else if (strcmp(argv[index], "-opengl") == 0) {
131             ++index;
132         } else if (strcmp(argv[index], "-qtquick1") == 0) {
133             qtQuick2 = false;
134             ++index;
135         } else if (outargc != index) {
136             argv[outargc++] = argv[index++];
137         } else {
138             ++outargc;
139             ++index;
140         }
141     }
142     argv[outargc] = 0;
143     argc = outargc;
144
145     // Parse the command-line arguments.
146     QuickTestResult::parseArgs(argc, argv);
147     QuickTestResult::setProgramName(name);
148
149     // Determine where to look for the test data.
150     if (testPath.isEmpty() && sourceDir)
151         testPath = QString::fromLocal8Bit(sourceDir);
152     if (testPath.isEmpty())
153         testPath = QLatin1String(".");
154
155     QStringList files;
156
157     if (testPath.endsWith(QLatin1String(".qml")) && QFileInfo(testPath).isFile()) {
158         files << testPath;
159     } else {
160         // Scan the test data directory recursively, looking for "tst_*.qml" files.
161         QStringList filters;
162         filters += QLatin1String("tst_*.qml");
163         QDirIterator iter(testPath, filters, QDir::Files,
164                           QDirIterator::Subdirectories |
165                           QDirIterator::FollowSymlinks);
166         while (iter.hasNext())
167             files += iter.next();
168         files.sort();
169     }
170
171     // Bail out if we didn't find any test cases.
172     if (files.isEmpty()) {
173         qWarning() << argv[0] << ": could not find any test cases under"
174                    << testPath;
175         return 1;
176     }
177
178
179     // Scan through all of the "tst_*.qml" files and run each of them
180     // in turn with a QDeclarativeView.
181 #ifdef QUICK_TEST_SCENEGRAPH
182     if (qtQuick2) {
183         QQuickView view;
184         QTestRootObject rootobj;
185         QEventLoop eventLoop;
186         QObject::connect(view.engine(), SIGNAL(quit()),
187                          &rootobj, SLOT(quit()));
188         QObject::connect(view.engine(), SIGNAL(quit()),
189                          &eventLoop, SLOT(quit()));
190         view.rootContext()->setContextProperty
191             (QLatin1String("qtest"), &rootobj);
192         foreach (QString path, imports)
193             view.engine()->addImportPath(path);
194
195         foreach (QString file, files) {
196             QFileInfo fi(file);
197             if (!fi.exists())
198                 continue;
199
200             rootobj.setHasTestCase(false);
201
202             QString path = fi.absoluteFilePath();
203             if (path.startsWith(QLatin1String(":/")))
204                 view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
205             else
206                 view.setSource(QUrl::fromLocalFile(path));
207
208             if (QTest::printAvailableFunctions)
209                 continue;
210             if (view.status() == QQuickView::Error) {
211                 // Error compiling the test - flag failure in the log and continue.
212                 QList<QDeclarativeError> errors = view.errors();
213                 QuickTestResult results;
214                 results.setTestCaseName(fi.baseName());
215                 results.startLogging();
216                 results.setFunctionName(QLatin1String("compile"));
217                 results.setFunctionType(QuickTestResult::Func);
218                 results.fail(errors.at(0).description(),
219                              errors.at(0).url().toString(),
220                              errors.at(0).line());
221                 results.finishTestFunction();
222                 results.setFunctionName(QString());
223                 results.setFunctionType(QuickTestResult::NoWhere);
224                 results.stopLogging();
225                 continue;
226             }
227             if (!rootobj.hasQuit) {
228                 // If the test already quit, then it was performed
229                 // synchronously during setSource().  Otherwise it is
230                 // an asynchronous test and we need to show the window
231                 // and wait for the quit indication.
232                 view.show();
233                 QTest::qWaitForWindowShown(&view);
234                 rootobj.setWindowShown(true);
235                 if (!rootobj.hasQuit && rootobj.hasTestCase())
236                     eventLoop.exec();
237             }
238         }
239     } else
240 #endif
241     {
242         foreach (QString file, files) {
243             QFileInfo fi(file);
244             if (!fi.exists())
245                 continue;
246             QDeclarativeView view;
247             QTestRootObject rootobj;
248             QEventLoop eventLoop;
249             QObject::connect(view.engine(), SIGNAL(quit()),
250                              &rootobj, SLOT(quit()));
251             QObject::connect(view.engine(), SIGNAL(quit()),
252                              &eventLoop, SLOT(quit()));
253             if (createViewport)
254                 view.setViewport((*createViewport)());
255             view.rootContext()->setContextProperty
256                 (QLatin1String("qtest"), &rootobj);
257             foreach (QString path, imports)
258                 view.engine()->addImportPath(path);
259             QString path = fi.absoluteFilePath();
260             if (path.startsWith(QLatin1String(":/")))
261                 view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
262             else
263                 view.setSource(QUrl::fromLocalFile(path));
264             if (QTest::printAvailableFunctions)
265                 continue;
266             if (view.status() == QDeclarativeView::Error) {
267                 // Error compiling the test - flag failure in the log and continue.
268                 QList<QDeclarativeError> errors = view.errors();
269                 QuickTestResult results;
270                 results.setTestCaseName(fi.baseName());
271                 results.startLogging();
272                 results.setFunctionName(QLatin1String("compile"));
273                 results.setFunctionType(QuickTestResult::Func);
274                 results.fail(errors.at(0).description(),
275                              errors.at(0).url().toString(),
276                              errors.at(0).line());
277                 results.finishTestFunction();
278                 results.setFunctionName(QString());
279                 results.setFunctionType(QuickTestResult::NoWhere);
280                 results.stopLogging();
281                 continue;
282             }
283             if (!rootobj.hasQuit) {
284                 // If the test already quit, then it was performed
285                 // synchronously during setSource().  Otherwise it is
286                 // an asynchronous test and we need to show the window
287                 // and wait for the quit indication.
288                 view.show();
289                 QTest::qWaitForWindowShown(&view);
290                 rootobj.setWindowShown(true);
291                 if (!rootobj.hasQuit)
292                     eventLoop.exec();
293             }
294         }
295     }
296
297     // Flush the current logging stream.
298     QuickTestResult::setProgramName(0);
299
300     delete app;
301     // Return the number of failures as the exit code.
302     return QuickTestResult::exitCode();
303 }
304
305 QT_END_NAMESPACE
306
307 #include "quicktest.moc"