Fix SignalSpy disconnect issue
[profile/ivi/qtdeclarative.git] / src / imports / testlib / TestCase.qml
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 import QtQuick 2.0
43 import QtTest 1.0
44 import "testlogger.js" as TestLogger
45
46 Item {
47     id: testCase
48     visible: false
49     TestUtil {
50         id:util
51     }
52
53     // Name of the test case to prefix the function name in messages.
54     property string name
55
56     // Set to true to start the test running.
57     property bool when: true
58
59     // Set to true once the test has completed.
60     property bool completed: false
61
62     // Set to true when the test is running but not yet complete.
63     property bool running: false
64
65     // Set to true if the test doesn't have to run (because some
66     // other test failed which this one depends on).
67     property bool optional: false
68
69     // Property that is set to true when the main window is shown.
70     // We need to set the property value in an odd way to handle
71     // both qmlviewer and the QtQuickTest module test wrapper.
72     property bool windowShown: util.wrapper ? qtest.windowShown : false
73
74     // Internal private state.  Identifiers prefixed with qtest are reserved.
75     property bool qtest_prevWhen: true
76     property int qtest_testId: -1
77     property bool qtest_componentCompleted : false
78     property var qtest_testCaseResult
79     property var qtest_results: qtest_results_normal
80     TestResult { id: qtest_results_normal }
81     property var qtest_events: qtest_events_normal
82     TestEvent { id: qtest_events_normal }
83
84     function fail(msg) {
85         if (msg === undefined)
86             msg = "";
87         qtest_results.fail(msg, util.callerFile(), util.callerLine())
88         throw new Error("QtQuickTest::fail")
89     }
90
91     function qtest_fail(msg, frame) {
92         if (msg === undefined)
93             msg = "";
94         qtest_results.fail(msg, util.callerFile(frame), util.callerLine(frame))
95         throw new Error("QtQuickTest::fail")
96     }
97
98     function verify(cond, msg) {
99         if (msg === undefined)
100             msg = "";
101         if (!qtest_results.verify(cond, msg, util.callerFile(), util.callerLine()))
102             throw new Error("QtQuickTest::fail")
103     }
104
105     // Determine what is o.
106     // Discussions and reference: http://philrathe.com/articles/equiv
107     // Test suites: http://philrathe.com/tests/equiv
108     // Author: Philippe Rathé <prathe@gmail.com>
109     function qtest_typeof(o) {
110         if (typeof o === "undefined") {
111             return "undefined";
112
113         // consider: typeof null === object
114         } else if (o === null) {
115             return "null";
116
117         } else if (o.constructor === String) {
118             return "string";
119
120         } else if (o.constructor === Boolean) {
121             return "boolean";
122
123         } else if (o.constructor === Number) {
124
125             if (isNaN(o)) {
126                 return "nan";
127             } else {
128                 return "number";
129             }
130         // consider: typeof [] === object
131         } else if (o instanceof Array) {
132             return "array";
133
134         // consider: typeof new Date() === object
135         } else if (o instanceof Date) {
136             return "date";
137
138         // consider: /./ instanceof Object;
139         //           /./ instanceof RegExp;
140         //          typeof /./ === "function"; // => false in IE and Opera,
141         //                                          true in FF and Safari
142         } else if (o instanceof RegExp) {
143             return "regexp";
144
145         } else if (typeof o === "object") {
146             if ("mapFromItem" in o && "mapToItem" in o) {
147                 return "declarativeitem";  // @todo improve detection of declarative items
148             } else if ("x" in o && "y" in o && "z" in o) {
149                 return "vector3d"; // Qt3D vector
150             }
151             return "object";
152         } else if (o instanceof Function) {
153             return "function";
154         } else {
155             return undefined;
156         }
157     }
158
159     // Test for equality
160     // Large parts contain sources from QUnit or http://philrathe.com
161     // Discussions and reference: http://philrathe.com/articles/equiv
162     // Test suites: http://philrathe.com/tests/equiv
163     // Author: Philippe Rathé <prathe@gmail.com>
164     function qtest_compareInternal(act, exp) {
165         var success = false;
166         if (act === exp) {
167             success = true; // catch the most you can
168         } else if (act === null || exp === null || typeof act === "undefined" || typeof exp === "undefined") {
169             success = false; // don't lose time with error prone cases
170         } else {
171             var typeExp = qtest_typeof(exp), typeAct = qtest_typeof(act)
172             if (typeExp !== typeAct) {
173                 // allow object vs string comparison (e.g. for colors)
174                 // else break on different types
175                 if ((typeExp === "string" && (typeAct === "object") || typeAct == "declarativeitem")
176                  || ((typeExp === "object" || typeExp == "declarativeitem") && typeAct === "string")) {
177                     success = (act == exp)
178                 }
179             } else if (typeExp === "string" || typeExp === "boolean" ||
180                        typeExp === "null" || typeExp === "undefined") {
181                 if (exp instanceof act.constructor || act instanceof exp.constructor) {
182                     // to catch short annotaion VS 'new' annotation of act declaration
183                     // e.g. var i = 1;
184                     //      var j = new Number(1);
185                     success = (act == exp)
186                 } else {
187                     success = (act === exp)
188                 }
189             } else if (typeExp === "nan") {
190                 success = isNaN(act);
191             } else if (typeExp === "number") {
192                 // Use act fuzzy compare if the two values are floats
193                 if (Math.abs(act - exp) <= 0.00001) {
194                     success = true
195                 }
196             } else if (typeExp === "array") {
197                 success = qtest_compareInternalArrays(act, exp)
198             } else if (typeExp === "object") {
199                 success = qtest_compareInternalObjects(act, exp)
200             } else if (typeExp === "declarativeitem") {
201                 success = qtest_compareInternalObjects(act, exp) // @todo improve comparison of declarative items
202             } else if (typeExp === "vector3d") {
203                 success = (Math.abs(act.x - exp.x) <= 0.00001 &&
204                            Math.abs(act.y - exp.y) <= 0.00001 &&
205                            Math.abs(act.z - exp.z) <= 0.00001)
206             } else if (typeExp === "date") {
207                 success = (act.valueOf() === exp.valueOf())
208             } else if (typeExp === "regexp") {
209                 success = (act.source === exp.source && // the regex itself
210                            act.global === exp.global && // and its modifers (gmi) ...
211                            act.ignoreCase === exp.ignoreCase &&
212                            act.multiline === exp.multiline)
213             }
214         }
215         return success
216     }
217
218     function qtest_compareInternalObjects(act, exp) {
219         var i;
220         var eq = true; // unless we can proove it
221         var aProperties = [], bProperties = []; // collection of strings
222
223         // comparing constructors is more strict than using instanceof
224         if (act.constructor !== exp.constructor) {
225             return false;
226         }
227
228         for (i in act) { // be strict: don't ensures hasOwnProperty and go deep
229             aProperties.push(i); // collect act's properties
230             if (!qtest_compareInternal(act[i], exp[i])) {
231                 eq = false;
232                 break;
233             }
234         }
235
236         for (i in exp) {
237             bProperties.push(i); // collect exp's properties
238         }
239
240         // Ensures identical properties name
241         return eq && qtest_compareInternal(aProperties.sort(), bProperties.sort());
242
243     }
244
245     function qtest_compareInternalArrays(actual, expected) {
246         if (actual.length != expected.length) {
247             return false
248         }
249
250         for (var i = 0, len = actual.length; i < len; i++) {
251             if (!qtest_compareInternal(actual[i], expected[i])) {
252                 return false
253             }
254         }
255
256         return true
257     }
258
259     function qtest_formatValue(value) {
260         if (qtest_typeof(value) == "object") {
261             if ("x" in value && "y" in value && "z" in value) {
262                 return "Qt.vector3d(" + value.x + ", " +
263                        value.y + ", " + value.z + ")"
264             }
265             try {
266                 return JSON.stringify(value)
267             } catch (ex) {
268                 // stringify might fail (e.g. due to circular references)
269             }
270         }
271         return value
272     }
273
274     function compare(actual, expected, msg) {
275         var act = testCase.qtest_formatValue(actual)
276         var exp = testCase.qtest_formatValue(expected)
277
278         var success = qtest_compareInternal(actual, expected)
279         if (msg === undefined) {
280             if (success)
281                 msg = "COMPARE()"
282             else
283                 msg = "Compared values are not the same"
284         }
285         if (!qtest_results.compare(success, msg, act, exp, util.callerFile(), util.callerLine())) {
286             throw new Error("QtQuickTest::fail")
287         }
288     }
289
290     function tryCompare(obj, prop, value, timeout) {
291         if (!timeout)
292             timeout = 5000
293         if (!qtest_compareInternal(obj[prop], value))
294             wait(0)
295         var i = 0
296         while (i < timeout && !qtest_compareInternal(obj[prop], value)) {
297             wait(50)
298             i += 50
299         }
300         var actual = obj[prop]
301         var act = testCase.qtest_formatValue(actual)
302         var exp = testCase.qtest_formatValue(value)
303         var success = qtest_compareInternal(actual, value)
304         if (!qtest_results.compare(success, "property " + prop, act, exp, util.callerFile(), util.callerLine()))
305             throw new Error("QtQuickTest::fail")
306     }
307
308     function skip(msg) {
309         if (msg === undefined)
310             msg = ""
311         qtest_results.skip(msg, util.callerFile(), util.callerLine())
312         throw new Error("QtQuickTest::skip")
313     }
314
315     function expectFail(tag, msg) {
316         if (tag === undefined) {
317             warn("tag argument missing from expectFail()")
318             tag = ""
319         }
320         if (msg === undefined) {
321             warn("message argument missing from expectFail()")
322             msg = ""
323         }
324         if (!qtest_results.expectFail(tag, msg, util.callerFile(), util.callerLine()))
325             throw new Error("QtQuickTest::expectFail")
326     }
327
328     function expectFailContinue(tag, msg) {
329         if (tag === undefined) {
330             warn("tag argument missing from expectFailContinue()")
331             tag = ""
332         }
333         if (msg === undefined) {
334             warn("message argument missing from expectFailContinue()")
335             msg = ""
336         }
337         if (!qtest_results.expectFailContinue(tag, msg, util.callerFile(), util.callerLine()))
338             throw new Error("QtQuickTest::expectFail")
339     }
340
341     function warn(msg) {
342         if (msg === undefined)
343             msg = ""
344         qtest_results.warn(msg, util.callerFile(), util.callerLine());
345     }
346
347     function ignoreWarning(msg) {
348         if (msg === undefined)
349             msg = ""
350         qtest_results.ignoreWarning(msg)
351     }
352
353     function wait(ms) {
354         qtest_results.wait(ms)
355     }
356
357     function sleep(ms) {
358         qtest_results.sleep(ms)
359     }
360
361     function keyPress(key, modifiers, delay) {
362         if (modifiers === undefined)
363             modifiers = Qt.NoModifier
364         if (delay == undefined)
365             delay = -1
366         if (!qtest_events.keyPress(key, modifiers, delay))
367             qtest_fail("window not shown", 2)
368     }
369
370     function keyRelease(key, modifiers, delay) {
371         if (modifiers === undefined)
372             modifiers = Qt.NoModifier
373         if (delay == undefined)
374             delay = -1
375         if (!qtest_events.keyRelease(key, modifiers, delay))
376             qtest_fail("window not shown", 2)
377     }
378
379     function keyClick(key, modifiers, delay) {
380         if (modifiers === undefined)
381             modifiers = Qt.NoModifier
382         if (delay == undefined)
383             delay = -1
384         if (!qtest_events.keyClick(key, modifiers, delay))
385             qtest_fail("window not shown", 2)
386     }
387
388     function mousePress(item, x, y, button, modifiers, delay) {
389         if (button === undefined)
390             button = Qt.LeftButton
391         if (modifiers === undefined)
392             modifiers = Qt.NoModifier
393         if (delay == undefined)
394             delay = -1
395         if (!qtest_events.mousePress(item, x, y, button, modifiers, delay))
396             qtest_fail("window not shown", 2)
397     }
398
399     function mouseRelease(item, x, y, button, modifiers, delay) {
400         if (button === undefined)
401             button = Qt.LeftButton
402         if (modifiers === undefined)
403             modifiers = Qt.NoModifier
404         if (delay == undefined)
405             delay = -1
406         if (!qtest_events.mouseRelease(item, x, y, button, modifiers, delay))
407             qtest_fail("window not shown", 2)
408     }
409
410     function mouseClick(item, x, y, button, modifiers, delay) {
411         if (button === undefined)
412             button = Qt.LeftButton
413         if (modifiers === undefined)
414             modifiers = Qt.NoModifier
415         if (delay == undefined)
416             delay = -1
417         if (!qtest_events.mouseClick(item, x, y, button, modifiers, delay))
418             qtest_fail("window not shown", 2)
419     }
420
421     function mouseDoubleClick(item, x, y, button, modifiers, delay) {
422         if (button === undefined)
423             button = Qt.LeftButton
424         if (modifiers === undefined)
425             modifiers = Qt.NoModifier
426         if (delay == undefined)
427             delay = -1
428         if (!qtest_events.mouseDoubleClick(item, x, y, button, modifiers, delay))
429             qtest_fail("window not shown", 2)
430     }
431
432     function mouseMove(item, x, y, delay, buttons) {
433         if (delay == undefined)
434             delay = -1
435         if (buttons == undefined)
436             buttons = Qt.NoButton
437         if (!qtest_events.mouseMove(item, x, y, delay, buttons))
438             qtest_fail("window not shown", 2)
439     }
440
441     function mouseWheel(item, x, y, delta, buttons, modifiers, delay, orientation) {
442         if (delay == undefined)
443             delay = -1
444         if (buttons == undefined)
445             buttons = Qt.NoButton
446         if (modifiers === undefined)
447             modifiers = Qt.NoModifier
448         if (delta == undefined)
449             delta = 0
450         if (orientation == undefined)
451             orientation = Qt.Vertical
452         if (!qtest_events.mouseWheel(item, x, y, buttons, modifiers, delta, delay, orientation))
453             qtest_fail("window not shown", 2)
454    }
455
456
457     // Functions that can be overridden in subclasses for init/cleanup duties.
458     function initTestCase() {}
459     function cleanupTestCase() {}
460     function init() {}
461     function cleanup() {}
462
463     function qtest_runInternal(prop, arg) {
464         try {
465             qtest_testCaseResult = testCase[prop](arg)
466         } catch (e) {
467             qtest_testCaseResult = []
468             if (e.message.indexOf("QtQuickTest::") != 0) {
469                 // Test threw an unrecognized exception - fail.
470                 qtest_results.fail("Uncaught exception: " + e.message,
471                              e.fileName, e.lineNumber)
472             }
473         }
474         return !qtest_results.failed
475     }
476
477     function qtest_runFunction(prop, arg) {
478         qtest_runInternal("init")
479         if (!qtest_results.skipped) {
480             qtest_runInternal(prop, arg)
481             qtest_results.finishTestData()
482             qtest_runInternal("cleanup")
483             qtest_results.finishTestDataCleanup()
484         }
485     }
486
487     function qtest_runBenchmarkFunction(prop, arg) {
488         qtest_results.startMeasurement()
489         do {
490             qtest_results.beginDataRun()
491             do {
492                 // Run the initialization function.
493                 qtest_runInternal("init")
494                 if (qtest_results.skipped)
495                     break
496
497                 // Execute the benchmark function.
498                 if (prop.indexOf("benchmark_once_") != 0)
499                     qtest_results.startBenchmark(TestResult.RepeatUntilValidMeasurement, qtest_results.dataTag)
500                 else
501                     qtest_results.startBenchmark(TestResult.RunOnce, qtest_results.dataTag)
502                 while (!qtest_results.isBenchmarkDone()) {
503                     var success = qtest_runInternal(prop, arg)
504                     qtest_results.finishTestData()
505                     if (!success)
506                         break
507                     qtest_results.nextBenchmark()
508                 }
509                 qtest_results.stopBenchmark()
510
511                 // Run the cleanup function.
512                 qtest_runInternal("cleanup")
513                 qtest_results.finishTestDataCleanup()
514             } while (!qtest_results.measurementAccepted())
515             qtest_results.endDataRun()
516         } while (qtest_results.needsMoreMeasurements())
517     }
518
519     function qtest_run() {
520         if (util.printAvailableFunctions) {
521             completed = true
522             return
523         }
524
525         if (TestLogger.log_start_test()) {
526             qtest_results.reset()
527             qtest_results.testCaseName = name
528             qtest_results.startLogging()
529         } else {
530             qtest_results.testCaseName = name
531         }
532         running = true
533
534         // Check the run list to see if this class is mentioned.
535         var functionsToRun = qtest_results.functionsToRun
536         if (functionsToRun.length > 0) {
537             var found = false
538             var list = []
539             if (name.length > 0) {
540                 var prefix = name + "::"
541                 for (var index in functionsToRun) {
542                     if (functionsToRun[index].indexOf(prefix) == 0) {
543                         list.push(functionsToRun[index])
544                         found = true
545                     }
546                 }
547             }
548             if (!found) {
549                 completed = true
550                 if (!TestLogger.log_complete_test(qtest_testId)) {
551                     qtest_results.stopLogging()
552                     Qt.quit()
553                 }
554                 qtest_results.testCaseName = ""
555                 return
556             }
557             functionsToRun = list
558         }
559
560         // Run the initTestCase function.
561         qtest_results.functionName = "initTestCase"
562         var runTests = true
563         if (!qtest_runInternal("initTestCase"))
564             runTests = false
565         qtest_results.finishTestData()
566         qtest_results.finishTestDataCleanup()
567         qtest_results.finishTestFunction()
568
569         // Run the test methods.
570         var testList = []
571         if (runTests) {
572             for (var prop in testCase) {
573                 if (prop.indexOf("test_") != 0 && prop.indexOf("benchmark_") != 0)
574                     continue
575                 var tail = prop.lastIndexOf("_data");
576                 if (tail != -1 && tail == (prop.length - 5))
577                     continue
578                 testList.push(prop)
579             }
580             testList.sort()
581         }
582         var checkNames = (functionsToRun.length > 0)
583         for (var index in testList) {
584             var prop = testList[index]
585             var datafunc = prop + "_data"
586             var isBenchmark = (prop.indexOf("benchmark_") == 0)
587             if (checkNames) {
588                 var index = functionsToRun.indexOf(name + "::" + prop)
589                 if (index < 0)
590                     continue
591                 functionsToRun.splice(index, 1)
592             }
593             qtest_results.functionName = prop
594             if (datafunc in testCase) {
595                 if (qtest_runInternal(datafunc)) {
596                     var table = qtest_testCaseResult
597                     var haveData = false
598                     qtest_results.initTestTable()
599                     for (var index in table) {
600                         haveData = true
601                         var row = table[index]
602                         if (!row.tag)
603                             row.tag = "row " + index    // Must have something
604                         qtest_results.dataTag = row.tag
605                         if (isBenchmark)
606                             qtest_runBenchmarkFunction(prop, row)
607                         else
608                             qtest_runFunction(prop, row)
609                         qtest_results.dataTag = ""
610                     }
611                     if (!haveData)
612                         qtest_results.warn("no data supplied for " + prop + "() by " + datafunc + "()"
613                                            , util.callerFile(), util.callerLine());
614                     qtest_results.clearTestTable()
615                 }
616             } else if (isBenchmark) {
617                 qtest_runBenchmarkFunction(prop, null, isBenchmark)
618             } else {
619                 qtest_runFunction(prop, null, isBenchmark)
620             }
621             qtest_results.finishTestFunction()
622             qtest_results.skipped = false
623         }
624
625         // Run the cleanupTestCase function.
626         qtest_results.skipped = false
627         qtest_results.functionName = "cleanupTestCase"
628         qtest_runInternal("cleanupTestCase")
629
630         // Complain about missing functions that we were supposed to run.
631         if (functionsToRun.length > 0)
632             qtest_results.fail("Could not find functions: " + functionsToRun, "", 0)
633
634         // Clean up and exit.
635         running = false
636         completed = true
637         qtest_results.finishTestData()
638         qtest_results.finishTestDataCleanup()
639         qtest_results.finishTestFunction()
640         qtest_results.functionName = ""
641
642         // Stop if there are no more tests to be run.
643         if (!TestLogger.log_complete_test(qtest_testId)) {
644             qtest_results.stopLogging()
645             Qt.quit()
646         }
647         qtest_results.testCaseName = ""
648     }
649
650     onWhenChanged: {
651         if (when != qtest_prevWhen) {
652             qtest_prevWhen = when
653             if (when && !completed && !running && qtest_componentCompleted)
654                 qtest_run()
655         }
656     }
657
658     onOptionalChanged: {
659         if (!completed) {
660             if (optional)
661                 TestLogger.log_optional_test(qtest_testId)
662             else
663                 TestLogger.log_mandatory_test(qtest_testId)
664         }
665     }
666
667     // The test framework will set util.windowShown when the
668     // window is actually shown.  If we are running with qmlviewer,
669     // then this won't happen.  So we use a timer instead.
670     Timer {
671         id: qtest_windowShowTimer
672         interval: 100
673         repeat: false
674         onTriggered: { windowShown = true }
675     }
676
677     Component.onCompleted: {
678         qtest.hasTestCase = true;
679         qtest_componentCompleted = true;
680
681         if (util.printAvailableFunctions) {
682             var testList = []
683             for (var prop in testCase) {
684                 if (prop.indexOf("test_") != 0 && prop.indexOf("benchmark_") != 0)
685                     continue
686                 var tail = prop.lastIndexOf("_data");
687                 if (tail != -1 && tail == (prop.length - 5))
688                     continue
689                 // Note: cannot run functions in TestCase elements
690                 // that lack a name.
691                 if (name.length > 0)
692                     testList.push(name + "::" + prop + "()")
693             }
694             testList.sort()
695             for (var index in testList)
696                 console.log(testList[index])
697             return
698         }
699         qtest_testId = TestLogger.log_register_test(name)
700         if (optional)
701             TestLogger.log_optional_test(qtest_testId)
702         qtest_prevWhen = when
703         var isQmlViewer = util.wrapper ? false : true
704         if (isQmlViewer)
705             qtest_windowShowTimer.running = true
706         if (when && !completed && !running)
707             qtest_run()
708     }
709 }