Merge branch 'master' into refactor
[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/qsgview.h>
53 #define QUICK_TEST_SCENEGRAPH 1
54 #endif
55 #include <QtDeclarative/qjsvalue.h>
56 #include <QtDeclarative/qjsengine.h>
57 #include <QtOpenGL/qgl.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
68 QT_BEGIN_NAMESPACE
69
70 // Copied from qdeclarativedebughelper_p.h in Qt, to avoid a dependency
71 // on a private header from Qt.
72 class Q_DECLARATIVE_EXPORT QDeclarativeDebugHelper
73 {
74 public:
75     static QJSEngine *getScriptEngine(QDeclarativeEngine *engine);
76     static void setAnimationSlowDownFactor(qreal factor);
77     static void enableDebugging();
78 };
79
80 class QTestRootObject : public QObject
81 {
82     Q_OBJECT
83     Q_PROPERTY(bool windowShown READ windowShown NOTIFY windowShownChanged)
84 public:
85     QTestRootObject(QObject *parent = 0)
86         : QObject(parent), hasQuit(false), m_windowShown(false) {}
87
88     bool hasQuit;
89
90     bool windowShown() const { return m_windowShown; }
91     void setWindowShown(bool value) { m_windowShown = value; emit windowShownChanged(); }
92
93 Q_SIGNALS:
94     void windowShownChanged();
95
96 private Q_SLOTS:
97     void quit() { hasQuit = true; }
98
99 private:
100     bool m_windowShown;
101 };
102
103 static inline QString stripQuotes(const QString &s)
104 {
105     if (s.length() >= 2 && s.startsWith(QLatin1Char('"')) && s.endsWith(QLatin1Char('"')))
106         return s.mid(1, s.length() - 2);
107     else
108         return s;
109 }
110
111 int quick_test_main(int argc, char **argv, const char *name, quick_test_viewport_create createViewport, const char *sourceDir)
112 {
113     QApplication app(argc, argv);
114
115     // Look for QML-specific command-line options.
116     //      -import dir         Specify an import directory.
117     //      -input dir          Specify the input directory for test cases.
118     //      -qtquick1           Run with QtQuick 1 rather than QtQuick 2.
119     QStringList imports;
120     QString testPath;
121     bool qtQuick2 = true;
122     int outargc = 1;
123     int index = 1;
124     while (index < argc) {
125         if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) {
126             imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
127             index += 2;
128         } else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) {
129             testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
130             index += 2;
131         } else if (strcmp(argv[index], "-opengl") == 0) {
132             ++index;
133         } else if (strcmp(argv[index], "-qtquick1") == 0) {
134             qtQuick2 = false;
135             ++index;
136         } else if (outargc != index) {
137             argv[outargc++] = argv[index++];
138         } else {
139             ++outargc;
140             ++index;
141         }
142     }
143     argv[outargc] = 0;
144     argc = outargc;
145
146     // Determine where to look for the test data.
147     if (testPath.isEmpty() && sourceDir)
148         testPath = QString::fromLocal8Bit(sourceDir);
149     if (testPath.isEmpty())
150         testPath = QLatin1String(".");
151
152     // Scan the test data directory recursively, looking for "tst_*.qml" files.
153     QStringList filters;
154     filters += QLatin1String("tst_*.qml");
155     QStringList files;
156     QDirIterator iter(testPath, filters, QDir::Files,
157                       QDirIterator::Subdirectories |
158                       QDirIterator::FollowSymlinks);
159     while (iter.hasNext())
160         files += iter.next();
161     files.sort();
162
163     // Bail out if we didn't find any test cases.
164     if (files.isEmpty()) {
165         qWarning() << argv[0] << ": could not find any test cases under"
166                    << testPath;
167         return 1;
168     }
169
170     // Parse the command-line arguments.
171     QuickTestResult::parseArgs(argc, argv);
172     QuickTestResult::setProgramName(name);
173
174     // Scan through all of the "tst_*.qml" files and run each of them
175     // in turn with a QDeclarativeView.
176 #ifdef QUICK_TEST_SCENEGRAPH
177     if (qtQuick2) {
178         foreach (QString file, files) {
179             QFileInfo fi(file);
180             if (!fi.exists())
181                 continue;
182             QSGView view;
183             QTestRootObject rootobj;
184             QEventLoop eventLoop;
185             QObject::connect(view.engine(), SIGNAL(quit()),
186                              &rootobj, SLOT(quit()));
187             QObject::connect(view.engine(), SIGNAL(quit()),
188                              &eventLoop, SLOT(quit()));
189             view.rootContext()->setContextProperty
190                 (QLatin1String("qtest"), &rootobj);
191             foreach (QString path, imports)
192                 view.engine()->addImportPath(path);
193             QString path = fi.absoluteFilePath();
194             if (path.startsWith(QLatin1String(":/")))
195                 view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
196             else
197                 view.setSource(QUrl::fromLocalFile(path));
198             if (QTest::printAvailableFunctions)
199                 continue;
200             if (view.status() == QSGView::Error) {
201                 // Error compiling the test - flag failure in the log and continue.
202                 QList<QDeclarativeError> errors = view.errors();
203                 QuickTestResult results;
204                 results.setTestCaseName(fi.baseName());
205                 results.startLogging();
206                 results.setFunctionName(QLatin1String("compile"));
207                 results.setFunctionType(QuickTestResult::Func);
208                 results.fail(errors.at(0).description(),
209                              errors.at(0).url().toString(),
210                              errors.at(0).line());
211                 results.finishTestFunction();
212                 results.setFunctionName(QString());
213                 results.setFunctionType(QuickTestResult::NoWhere);
214                 results.stopLogging();
215                 continue;
216             }
217             if (!rootobj.hasQuit) {
218                 // If the test already quit, then it was performed
219                 // synchronously during setSource().  Otherwise it is
220                 // an asynchronous test and we need to show the window
221                 // and wait for the quit indication.
222                 view.show();
223                 QTest::qWaitForWindowShown(&view);
224                 rootobj.setWindowShown(true);
225                 if (!rootobj.hasQuit)
226                     eventLoop.exec();
227             }
228         }
229     } else
230 #endif
231     {
232         foreach (QString file, files) {
233             QFileInfo fi(file);
234             if (!fi.exists())
235                 continue;
236             QDeclarativeView view;
237             QTestRootObject rootobj;
238             QEventLoop eventLoop;
239             QObject::connect(view.engine(), SIGNAL(quit()),
240                              &rootobj, SLOT(quit()));
241             QObject::connect(view.engine(), SIGNAL(quit()),
242                              &eventLoop, SLOT(quit()));
243             if (createViewport)
244                 view.setViewport((*createViewport)());
245             view.rootContext()->setContextProperty
246                 (QLatin1String("qtest"), &rootobj);
247             foreach (QString path, imports)
248                 view.engine()->addImportPath(path);
249             QString path = fi.absoluteFilePath();
250             if (path.startsWith(QLatin1String(":/")))
251                 view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
252             else
253                 view.setSource(QUrl::fromLocalFile(path));
254             if (QTest::printAvailableFunctions)
255                 continue;
256             if (view.status() == QDeclarativeView::Error) {
257                 // Error compiling the test - flag failure in the log and continue.
258                 QList<QDeclarativeError> errors = view.errors();
259                 QuickTestResult results;
260                 results.setTestCaseName(fi.baseName());
261                 results.startLogging();
262                 results.setFunctionName(QLatin1String("compile"));
263                 results.setFunctionType(QuickTestResult::Func);
264                 results.fail(errors.at(0).description(),
265                              errors.at(0).url().toString(),
266                              errors.at(0).line());
267                 results.finishTestFunction();
268                 results.setFunctionName(QString());
269                 results.setFunctionType(QuickTestResult::NoWhere);
270                 results.stopLogging();
271                 continue;
272             }
273             if (!rootobj.hasQuit) {
274                 // If the test already quit, then it was performed
275                 // synchronously during setSource().  Otherwise it is
276                 // an asynchronous test and we need to show the window
277                 // and wait for the quit indication.
278                 view.show();
279                 QTest::qWaitForWindowShown(&view);
280                 rootobj.setWindowShown(true);
281                 if (!rootobj.hasQuit)
282                     eventLoop.exec();
283             }
284         }
285     }
286
287     // Flush the current logging stream.
288     QuickTestResult::setProgramName(0);
289
290     // Return the number of failures as the exit code.
291     return QuickTestResult::exitCode();
292 }
293
294 QT_END_NAMESPACE
295
296 #include "quicktest.moc"