Rename QDeclarative symbols to QQuick and QQml
[profile/ivi/qtdeclarative.git] / src / qmltest / quicktest.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the test suite of the Qt Toolkit.
7 **
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.
16 **
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.
20 **
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.
28 **
29 ** Other Usage
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.
32 **
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 <QtQml/qqml.h>
48 #include <QtQml/qqmlengine.h>
49 #include <QtQml/qqmlcontext.h>
50 #if defined(QML_VERSION) && QML_VERSION >= 0x020000
51 #include <QtQuick/qquickview.h>
52 #define QUICK_TEST_SCENEGRAPH 1
53 #endif
54 #include <QtQml/qjsvalue.h>
55 #include <QtQml/qjsengine.h>
56 #include <QtGui/qopengl.h>
57 #include <QtCore/qurl.h>
58 #include <QtCore/qfileinfo.h>
59 #include <QtCore/qdir.h>
60 #include <QtCore/qdiriterator.h>
61 #include <QtCore/qfile.h>
62 #include <QtCore/qdebug.h>
63 #include <QtCore/qeventloop.h>
64 #include <QtCore/qtextstream.h>
65 #include <QtGui/qtextdocument.h>
66 #include <stdio.h>
67 #include <QtGui/QGuiApplication>
68 #include <QtCore/QTranslator>
69 QT_BEGIN_NAMESPACE
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_windowShown(false), m_hasTestCase(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 template <class View> void handleCompileErrors(const QFileInfo &fi, const View &view)
108 {
109     // Error compiling the test - flag failure in the log and continue.
110     const QList<QQmlError> errors = view.errors();
111     QuickTestResult results;
112     results.setTestCaseName(fi.baseName());
113     results.startLogging();
114     results.setFunctionName(QLatin1String("compile"));
115     // Verbose warning output of all messages and relevant parameters
116     QString message;
117     QTextStream str(&message);
118     str << "\n  " << QDir::toNativeSeparators(fi.absoluteFilePath()) << " produced "
119         << errors.size() << " error(s):\n";
120     foreach (const QQmlError &e, errors) {
121         str << "    ";
122         if (e.url().isLocalFile()) {
123             str << e.url().toLocalFile();
124         } else {
125             str << e.url().toString();
126         }
127         if (e.line() > 0)
128             str << ':' << e.line() << ',' << e.column();
129         str << ": " << e.description() << '\n';
130     }
131     str << "  Working directory: " << QDir::toNativeSeparators(QDir::current().absolutePath()) << '\n';
132     if (QQmlEngine *engine = view.engine()) {
133         str << "  View: " << view.metaObject()->className() << ", import paths:\n";
134         foreach (const QString &i, engine->importPathList())
135             str << "    '" << QDir::toNativeSeparators(i) << "'\n";
136         const QStringList pluginPaths = engine->pluginPathList();
137         str << "  Plugin paths:\n";
138         foreach (const QString &p, pluginPaths)
139             str << "    '" << QDir::toNativeSeparators(p) << "'\n";
140     }
141     qWarning("%s", qPrintable(message));
142     // Fail with error 0.
143     results.fail(errors.at(0).description(),
144                  errors.at(0).url(), errors.at(0).line());
145     results.finishTestData();
146     results.finishTestDataCleanup();
147     results.finishTestFunction();
148     results.setFunctionName(QString());
149     results.stopLogging();
150 }
151
152 int quick_test_main(int argc, char **argv, const char *name, quick_test_viewport_create createViewport, const char *sourceDir)
153 {
154     Q_UNUSED(createViewport);
155     QGuiApplication* app = 0;
156     if (!QCoreApplication::instance()) {
157         app = new QGuiApplication(argc, argv);
158     }
159
160     // Look for QML-specific command-line options.
161     //      -import dir         Specify an import directory.
162     //      -input dir          Specify the input directory for test cases.
163     //      -qtquick1           Run with QtQuick 1 rather than QtQuick 2.
164     //      -translation file   Specify the translation file.
165     QStringList imports;
166     QString testPath;
167     QString translationFile;
168     bool qtQuick2 = true;
169     int outargc = 1;
170     int index = 1;
171     while (index < argc) {
172         if (strcmp(argv[index], "-import") == 0 && (index + 1) < argc) {
173             imports += stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
174             index += 2;
175         } else if (strcmp(argv[index], "-input") == 0 && (index + 1) < argc) {
176             testPath = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
177             index += 2;
178         } else if (strcmp(argv[index], "-opengl") == 0) {
179             ++index;
180         } else if (strcmp(argv[index], "-qtquick1") == 0) {
181             qtQuick2 = false;
182             ++index;
183         } else if (strcmp(argv[index], "-translation") == 0 && (index + 1) < argc) {
184             translationFile = stripQuotes(QString::fromLocal8Bit(argv[index + 1]));
185             index += 2;
186         } else if (outargc != index) {
187             argv[outargc++] = argv[index++];
188         } else {
189             ++outargc;
190             ++index;
191         }
192     }
193     argv[outargc] = 0;
194     argc = outargc;
195
196     // Parse the command-line arguments.
197
198     // Setting currentAppname and currentTestObjectName (via setProgramName) are needed
199     // for the code coverage analysis. Must be done before parseArgs is called.
200     QuickTestResult::setCurrentAppname(argv[0]);
201     QuickTestResult::setProgramName(name);
202
203     QuickTestResult::parseArgs(argc, argv);
204
205     QTranslator translator;
206     if (!translationFile.isEmpty()) {
207         if (translator.load(translationFile)) {
208             app->installTranslator(&translator);
209         } else {
210             qWarning("Could not load the translation file '%s'.", qPrintable(translationFile));
211         }
212     }
213
214     // Determine where to look for the test data.
215     if (testPath.isEmpty() && sourceDir)
216         testPath = QString::fromLocal8Bit(sourceDir);
217     if (testPath.isEmpty()) {
218         QDir current = QDir::current();
219 #ifdef Q_OS_WIN
220         // Skip release/debug subfolders
221         if (!current.dirName().compare(QLatin1String("Release"), Qt::CaseInsensitive)
222             || !current.dirName().compare(QLatin1String("Debug"), Qt::CaseInsensitive))
223             current.cdUp();
224 #endif // Q_OS_WIN
225         testPath = current.absolutePath();
226     }
227     QStringList files;
228
229     const QFileInfo testPathInfo(testPath);
230     if (testPathInfo.isFile()) {
231         if (!testPath.endsWith(QStringLiteral(".qml"))) {
232             qWarning("'%s' does not have the suffix '.qml'.", qPrintable(testPath));
233             return 1;
234         }
235         files << testPath;
236     } else if (testPathInfo.isDir()) {
237         // Scan the test data directory recursively, looking for "tst_*.qml" files.
238         const QStringList filters(QStringLiteral("tst_*.qml"));
239         QDirIterator iter(testPathInfo.absoluteFilePath(), filters, QDir::Files,
240                           QDirIterator::Subdirectories |
241                           QDirIterator::FollowSymlinks);
242         while (iter.hasNext())
243             files += iter.next();
244         files.sort();
245         if (files.isEmpty()) {
246             qWarning("The directory '%s' does not contain any test files matching '%s'",
247                      qPrintable(testPath), qPrintable(filters.front()));
248             return 1;
249         }
250     } else {
251         qWarning("'%s' does not exist under '%s'.",
252                  qPrintable(testPath), qPrintable(QDir::currentPath()));
253         return 1;
254     }
255
256     // Scan through all of the "tst_*.qml" files and run each of them
257     // in turn with a QQuickView.
258 #ifdef QUICK_TEST_SCENEGRAPH
259     if (qtQuick2) {
260         QQuickView view;
261         QTestRootObject rootobj;
262         QEventLoop eventLoop;
263         QObject::connect(view.engine(), SIGNAL(quit()),
264                          &rootobj, SLOT(quit()));
265         QObject::connect(view.engine(), SIGNAL(quit()),
266                          &eventLoop, SLOT(quit()));
267         view.rootContext()->setContextProperty
268             (QLatin1String("qtest"), &rootobj);
269         foreach (const QString &path, imports)
270             view.engine()->addImportPath(path);
271
272         foreach (QString file, files) {
273             QFileInfo fi(file);
274             if (!fi.exists())
275                 continue;
276
277             rootobj.setHasTestCase(false);
278             rootobj.setWindowShown(false);
279             rootobj.hasQuit = false;
280             QString path = fi.absoluteFilePath();
281             if (path.startsWith(QLatin1String(":/")))
282                 view.setSource(QUrl(QLatin1String("qrc:") + path.mid(2)));
283             else
284                 view.setSource(QUrl::fromLocalFile(path));
285
286             if (QTest::printAvailableFunctions)
287                 continue;
288             if (view.status() == QQuickView::Error) {
289                 handleCompileErrors(fi, view);
290                 continue;
291             }
292             if (!rootobj.hasQuit) {
293                 // If the test already quit, then it was performed
294                 // synchronously during setSource().  Otherwise it is
295                 // an asynchronous test and we need to show the window
296                 // and wait for the quit indication.
297                 view.show();
298                 QTest::qWaitForWindowShown(&view);
299                 rootobj.setWindowShown(true);
300                 if (!rootobj.hasQuit && rootobj.hasTestCase())
301                     eventLoop.exec();
302             }
303         }
304     } else
305 #endif
306     {
307         qWarning("No suitable QtQuick1 implementation is available!");
308         return 1;
309     }
310
311     // Flush the current logging stream.
312     QuickTestResult::setProgramName(0);
313
314     //Sometimes delete app cause crash here with some qpa plugins,
315     //so we comment the follow line out to make them happy.
316     //delete app;
317
318     // Return the number of failures as the exit code.
319     return QuickTestResult::exitCode();
320 }
321
322 QT_END_NAMESPACE
323
324 #include "quicktest.moc"