fix qmltest bugs
[profile/ivi/qtdeclarative.git] / src / imports / testlib / TestCase.qml
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 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 variant qtest_testCaseResult
78     property variant qtest_results: qtest_results_normal
79     TestResult { id: qtest_results_normal }
80     property variant qtest_events: qtest_events_normal
81     TestEvent { id: qtest_events_normal }
82
83     function fail(msg) {
84         if (msg === undefined)
85             msg = "";
86         qtest_results.fail(msg, util.callerFile(), util.callerLine())
87         throw new Error("QtQuickTest::fail")
88     }
89
90     function qtest_fail(msg, frame) {
91         if (msg === undefined)
92             msg = "";
93         qtest_results.fail(msg, util.callerFile(frame), util.callerLine(frame))
94         throw new Error("QtQuickTest::fail")
95     }
96
97     function verify(cond, msg) {
98         if (msg === undefined)
99             msg = "";
100         if (!qtest_results.verify(cond, msg, util.callerFile(), util.callerLine()))
101             throw new Error("QtQuickTest::fail")
102     }
103
104     // Determine what is o.
105     // Discussions and reference: http://philrathe.com/articles/equiv
106     // Test suites: http://philrathe.com/tests/equiv
107     // Author: Philippe Rathé <prathe@gmail.com>
108     function qtest_typeof(o) {
109         if (typeof o === "undefined") {
110             return "undefined";
111
112         // consider: typeof null === object
113         } else if (o === null) {
114             return "null";
115
116         } else if (o.constructor === String) {
117             return "string";
118
119         } else if (o.constructor === Boolean) {
120             return "boolean";
121
122         } else if (o.constructor === Number) {
123
124             if (isNaN(o)) {
125                 return "nan";
126             } else {
127                 return "number";
128             }
129         // consider: typeof [] === object
130         } else if (o instanceof Array) {
131             return "array";
132
133         // consider: typeof new Date() === object
134         } else if (o instanceof Date) {
135             return "date";
136
137         // consider: /./ instanceof Object;
138         //           /./ instanceof RegExp;
139         //          typeof /./ === "function"; // => false in IE and Opera,
140         //                                          true in FF and Safari
141         } else if (o instanceof RegExp) {
142             return "regexp";
143
144         } else if (typeof o === "object") {
145             if ("mapFromItem" in o && "mapToItem" in o) {
146                 return "declarativeitem";  // @todo improve detection of declarative items
147             } else if ("x" in o && "y" in o && "z" in o) {
148                 console.log("typeof debug:" + 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" || typeExp === "number" ||
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 = qtest_formatValue(actual)
276         var exp = 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 = qtest_formatValue(actual)
302         var exp = 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.skipSingle(msg, util.callerFile(), util.callerLine())
312         throw new Error("QtQuickTest::skip")
313     }
314
315     function skipAll(msg) {
316         if (msg === undefined)
317             msg = ""
318         qtest_results.skipAll(msg, util.callerFile(), util.callerLine())
319         throw new Error("QtQuickTest::skip")
320     }
321
322     function expectFail(tag, msg) {
323         if (tag === undefined) {
324             warn("tag argument missing from expectFail()")
325             tag = ""
326         }
327         if (msg === undefined) {
328             warn("message argument missing from expectFail()")
329             msg = ""
330         }
331         if (!qtest_results.expectFail(tag, msg, util.callerFile(), util.callerLine()))
332             throw new Error("QtQuickTest::expectFail")
333     }
334
335     function expectFailContinue(tag, msg) {
336         if (tag === undefined) {
337             warn("tag argument missing from expectFailContinue()")
338             tag = ""
339         }
340         if (msg === undefined) {
341             warn("message argument missing from expectFailContinue()")
342             msg = ""
343         }
344         if (!qtest_results.expectFailContinue(tag, msg, util.callerFile(), util.callerLine()))
345             throw new Error("QtQuickTest::expectFail")
346     }
347
348     function warn(msg) {
349         if (msg === undefined)
350             msg = ""
351         qtest_results.warn(msg);
352     }
353
354     function ignoreWarning(msg) {
355         if (msg === undefined)
356             msg = ""
357         qtest_results.ignoreWarning(msg)
358     }
359
360     function wait(ms) {
361         qtest_results.wait(ms)
362     }
363
364     function sleep(ms) {
365         qtest_results.sleep(ms)
366     }
367
368     function keyPress(key, modifiers, delay) {
369         if (modifiers === undefined)
370             modifiers = Qt.NoModifier
371         if (delay == undefined)
372             delay = -1
373         if (!qtest_events.keyPress(key, modifiers, delay))
374             qtest_fail("window not shown", 2)
375     }
376
377     function keyRelease(key, modifiers, delay) {
378         if (modifiers === undefined)
379             modifiers = Qt.NoModifier
380         if (delay == undefined)
381             delay = -1
382         if (!qtest_events.keyRelease(key, modifiers, delay))
383             qtest_fail("window not shown", 2)
384     }
385
386     function keyClick(key, modifiers, delay) {
387         if (modifiers === undefined)
388             modifiers = Qt.NoModifier
389         if (delay == undefined)
390             delay = -1
391         if (!qtest_events.keyClick(key, modifiers, delay))
392             qtest_fail("window not shown", 2)
393     }
394
395     function mousePress(item, x, y, button, modifiers, delay) {
396         if (button === undefined)
397             button = Qt.LeftButton
398         if (modifiers === undefined)
399             modifiers = Qt.NoModifier
400         if (delay == undefined)
401             delay = -1
402         if (!qtest_events.mousePress(item, x, y, button, modifiers, delay))
403             qtest_fail("window not shown", 2)
404     }
405
406     function mouseRelease(item, x, y, button, modifiers, delay) {
407         if (button === undefined)
408             button = Qt.LeftButton
409         if (modifiers === undefined)
410             modifiers = Qt.NoModifier
411         if (delay == undefined)
412             delay = -1
413         if (!qtest_events.mouseRelease(item, x, y, button, modifiers, delay))
414             qtest_fail("window not shown", 2)
415     }
416
417     function mouseClick(item, x, y, button, modifiers, delay) {
418         if (button === undefined)
419             button = Qt.LeftButton
420         if (modifiers === undefined)
421             modifiers = Qt.NoModifier
422         if (delay == undefined)
423             delay = -1
424         if (!qtest_events.mouseClick(item, x, y, button, modifiers, delay))
425             qtest_fail("window not shown", 2)
426     }
427
428     function mouseDoubleClick(item, x, y, button, modifiers, delay) {
429         if (button === undefined)
430             button = Qt.LeftButton
431         if (modifiers === undefined)
432             modifiers = Qt.NoModifier
433         if (delay == undefined)
434             delay = -1
435         if (!qtest_events.mouseDoubleClick(item, x, y, button, modifiers, delay))
436             qtest_fail("window not shown", 2)
437     }
438
439     function mouseMove(item, x, y, delay) {
440         if (delay == undefined)
441             delay = -1
442         if (!qtest_events.mouseMove(item, x, y, delay))
443             qtest_fail("window not shown", 2)
444     }
445
446     // Functions that can be overridden in subclasses for init/cleanup duties.
447     function initTestCase() {}
448     function cleanupTestCase() {}
449     function init() {}
450     function cleanup() {}
451
452     function qtest_runInternal(prop, arg) {
453         try {
454             qtest_testCaseResult = testCase[prop](arg)
455         } catch (e) {
456             qtest_testCaseResult = []
457             if (e.message.indexOf("QtQuickTest::") != 0) {
458                 // Test threw an unrecognized exception - fail.
459                 qtest_results.fail("Uncaught exception: " + e.message,
460                              e.fileName, e.lineNumber)
461             }
462         }
463         return !qtest_results.dataFailed
464     }
465
466     function qtest_runFunction(prop, arg) {
467         qtest_results.functionType = TestResult.InitFunc
468         qtest_runInternal("init")
469         if (!qtest_results.skipped) {
470             qtest_results.functionType = TestResult.Func
471             qtest_runInternal(prop, arg)
472             qtest_results.functionType = TestResult.CleanupFunc
473             qtest_runInternal("cleanup")
474         }
475         qtest_results.functionType = TestResult.NoWhere
476     }
477
478     function qtest_runBenchmarkFunction(prop, arg) {
479         qtest_results.startMeasurement()
480         do {
481             qtest_results.beginDataRun()
482             do {
483                 // Run the initialization function.
484                 qtest_results.functionType = TestResult.InitFunc
485                 qtest_runInternal("init")
486                 if (qtest_results.skipped)
487                     break
488
489                 // Execute the benchmark function.
490                 qtest_results.functionType = TestResult.Func
491                 if (prop.indexOf("benchmark_once_") != 0)
492                     qtest_results.startBenchmark(TestResult.RepeatUntilValidMeasurement, qtest_results.dataTag)
493                 else
494                     qtest_results.startBenchmark(TestResult.RunOnce, qtest_results.dataTag)
495                 while (!qtest_results.isBenchmarkDone()) {
496                     if (!qtest_runInternal(prop, arg))
497                         break
498                     qtest_results.nextBenchmark()
499                 }
500                 qtest_results.stopBenchmark()
501
502                 // Run the cleanup function.
503                 qtest_results.functionType = TestResult.CleanupFunc
504                 qtest_runInternal("cleanup")
505                 qtest_results.functionType = TestResult.NoWhere
506             } while (!qtest_results.measurementAccepted())
507             qtest_results.endDataRun()
508         } while (qtest_results.needsMoreMeasurements())
509     }
510
511     function qtest_run() {
512         if (util.printAvailableFunctions) {
513             completed = true
514             return
515         }
516
517         if (TestLogger.log_start_test()) {
518             qtest_results.reset()
519             qtest_results.testCaseName = name
520             qtest_results.startLogging()
521         } else {
522             qtest_results.testCaseName = name
523         }
524         running = true
525
526         // Check the run list to see if this class is mentioned.
527         var functionsToRun = qtest_results.functionsToRun
528         if (functionsToRun.length > 0) {
529             var found = false
530             var list = []
531             if (name.length > 0) {
532                 var prefix = name + "::"
533                 for (var index in functionsToRun) {
534                     if (functionsToRun[index].indexOf(prefix) == 0) {
535                         list.push(functionsToRun[index])
536                         found = true
537                     }
538                 }
539             }
540             if (!found) {
541                 completed = true
542                 if (!TestLogger.log_complete_test(qtest_testId)) {
543                     qtest_results.stopLogging()
544                     Qt.quit()
545                 }
546                 qtest_results.testCaseName = ""
547                 return
548             }
549             functionsToRun = list
550         }
551
552         // Run the initTestCase function.
553         qtest_results.functionName = "initTestCase"
554         qtest_results.functionType = TestResult.InitFunc
555         var runTests = true
556         if (!qtest_runInternal("initTestCase"))
557             runTests = false
558         qtest_results.finishTestFunction()
559
560         // Run the test methods.
561         var testList = []
562         if (runTests) {
563             for (var prop in testCase) {
564                 if (prop.indexOf("test_") != 0 && prop.indexOf("benchmark_") != 0)
565                     continue
566                 var tail = prop.lastIndexOf("_data");
567                 if (tail != -1 && tail == (prop.length - 5))
568                     continue
569                 testList.push(prop)
570             }
571             testList.sort()
572         }
573         var checkNames = (functionsToRun.length > 0)
574         for (var index in testList) {
575             var prop = testList[index]
576             var datafunc = prop + "_data"
577             var isBenchmark = (prop.indexOf("benchmark_") == 0)
578             if (checkNames) {
579                 var index = functionsToRun.indexOf(name + "::" + prop)
580                 if (index < 0)
581                     continue
582                 functionsToRun.splice(index, 1)
583             }
584             qtest_results.functionName = prop
585             if (datafunc in testCase) {
586                 qtest_results.functionType = TestResult.DataFunc
587                 if (qtest_runInternal(datafunc)) {
588                     var table = qtest_testCaseResult
589                     var haveData = false
590                     qtest_results.initTestTable()
591                     for (var index in table) {
592                         haveData = true
593                         var row = table[index]
594                         if (!row.tag)
595                             row.tag = "row " + index    // Must have something
596                         qtest_results.dataTag = row.tag
597                         if (isBenchmark)
598                             qtest_runBenchmarkFunction(prop, row)
599                         else
600                             qtest_runFunction(prop, row)
601                         qtest_results.dataTag = ""
602                     }
603                     if (!haveData)
604                         qtest_results.warn("no data supplied for " + prop + "() by " + datafunc + "()")
605                     qtest_results.clearTestTable()
606                 }
607             } else if (isBenchmark) {
608                 qtest_runBenchmarkFunction(prop, null, isBenchmark)
609             } else {
610                 qtest_runFunction(prop, null, isBenchmark)
611             }
612             qtest_results.finishTestFunction()
613             qtest_results.skipped = false
614         }
615
616         // Run the cleanupTestCase function.
617         qtest_results.skipped = false
618         qtest_results.functionName = "cleanupTestCase"
619         qtest_results.functionType = TestResult.CleanupFunc
620         qtest_runInternal("cleanupTestCase")
621
622         // Complain about missing functions that we were supposed to run.
623         if (functionsToRun.length > 0)
624             qtest_results.fail("Could not find functions: " + functionsToRun, "", 0)
625
626         // Clean up and exit.
627         running = false
628         completed = true
629         qtest_results.finishTestFunction()
630         qtest_results.functionName = ""
631
632         // Stop if there are no more tests to be run.
633         if (!TestLogger.log_complete_test(qtest_testId)) {
634             qtest_results.stopLogging()
635             Qt.quit()
636         }
637         qtest_results.testCaseName = ""
638     }
639
640     onWhenChanged: {
641         if (when != qtest_prevWhen) {
642             qtest_prevWhen = when
643             if (when && !completed && !running)
644                 qtest_run()
645         }
646     }
647
648     onOptionalChanged: {
649         if (!completed) {
650             if (optional)
651                 TestLogger.log_optional_test(qtest_testId)
652             else
653                 TestLogger.log_mandatory_test(qtest_testId)
654         }
655     }
656
657     // The test framework will set util.windowShown when the
658     // window is actually shown.  If we are running with qmlviewer,
659     // then this won't happen.  So we use a timer instead.
660     Timer {
661         id: qtest_windowShowTimer
662         interval: 100
663         repeat: false
664         onTriggered: { windowShown = true }
665     }
666
667     Component.onCompleted: {
668         if (util.printAvailableFunctions) {
669             var testList = []
670             for (var prop in testCase) {
671                 if (prop.indexOf("test_") != 0 && prop.indexOf("benchmark_") != 0)
672                     continue
673                 var tail = prop.lastIndexOf("_data");
674                 if (tail != -1 && tail == (prop.length - 5))
675                     continue
676                 // Note: cannot run functions in TestCase elements
677                 // that lack a name.
678                 if (name.length > 0)
679                     testList.push(name + "::" + prop + "()")
680             }
681             testList.sort()
682             for (var index in testList)
683                 console.log(testList[index])
684             return
685         }
686         qtest_testId = TestLogger.log_register_test(name)
687         if (optional)
688             TestLogger.log_optional_test(qtest_testId)
689         qtest_prevWhen = when
690         var isQmlViewer = util.wrapper ? false : true
691         if (isQmlViewer)
692             qtest_windowShowTimer.running = true
693         if (when && !completed && !running)
694             qtest_run()
695     }
696 }