diff --git a/js/js.libraries/src/junit/core.kt b/js/js.libraries/src/junit/core.kt new file mode 100644 index 00000000000..a426187b2b5 --- /dev/null +++ b/js/js.libraries/src/junit/core.kt @@ -0,0 +1,4 @@ +package org.junit; + +native +annotation class Test(name : String = "") {} \ No newline at end of file diff --git a/js/js.tests/test/org/jetbrains/k2js/test/BasicTest.java b/js/js.tests/test/org/jetbrains/k2js/test/BasicTest.java index 408014b2c3d..9befa4ba160 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/BasicTest.java +++ b/js/js.tests/test/org/jetbrains/k2js/test/BasicTest.java @@ -102,7 +102,7 @@ public abstract class BasicTest extends TestWithEnvironment { @NotNull MainCallParameters mainCallParameters, @NotNull EnumSet ecmaVersions) throws Exception { for (EcmaVersion version : ecmaVersions) { - TranslationUtils.translateFiles(getProject(), files, getOutputFilePath(testName, version), mainCallParameters, version); + TranslationUtils.translateFiles(getProject(), files, getOutputFilePath(testName, version), mainCallParameters, version, null); } } diff --git a/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibTestToJSTest.java b/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibTestToJSTest.java new file mode 100644 index 00000000000..a9c81396158 --- /dev/null +++ b/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibTestToJSTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.k2js.test.semantics; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.cli.common.ExitCode; +import org.jetbrains.jet.cli.js.K2JSCompiler; +import org.jetbrains.jet.cli.js.K2JSCompilerArguments; +import org.jetbrains.k2js.config.Config; +import org.jetbrains.k2js.config.EcmaVersion; +import org.jetbrains.k2js.facade.MainCallParameters; +import org.jetbrains.k2js.test.SingleFileTranslationTest; + +import java.io.File; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; + +/** + */ +public class StdLibTestToJSTest extends StdLibToJSTest { + public void testCompileJavaScriptFiles() throws Exception { + + generateJavaScriptFiles(EcmaVersion.all(), + "libraries/stdlib/test", + "js/SimpleTest.kt"); + } +} diff --git a/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibToJSTest.java b/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibToJSTest.java index e46d16a5dd7..99b47af5d79 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibToJSTest.java +++ b/js/js.tests/test/org/jetbrains/k2js/test/semantics/StdLibToJSTest.java @@ -24,7 +24,6 @@ import org.jetbrains.jet.cli.js.K2JSCompiler; import org.jetbrains.jet.cli.js.K2JSCompilerArguments; import org.jetbrains.k2js.config.Config; import org.jetbrains.k2js.config.EcmaVersion; -import org.jetbrains.k2js.facade.MainCallParameters; import org.jetbrains.k2js.test.SingleFileTranslationTest; import java.io.File; @@ -34,27 +33,24 @@ import java.util.Set; /** */ -public final class StdLibToJSTest extends SingleFileTranslationTest { +public class StdLibToJSTest extends SingleFileTranslationTest { public StdLibToJSTest() { super("stdlib/"); } - public void testCompileStandardLibraryFiles() throws Exception { + public void testCompileJavaScriptFiles() throws Exception { - generateJavaScriptFiles(MainCallParameters.noCall(), EcmaVersion.all(), - "kotlin/Preconditions.kt", - "kotlin/dom/Dom.kt", - "kotlin/support/AbstractIterator.kt" - ); + generateJavaScriptFiles(EcmaVersion.all(), + "libraries/stdlib/src", + "kotlin/Preconditions.kt", "kotlin/dom/Dom.kt", "kotlin/support/AbstractIterator.kt"); } - protected void generateJavaScriptFiles(@NotNull MainCallParameters mainCallParameters, - @NotNull EnumSet ecmaVersions, - String... stdLibFiles) throws Exception { + protected void generateJavaScriptFiles(@NotNull EnumSet ecmaVersions, + @NotNull String sourceDir, @NotNull String... stdLibFiles) throws Exception { List files = Lists.newArrayList(); - File stdlibDir = new File("libraries/stdlib/src"); + File stdlibDir = new File(sourceDir); assertTrue("Cannot find stdlib source: " + stdlibDir, stdlibDir.exists()); for (String file : stdLibFiles) { files.add(new File(stdlibDir, file).getPath()); @@ -78,12 +74,12 @@ public final class StdLibToJSTest extends SingleFileTranslationTest { // now lets try invoke the compiler for (EcmaVersion version : ecmaVersions) { - System.out.println("Compiling with version: " + version); K2JSCompiler compiler = new K2JSCompiler(); K2JSCompilerArguments arguments = new K2JSCompilerArguments(); arguments.outputFile = getOutputFilePath(getTestName(false) + ".compiler.kt", version); arguments.sourceFiles = files; arguments.verbose = true; + System.out.println("Compiling with version: " + version + " to: " + arguments.outputFile); ExitCode answer = compiler.exec(System.out, arguments); assertEquals("Compile failed", ExitCode.OK, answer); } diff --git a/js/js.tests/test/org/jetbrains/k2js/test/utils/TranslationUtils.java b/js/js.tests/test/org/jetbrains/k2js/test/utils/TranslationUtils.java index 76c88714074..d3f5cadbc7f 100644 --- a/js/js.tests/test/org/jetbrains/k2js/test/utils/TranslationUtils.java +++ b/js/js.tests/test/org/jetbrains/k2js/test/utils/TranslationUtils.java @@ -48,17 +48,20 @@ public final class TranslationUtils { public static void translateFile(@NotNull Project project, @NotNull String inputFile, @NotNull String outputFile, @NotNull MainCallParameters mainCallParameters, @NotNull EcmaVersion version) throws Exception { - translateFiles(project, Collections.singletonList(inputFile), outputFile, mainCallParameters, version); + translateFiles(project, Collections.singletonList(inputFile), outputFile, mainCallParameters, version, null); } public static void translateFiles(@NotNull Project project, @NotNull List inputFiles, - @NotNull String outputFile, @NotNull MainCallParameters mainCallParameters, @NotNull EcmaVersion version) throws Exception { + @NotNull String outputFile, + @NotNull MainCallParameters mainCallParameters, + @NotNull EcmaVersion version, + List rawStatements) throws Exception { List psiFiles = createPsiFileList(inputFiles, project); - JsProgram program = getTranslator(project, version).generateProgram(psiFiles, mainCallParameters); + JsProgram program = getTranslator(project, version).generateProgram(psiFiles, mainCallParameters, rawStatements); FileWriter writer = new FileWriter(new File(outputFile)); try { writer.write("\"use strict\";\n"); - writer.write(CodeGenerator.toString(program)); + writer.write(CodeGenerator.toString(program, null)); } finally { writer.close(); diff --git a/js/js.translator/qunit/deepEqual.js b/js/js.translator/qunit/deepEqual.js new file mode 100644 index 00000000000..f31d283db03 --- /dev/null +++ b/js/js.translator/qunit/deepEqual.js @@ -0,0 +1,1432 @@ +module("equiv"); + + +test("Primitive types and constants", function () { + equal(QUnit.equiv(null, null), true, "null"); + equal(QUnit.equiv(null, {}), false, "null"); + equal(QUnit.equiv(null, undefined), false, "null"); + equal(QUnit.equiv(null, 0), false, "null"); + equal(QUnit.equiv(null, false), false, "null"); + equal(QUnit.equiv(null, ''), false, "null"); + equal(QUnit.equiv(null, []), false, "null"); + + equal(QUnit.equiv(undefined, undefined), true, "undefined"); + equal(QUnit.equiv(undefined, null), false, "undefined"); + equal(QUnit.equiv(undefined, 0), false, "undefined"); + equal(QUnit.equiv(undefined, false), false, "undefined"); + equal(QUnit.equiv(undefined, {}), false, "undefined"); + equal(QUnit.equiv(undefined, []), false, "undefined"); + equal(QUnit.equiv(undefined, ""), false, "undefined"); + + // Nan usually doest not equal to Nan using the '==' operator. + // Only isNaN() is able to do it. + equal(QUnit.equiv(0/0, 0/0), true, "NaN"); // NaN VS NaN + equal(QUnit.equiv(1/0, 2/0), true, "Infinity"); // Infinity VS Infinity + equal(QUnit.equiv(-1/0, 2/0), false, "-Infinity, Infinity"); // -Infinity VS Infinity + equal(QUnit.equiv(-1/0, -2/0), true, "-Infinity, -Infinity"); // -Infinity VS -Infinity + equal(QUnit.equiv(0/0, 1/0), false, "NaN, Infinity"); // Nan VS Infinity + equal(QUnit.equiv(1/0, 0/0), false, "NaN, Infinity"); // Nan VS Infinity + equal(QUnit.equiv(0/0, null), false, "NaN"); + equal(QUnit.equiv(0/0, undefined), false, "NaN"); + equal(QUnit.equiv(0/0, 0), false, "NaN"); + equal(QUnit.equiv(0/0, false), false, "NaN"); + equal(QUnit.equiv(0/0, function () {}), false, "NaN"); + equal(QUnit.equiv(1/0, null), false, "NaN, Infinity"); + equal(QUnit.equiv(1/0, undefined), false, "NaN, Infinity"); + equal(QUnit.equiv(1/0, 0), false, "NaN, Infinity"); + equal(QUnit.equiv(1/0, 1), false, "NaN, Infinity"); + equal(QUnit.equiv(1/0, false), false, "NaN, Infinity"); + equal(QUnit.equiv(1/0, true), false, "NaN, Infinity"); + equal(QUnit.equiv(1/0, function () {}), false, "NaN, Infinity"); + + equal(QUnit.equiv(0, 0), true, "number"); + equal(QUnit.equiv(0, 1), false, "number"); + equal(QUnit.equiv(1, 0), false, "number"); + equal(QUnit.equiv(1, 1), true, "number"); + equal(QUnit.equiv(1.1, 1.1), true, "number"); + equal(QUnit.equiv(0.0000005, 0.0000005), true, "number"); + equal(QUnit.equiv(0, ''), false, "number"); + equal(QUnit.equiv(0, '0'), false, "number"); + equal(QUnit.equiv(1, '1'), false, "number"); + equal(QUnit.equiv(0, false), false, "number"); + equal(QUnit.equiv(1, true), false, "number"); + + equal(QUnit.equiv(true, true), true, "boolean"); + equal(QUnit.equiv(true, false), false, "boolean"); + equal(QUnit.equiv(false, true), false, "boolean"); + equal(QUnit.equiv(false, 0), false, "boolean"); + equal(QUnit.equiv(false, null), false, "boolean"); + equal(QUnit.equiv(false, undefined), false, "boolean"); + equal(QUnit.equiv(true, 1), false, "boolean"); + equal(QUnit.equiv(true, null), false, "boolean"); + equal(QUnit.equiv(true, undefined), false, "boolean"); + + equal(QUnit.equiv('', ''), true, "string"); + equal(QUnit.equiv('a', 'a'), true, "string"); + equal(QUnit.equiv("foobar", "foobar"), true, "string"); + equal(QUnit.equiv("foobar", "foo"), false, "string"); + equal(QUnit.equiv('', 0), false, "string"); + equal(QUnit.equiv('', false), false, "string"); + equal(QUnit.equiv('', null), false, "string"); + equal(QUnit.equiv('', undefined), false, "string"); + + // Short annotation VS new annotation + equal(QUnit.equiv(0, new Number()), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Number(), 0), true, "short annotation VS new annotation"); + equal(QUnit.equiv(1, new Number(1)), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Number(1), 1), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Number(0), 1), false, "short annotation VS new annotation"); + equal(QUnit.equiv(0, new Number(1)), false, "short annotation VS new annotation"); + + equal(QUnit.equiv(new String(), ""), true, "short annotation VS new annotation"); + equal(QUnit.equiv("", new String()), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new String("My String"), "My String"), true, "short annotation VS new annotation"); + equal(QUnit.equiv("My String", new String("My String")), true, "short annotation VS new annotation"); + equal(QUnit.equiv("Bad String", new String("My String")), false, "short annotation VS new annotation"); + equal(QUnit.equiv(new String("Bad String"), "My String"), false, "short annotation VS new annotation"); + + equal(QUnit.equiv(false, new Boolean()), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Boolean(), false), true, "short annotation VS new annotation"); + equal(QUnit.equiv(true, new Boolean(true)), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Boolean(true), true), true, "short annotation VS new annotation"); + equal(QUnit.equiv(true, new Boolean(1)), true, "short annotation VS new annotation"); + equal(QUnit.equiv(false, new Boolean(false)), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Boolean(false), false), true, "short annotation VS new annotation"); + equal(QUnit.equiv(false, new Boolean(0)), true, "short annotation VS new annotation"); + equal(QUnit.equiv(true, new Boolean(false)), false, "short annotation VS new annotation"); + equal(QUnit.equiv(new Boolean(false), true), false, "short annotation VS new annotation"); + + equal(QUnit.equiv(new Object(), {}), true, "short annotation VS new annotation"); + equal(QUnit.equiv({}, new Object()), true, "short annotation VS new annotation"); + equal(QUnit.equiv(new Object(), {a:1}), false, "short annotation VS new annotation"); + equal(QUnit.equiv({a:1}, new Object()), false, "short annotation VS new annotation"); + equal(QUnit.equiv({a:undefined}, new Object()), false, "short annotation VS new annotation"); + equal(QUnit.equiv(new Object(), {a:undefined}), false, "short annotation VS new annotation"); +}); + +test("Objects Basics.", function() { + equal(QUnit.equiv({}, {}), true); + equal(QUnit.equiv({}, null), false); + equal(QUnit.equiv({}, undefined), false); + equal(QUnit.equiv({}, 0), false); + equal(QUnit.equiv({}, false), false); + + // This test is a hard one, it is very important + // REASONS: + // 1) They are of the same type "object" + // 2) [] instanceof Object is true + // 3) Their properties are the same (doesn't exists) + equal(QUnit.equiv({}, []), false); + + equal(QUnit.equiv({a:1}, {a:1}), true); + equal(QUnit.equiv({a:1}, {a:"1"}), false); + equal(QUnit.equiv({a:[]}, {a:[]}), true); + equal(QUnit.equiv({a:{}}, {a:null}), false); + equal(QUnit.equiv({a:1}, {}), false); + equal(QUnit.equiv({}, {a:1}), false); + + // Hard ones + equal(QUnit.equiv({a:undefined}, {}), false); + equal(QUnit.equiv({}, {a:undefined}), false); + equal(QUnit.equiv( + { + a: [{ bar: undefined }] + }, + { + a: [{ bat: undefined }] + } + ), false); + + // Objects with no prototype, created via Object.create(null), are used e.g. as dictionaries. + // Being able to test equivalence against object literals is quite useful. + if (typeof Object.create === 'function') { + equal(QUnit.equiv(Object.create(null), {}), true, "empty object without prototype VS empty object"); + + var nonEmptyWithNoProto = Object.create(null); + nonEmptyWithNoProto.foo = "bar"; + + equal(QUnit.equiv(nonEmptyWithNoProto, { foo: "bar" }), true, "object without prototype VS object"); + } +}); + + +test("Arrays Basics.", function() { + + equal(QUnit.equiv([], []), true); + + // May be a hard one, can invoke a crash at execution. + // because their types are both "object" but null isn't + // like a true object, it doesn't have any property at all. + equal(QUnit.equiv([], null), false); + + equal(QUnit.equiv([], undefined), false); + equal(QUnit.equiv([], false), false); + equal(QUnit.equiv([], 0), false); + equal(QUnit.equiv([], ""), false); + + // May be a hard one, but less hard + // than {} with [] (note the order) + equal(QUnit.equiv([], {}), false); + + equal(QUnit.equiv([null],[]), false); + equal(QUnit.equiv([undefined],[]), false); + equal(QUnit.equiv([],[null]), false); + equal(QUnit.equiv([],[undefined]), false); + equal(QUnit.equiv([null],[undefined]), false); + equal(QUnit.equiv([[]],[[]]), true); + equal(QUnit.equiv([[],[],[]],[[],[],[]]), true); + equal(QUnit.equiv( + [[],[],[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + [[],[],[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]), + true); + equal(QUnit.equiv( + [[],[],[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + [[],[],[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]), // shorter + false); + equal(QUnit.equiv( + [[],[],[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[{}]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + [[],[],[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]), // deepest element not an array + false); + + // same multidimensional + equal(QUnit.equiv( + [1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,[ + [6,7,8,9, [ + [ + 1,2,3,4,[ + 2,3,4,[ + 1,2,[ + 1,2,3,4,[ + 1,2,3,4,5,6,7,8,9,[ + 0 + ],1,2,3,4,5,6,7,8,9 + ],5,6,7,8,9 + ],4,5,6,7,8,9 + ],5,6,7,8,9 + ],5,6,7 + ] + ] + ] + ] + ]]], + [1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,[ + [6,7,8,9, [ + [ + 1,2,3,4,[ + 2,3,4,[ + 1,2,[ + 1,2,3,4,[ + 1,2,3,4,5,6,7,8,9,[ + 0 + ],1,2,3,4,5,6,7,8,9 + ],5,6,7,8,9 + ],4,5,6,7,8,9 + ],5,6,7,8,9 + ],5,6,7 + ] + ] + ] + ] + ]]]), + true, "Multidimensional"); + + // different multidimensional + equal(QUnit.equiv( + [1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,[ + [6,7,8,9, [ + [ + 1,2,3,4,[ + 2,3,4,[ + 1,2,[ + 1,2,3,4,[ + 1,2,3,4,5,6,7,8,9,[ + 0 + ],1,2,3,4,5,6,7,8,9 + ],5,6,7,8,9 + ],4,5,6,7,8,9 + ],5,6,7,8,9 + ],5,6,7 + ] + ] + ] + ] + ]]], + [1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,[ + [6,7,8,9, [ + [ + 1,2,3,4,[ + 2,3,4,[ + 1,2,[ + '1',2,3,4,[ // string instead of number + 1,2,3,4,5,6,7,8,9,[ + 0 + ],1,2,3,4,5,6,7,8,9 + ],5,6,7,8,9 + ],4,5,6,7,8,9 + ],5,6,7,8,9 + ],5,6,7 + ] + ] + ] + ] + ]]]), + false, "Multidimensional"); + + // different multidimensional + equal(QUnit.equiv( + [1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,[ + [6,7,8,9, [ + [ + 1,2,3,4,[ + 2,3,4,[ + 1,2,[ + 1,2,3,4,[ + 1,2,3,4,5,6,7,8,9,[ + 0 + ],1,2,3,4,5,6,7,8,9 + ],5,6,7,8,9 + ],4,5,6,7,8,9 + ],5,6,7,8,9 + ],5,6,7 + ] + ] + ] + ] + ]]], + [1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,6,7,8,9, [ + 1,2,3,4,5,[ + [6,7,8,9, [ + [ + 1,2,3,4,[ + 2,3,[ // missing an element (4) + 1,2,[ + 1,2,3,4,[ + 1,2,3,4,5,6,7,8,9,[ + 0 + ],1,2,3,4,5,6,7,8,9 + ],5,6,7,8,9 + ],4,5,6,7,8,9 + ],5,6,7,8,9 + ],5,6,7 + ] + ] + ] + ] + ]]]), + false, "Multidimensional"); +}); + +test("Functions.", function() { + var f0 = function () {}; + var f1 = function () {}; + + // f2 and f3 have the same code, formatted differently + var f2 = function () {var i = 0;}; + var f3 = function () { + var i = 0 // this comment and no semicoma as difference + }; + + equal(QUnit.equiv(function() {}, function() {}), false, "Anonymous functions"); // exact source code + equal(QUnit.equiv(function() {}, function() {return true;}), false, "Anonymous functions"); + + equal(QUnit.equiv(f0, f0), true, "Function references"); // same references + equal(QUnit.equiv(f0, f1), false, "Function references"); // exact source code, different references + equal(QUnit.equiv(f2, f3), false, "Function references"); // equivalent source code, different references + equal(QUnit.equiv(f1, f2), false, "Function references"); // different source code, different references + equal(QUnit.equiv(function() {}, true), false); + equal(QUnit.equiv(function() {}, undefined), false); + equal(QUnit.equiv(function() {}, null), false); + equal(QUnit.equiv(function() {}, {}), false); +}); + + +test("Date instances.", function() { + // Date, we don't need to test Date.parse() because it returns a number. + // Only test the Date instances by setting them a fix date. + // The date use is midnight January 1, 1970 + + var d1 = new Date(); + d1.setTime(0); // fix the date + + var d2 = new Date(); + d2.setTime(0); // fix the date + + var d3 = new Date(); // The very now + + // Anyway their types differs, just in case the code fails in the order in which it deals with date + equal(QUnit.equiv(d1, 0), false); // d1.valueOf() returns 0, but d1 and 0 are different + // test same values date and different instances equality + equal(QUnit.equiv(d1, d2), true); + // test different date and different instances difference + equal(QUnit.equiv(d1, d3), false); +}); + + +test("RegExp.", function() { + // Must test cases that imply those traps: + // var a = /./; + // a instanceof Object; // Oops + // a instanceof RegExp; // Oops + // typeof a === "function"; // Oops, false in IE and Opera, true in FF and Safari ("object") + + // Tests same regex with same modifiers in different order + var r = /foo/; + var r5 = /foo/gim; + var r6 = /foo/gmi; + var r7 = /foo/igm; + var r8 = /foo/img; + var r9 = /foo/mig; + var r10 = /foo/mgi; + var ri1 = /foo/i; + var ri2 = /foo/i; + var rm1 = /foo/m; + var rm2 = /foo/m; + var rg1 = /foo/g; + var rg2 = /foo/g; + + equal(QUnit.equiv(r5, r6), true, "Modifier order"); + equal(QUnit.equiv(r5, r7), true, "Modifier order"); + equal(QUnit.equiv(r5, r8), true, "Modifier order"); + equal(QUnit.equiv(r5, r9), true, "Modifier order"); + equal(QUnit.equiv(r5, r10), true, "Modifier order"); + equal(QUnit.equiv(r, r5), false, "Modifier"); + + equal(QUnit.equiv(ri1, ri2), true, "Modifier"); + equal(QUnit.equiv(r, ri1), false, "Modifier"); + equal(QUnit.equiv(ri1, rm1), false, "Modifier"); + equal(QUnit.equiv(r, rm1), false, "Modifier"); + equal(QUnit.equiv(rm1, ri1), false, "Modifier"); + equal(QUnit.equiv(rm1, rm2), true, "Modifier"); + equal(QUnit.equiv(rg1, rm1), false, "Modifier"); + equal(QUnit.equiv(rm1, rg1), false, "Modifier"); + equal(QUnit.equiv(rg1, rg2), true, "Modifier"); + + // Different regex, same modifiers + var r11 = /[a-z]/gi; + var r13 = /[0-9]/gi; // oops! different + equal(QUnit.equiv(r11, r13), false, "Regex pattern"); + + var r14 = /0/ig; + var r15 = /"0"/ig; // oops! different + equal(QUnit.equiv(r14, r15), false, "Regex pattern"); + + var r1 = /[\n\r\u2028\u2029]/g; + var r2 = /[\n\r\u2028\u2029]/g; + var r3 = /[\n\r\u2028\u2028]/g; // differs from r1 + var r4 = /[\n\r\u2028\u2029]/; // differs from r1 + + equal(QUnit.equiv(r1, r2), true, "Regex pattern"); + equal(QUnit.equiv(r1, r3), false, "Regex pattern"); + equal(QUnit.equiv(r1, r4), false, "Regex pattern"); + + // More complex regex + var regex1 = "^[-_.a-z0-9]+@([-_a-z0-9]+\\.)+([A-Za-z][A-Za-z]|[A-Za-z][A-Za-z][A-Za-z])|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$"; + var regex2 = "^[-_.a-z0-9]+@([-_a-z0-9]+\\.)+([A-Za-z][A-Za-z]|[A-Za-z][A-Za-z][A-Za-z])|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$"; + // regex 3 is different: '.' not escaped + var regex3 = "^[-_.a-z0-9]+@([-_a-z0-9]+.)+([A-Za-z][A-Za-z]|[A-Za-z][A-Za-z][A-Za-z])|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$"; + + var r21 = new RegExp(regex1); + var r22 = new RegExp(regex2); + var r23 = new RegExp(regex3); // diff from r21, not same pattern + var r23a = new RegExp(regex3, "gi"); // diff from r23, not same modifier + var r24a = new RegExp(regex3, "ig"); // same as r23a + + equal(QUnit.equiv(r21, r22), true, "Complex Regex"); + equal(QUnit.equiv(r21, r23), false, "Complex Regex"); + equal(QUnit.equiv(r23, r23a), false, "Complex Regex"); + equal(QUnit.equiv(r23a, r24a), true, "Complex Regex"); + + // typeof r1 is "function" in some browsers and "object" in others so we must cover this test + var re = / /; + equal(QUnit.equiv(re, function () {}), false, "Regex internal"); + equal(QUnit.equiv(re, {}), false, "Regex internal"); +}); + + +test("Complex Objects.", function() { + + function fn1() { + return "fn1"; + } + function fn2() { + return "fn2"; + } + + // Try to invert the order of some properties to make sure it is covered. + // It can failed when properties are compared between unsorted arrays. + equal(QUnit.equiv( + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + s: [1,2,3], + t: undefined, + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + q: [], + p: 1/0, + o: 99 + }, + l: undefined, + m: null + } + }, + d: 0, + i: true, + h: "false" + } + }, + e: undefined, + g: "", + h: "h", + f: {}, + i: [] + }, + { + a: 1, + b: null, + c: [{}], + d: { + b: false, + a: 3.14159, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + t: undefined, + u: 0, + s: [1,2,3], + v: { + w: { + x: { + z: null, + y: "Yahoo!" + } + } + } + }, + o: 99, + p: 1/0, + q: [] + }, + l: undefined, + m: null + } + }, + i: true, + h: "false" + } + }, + e: undefined, + g: "", + f: {}, + h: "h", + i: [] + } + ), true); + + equal(QUnit.equiv( + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + //r: "r", // different: missing a property + s: [1,2,3], + t: undefined, + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + o: 99, + p: 1/0, + q: [] + }, + l: undefined, + m: null + } + }, + h: "false", + i: true + } + }, + e: undefined, + f: {}, + g: "", + h: "h", + i: [] + }, + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + s: [1,2,3], + t: undefined, + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + o: 99, + p: 1/0, + q: [] + }, + l: undefined, + m: null + } + }, + h: "false", + i: true + } + }, + e: undefined, + f: {}, + g: "", + h: "h", + i: [] + } + ), false); + + equal(QUnit.equiv( + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + s: [1,2,3], + t: undefined, + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + o: 99, + p: 1/0, + q: [] + }, + l: undefined, + m: null + } + }, + h: "false", + i: true + } + }, + e: undefined, + f: {}, + g: "", + h: "h", + i: [] + }, + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + s: [1,2,3], + //t: undefined, // different: missing a property with an undefined value + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + o: 99, + p: 1/0, + q: [] + }, + l: undefined, + m: null + } + }, + h: "false", + i: true + } + }, + e: undefined, + f: {}, + g: "", + h: "h", + i: [] + } + ), false); + + equal(QUnit.equiv( + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + s: [1,2,3], + t: undefined, + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + o: 99, + p: 1/0, + q: [] + }, + l: undefined, + m: null + } + }, + h: "false", + i: true + } + }, + e: undefined, + f: {}, + g: "", + h: "h", + i: [] + }, + { + a: 1, + b: null, + c: [{}], + d: { + a: 3.14159, + b: false, + c: { + d: 0, + e: fn1, + f: [[[]]], + g: { + j: { + k: { + n: { + r: "r", + s: [1,2,3], + t: undefined, + u: 0, + v: { + w: { + x: { + y: "Yahoo!", + z: null + } + } + } + }, + o: 99, + p: 1/0, + q: {} // different was [] + }, + l: undefined, + m: null + } + }, + h: "false", + i: true + } + }, + e: undefined, + f: {}, + g: "", + h: "h", + i: [] + } + ), false); + + var same1 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,null,{}, [], [1,2,3]], + bar: undefined + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ ας" + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + var same2 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,null,{}, [], [1,2,3]], + bar: undefined + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ ας" + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + var diff1 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,null,{}, [], [1,2,3,4]], // different: 4 was add to the array + bar: undefined + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ ας" + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + var diff2 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,null,{}, [], [1,2,3]], + newprop: undefined, // different: newprop was added + bar: undefined + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ ας" + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + var diff3 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,null,{}, [], [1,2,3]], + bar: undefined + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ α" // different: missing last char + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + var diff4 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,undefined,{}, [], [1,2,3]], // different: undefined instead of null + bar: undefined + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ ας" + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + var diff5 = { + a: [ + "string", null, 0, "1", 1, { + prop: null, + foo: [1,2,null,{}, [], [1,2,3]], + bat: undefined // different: property name not "bar" + }, 3, "Hey!", "Κάνε πάντα γνω�ίζουμε ας των, μηχανής επιδιό�θωσης επιδιο�θώσεις ώς μια. Κλπ ας" + ], + unicode: "� 汉语中存在 港澳和海外的�人圈中 贵州 我去了书店 现在尚有争", + b: "b", + c: fn1 + }; + + equal(QUnit.equiv(same1, same2), true); + equal(QUnit.equiv(same2, same1), true); + equal(QUnit.equiv(same2, diff1), false); + equal(QUnit.equiv(diff1, same2), false); + + equal(QUnit.equiv(same1, diff1), false); + equal(QUnit.equiv(same1, diff2), false); + equal(QUnit.equiv(same1, diff3), false); + equal(QUnit.equiv(same1, diff3), false); + equal(QUnit.equiv(same1, diff4), false); + equal(QUnit.equiv(same1, diff5), false); + equal(QUnit.equiv(diff5, diff1), false); +}); + + +test("Complex Arrays.", function() { + + function fn() { + } + + equal(QUnit.equiv( + [1, 2, 3, true, {}, null, [ + { + a: ["", '1', 0] + }, + 5, 6, 7 + ], "foo"], + [1, 2, 3, true, {}, null, [ + { + a: ["", '1', 0] + }, + 5, 6, 7 + ], "foo"]), + true); + + equal(QUnit.equiv( + [1, 2, 3, true, {}, null, [ + { + a: ["", '1', 0] + }, + 5, 6, 7 + ], "foo"], + [1, 2, 3, true, {}, null, [ + { + b: ["", '1', 0] // not same property name + }, + 5, 6, 7 + ], "foo"]), + false); + + var a = [{ + b: fn, + c: false, + "do": "reserved word", + "for": { + ar: [3,5,9,"hey!", [], { + ar: [1,[ + 3,4,6,9, null, [], [] + ]], + e: fn, + f: undefined + }] + }, + e: 0.43445 + }, 5, "string", 0, fn, false, null, undefined, 0, [ + 4,5,6,7,8,9,11,22,33,44,55,"66", null, [], [[[[[3]]]], "3"], {}, 1/0 + ], [], [[[], "foo", null, { + n: 1/0, + z: { + a: [3,4,5,6,"yep!", undefined, undefined], + b: {} + } + }, {}]]]; + + equal(QUnit.equiv(a, + [{ + b: fn, + c: false, + "do": "reserved word", + "for": { + ar: [3,5,9,"hey!", [], { + ar: [1,[ + 3,4,6,9, null, [], [] + ]], + e: fn, + f: undefined + }] + }, + e: 0.43445 + }, 5, "string", 0, fn, false, null, undefined, 0, [ + 4,5,6,7,8,9,11,22,33,44,55,"66", null, [], [[[[[3]]]], "3"], {}, 1/0 + ], [], [[[], "foo", null, { + n: 1/0, + z: { + a: [3,4,5,6,"yep!", undefined, undefined], + b: {} + } + }, {}]]]), true); + + equal(QUnit.equiv(a, + [{ + b: fn, + c: false, + "do": "reserved word", + "for": { + ar: [3,5,9,"hey!", [], { + ar: [1,[ + 3,4,6,9, null, [], [] + ]], + e: fn, + f: undefined + }] + }, + e: 0.43445 + }, 5, "string", 0, fn, false, null, undefined, 0, [ + 4,5,6,7,8,9,11,22,33,44,55,"66", null, [], [[[[[2]]]], "3"], {}, 1/0 // different: [[[[[2]]]]] instead of [[[[[3]]]]] + ], [], [[[], "foo", null, { + n: 1/0, + z: { + a: [3,4,5,6,"yep!", undefined, undefined], + b: {} + } + }, {}]]]), false); + + equal(QUnit.equiv(a, + [{ + b: fn, + c: false, + "do": "reserved word", + "for": { + ar: [3,5,9,"hey!", [], { + ar: [1,[ + 3,4,6,9, null, [], [] + ]], + e: fn, + f: undefined + }] + }, + e: 0.43445 + }, 5, "string", 0, fn, false, null, undefined, 0, [ + 4,5,6,7,8,9,11,22,33,44,55,"66", null, [], [[[[[3]]]], "3"], {}, 1/0 + ], [], [[[], "foo", null, { + n: -1/0, // different, -Infinity instead of Infinity + z: { + a: [3,4,5,6,"yep!", undefined, undefined], + b: {} + } + }, {}]]]), false); + + equal(QUnit.equiv(a, + [{ + b: fn, + c: false, + "do": "reserved word", + "for": { + ar: [3,5,9,"hey!", [], { + ar: [1,[ + 3,4,6,9, null, [], [] + ]], + e: fn, + f: undefined + }] + }, + e: 0.43445 + }, 5, "string", 0, fn, false, null, undefined, 0, [ + 4,5,6,7,8,9,11,22,33,44,55,"66", null, [], [[[[[3]]]], "3"], {}, 1/0 + ], [], [[[], "foo", { // different: null is missing + n: 1/0, + z: { + a: [3,4,5,6,"yep!", undefined, undefined], + b: {} + } + }, {}]]]), false); + + equal(QUnit.equiv(a, + [{ + b: fn, + c: false, + "do": "reserved word", + "for": { + ar: [3,5,9,"hey!", [], { + ar: [1,[ + 3,4,6,9, null, [], [] + ]], + e: fn + // different: missing property f: undefined + }] + }, + e: 0.43445 + }, 5, "string", 0, fn, false, null, undefined, 0, [ + 4,5,6,7,8,9,11,22,33,44,55,"66", null, [], [[[[[3]]]], "3"], {}, 1/0 + ], [], [[[], "foo", null, { + n: 1/0, + z: { + a: [3,4,5,6,"yep!", undefined, undefined], + b: {} + } + }, {}]]]), false); +}); + + +test("Prototypal inheritance", function() { + function Gizmo(id) { + this.id = id; + } + + function Hoozit(id) { + this.id = id; + } + Hoozit.prototype = new Gizmo(); + + var gizmo = new Gizmo("ok"); + var hoozit = new Hoozit("ok"); + + // Try this test many times after test on instances that hold function + // to make sure that our code does not mess with last object constructor memoization. + equal(QUnit.equiv(function () {}, function () {}), false); + + // Hoozit inherit from Gizmo + // hoozit instanceof Hoozit; // true + // hoozit instanceof Gizmo; // true + equal(QUnit.equiv(hoozit, gizmo), true); + + Gizmo.prototype.bar = true; // not a function just in case we skip them + + // Hoozit inherit from Gizmo + // They are equivalent + equal(QUnit.equiv(hoozit, gizmo), true); + + // Make sure this is still true !important + // The reason for this is that I forgot to reset the last + // caller to where it were called from. + equal(QUnit.equiv(function () {}, function () {}), false); + + // Make sure this is still true !important + equal(QUnit.equiv(hoozit, gizmo), true); + + Hoozit.prototype.foo = true; // not a function just in case we skip them + + // Gizmo does not inherit from Hoozit + // gizmo instanceof Gizmo; // true + // gizmo instanceof Hoozit; // false + // They are not equivalent + equal(QUnit.equiv(hoozit, gizmo), false); + + // Make sure this is still true !important + equal(QUnit.equiv(function () {}, function () {}), false); +}); + + +test("Instances", function() { + function A() {} + var a1 = new A(); + var a2 = new A(); + + function B() { + this.fn = function () {}; + } + var b1 = new B(); + var b2 = new B(); + + equal(QUnit.equiv(a1, a2), true, "Same property, same constructor"); + + // b1.fn and b2.fn are functions but they are different references + // But we decided to skip function for instances. + equal(QUnit.equiv(b1, b2), true, "Same property, same constructor"); + equal(QUnit.equiv(a1, b1), false, "Same properties but different constructor"); // failed + + function Car(year) { + var privateVar = 0; + this.year = year; + this.isOld = function() { + return year > 10; + }; + } + + function Human(year) { + var privateVar = 1; + this.year = year; + this.isOld = function() { + return year > 80; + }; + } + + var car = new Car(30); + var carSame = new Car(30); + var carDiff = new Car(10); + var human = new Human(30); + + var diff = { + year: 30 + }; + + var same = { + year: 30, + isOld: function () {} + }; + + equal(QUnit.equiv(car, car), true); + equal(QUnit.equiv(car, carDiff), false); + equal(QUnit.equiv(car, carSame), true); + equal(QUnit.equiv(car, human), false); +}); + + +test("Complex Instances Nesting (with function value in literals and/or in nested instances)", function() { + function A(fn) { + this.a = {}; + this.fn = fn; + this.b = {a: []}; + this.o = {}; + this.fn1 = fn; + } + function B(fn) { + this.fn = fn; + this.fn1 = function () {}; + this.a = new A(function () {}); + } + + function fnOutside() { + } + + function C(fn) { + function fnInside() { + } + this.x = 10; + this.fn = fn; + this.fn1 = function () {}; + this.fn2 = fnInside; + this.fn3 = { + a: true, + b: fnOutside // ok make reference to a function in all instances scope + }; + this.o1 = {}; + + // This function will be ignored. + // Even if it is not visible for all instances (e.g. locked in a closures), + // it is from a property that makes part of an instance (e.g. from the C constructor) + this.b1 = new B(function () {}); + this.b2 = new B({ + x: { + b2: new B(function() {}) + } + }); + } + + function D(fn) { + function fnInside() { + } + this.x = 10; + this.fn = fn; + this.fn1 = function () {}; + this.fn2 = fnInside; + this.fn3 = { + a: true, + b: fnOutside, // ok make reference to a function in all instances scope + + // This function won't be ingored. + // It isn't visible for all C insances + // and it is not in a property of an instance. (in an Object instances e.g. the object literal) + c: fnInside + }; + this.o1 = {}; + + // This function will be ignored. + // Even if it is not visible for all instances (e.g. locked in a closures), + // it is from a property that makes part of an instance (e.g. from the C constructor) + this.b1 = new B(function () {}); + this.b2 = new B({ + x: { + b2: new B(function() {}) + } + }); + } + + function E(fn) { + function fnInside() { + } + this.x = 10; + this.fn = fn; + this.fn1 = function () {}; + this.fn2 = fnInside; + this.fn3 = { + a: true, + b: fnOutside // ok make reference to a function in all instances scope + }; + this.o1 = {}; + + // This function will be ignored. + // Even if it is not visible for all instances (e.g. locked in a closures), + // it is from a property that makes part of an instance (e.g. from the C constructor) + this.b1 = new B(function () {}); + this.b2 = new B({ + x: { + b1: new B({a: function() {}}), + b2: new B(function() {}) + } + }); + } + + + var a1 = new A(function () {}); + var a2 = new A(function () {}); + equal(QUnit.equiv(a1, a2), true); + + equal(QUnit.equiv(a1, a2), true); // different instances + + var b1 = new B(function () {}); + var b2 = new B(function () {}); + equal(QUnit.equiv(b1, b2), true); + + var c1 = new C(function () {}); + var c2 = new C(function () {}); + equal(QUnit.equiv(c1, c2), true); + + var d1 = new D(function () {}); + var d2 = new D(function () {}); + equal(QUnit.equiv(d1, d2), false); + + var e1 = new E(function () {}); + var e2 = new E(function () {}); + equal(QUnit.equiv(e1, e2), false); + +}); + + +test('object with references to self wont loop', function(){ + var circularA = { + abc:null + }, circularB = { + abc:null + }; + circularA.abc = circularA; + circularB.abc = circularB; + equal(QUnit.equiv(circularA, circularB), true, "Should not repeat test on object (ambigous test)"); + + circularA.def = 1; + circularB.def = 1; + equal(QUnit.equiv(circularA, circularB), true, "Should not repeat test on object (ambigous test)"); + + circularA.def = 1; + circularB.def = 0; + equal(QUnit.equiv(circularA, circularB), false, "Should not repeat test on object (unambigous test)"); +}); + +test('array with references to self wont loop', function(){ + var circularA = [], + circularB = []; + circularA.push(circularA); + circularB.push(circularB); + equal(QUnit.equiv(circularA, circularB), true, "Should not repeat test on array (ambigous test)"); + + circularA.push( 'abc' ); + circularB.push( 'abc' ); + equal(QUnit.equiv(circularA, circularB), true, "Should not repeat test on array (ambigous test)"); + + circularA.push( 'hello' ); + circularB.push( 'goodbye' ); + equal(QUnit.equiv(circularA, circularB), false, "Should not repeat test on array (unambigous test)"); +}); + +test('mixed object/array with references to self wont loop', function(){ + var circularA = [{abc:null}], + circularB = [{abc:null}]; + circularA[0].abc = circularA; + circularB[0].abc = circularB; + + circularA.push(circularA); + circularB.push(circularB); + equal(QUnit.equiv(circularA, circularB), true, "Should not repeat test on object/array (ambigous test)"); + + circularA[0].def = 1; + circularB[0].def = 1; + equal(QUnit.equiv(circularA, circularB), true, "Should not repeat test on object/array (ambigous test)"); + + circularA[0].def = 1; + circularB[0].def = 0; + equal(QUnit.equiv(circularA, circularB), false, "Should not repeat test on object/array (unambigous test)"); +}); + +test("Test that must be done at the end because they extend some primitive's prototype", function() { + // Try that a function looks like our regular expression. + // This tests if we check that a and b are really both instance of RegExp + Function.prototype.global = true; + Function.prototype.multiline = true; + Function.prototype.ignoreCase = false; + Function.prototype.source = "my regex"; + var re = /my regex/gm; + equal(QUnit.equiv(re, function () {}), false, "A function that looks that a regex isn't a regex"); + // This test will ensures it works in both ways, and ALSO especially that we can make differences + // between RegExp and Function constructor because typeof on a RegExpt instance is "function" + equal(QUnit.equiv(function () {}, re), false, "Same conversely, but ensures that function and regexp are distinct because their constructor are different"); +}); diff --git a/js/js.translator/qunit/headless.html b/js/js.translator/qunit/headless.html new file mode 100644 index 00000000000..e2f3f7fe39d --- /dev/null +++ b/js/js.translator/qunit/headless.html @@ -0,0 +1,24 @@ + + + + QUnit Test Suite + + + + + + + +
test markup
+ + diff --git a/js/js.translator/qunit/index.html b/js/js.translator/qunit/index.html new file mode 100644 index 00000000000..ee18ba2db3a --- /dev/null +++ b/js/js.translator/qunit/index.html @@ -0,0 +1,19 @@ + + + + + Kotlin QUnit Test Suite + + + + + + + + + + +
+
test markup
+ + diff --git a/js/js.translator/qunit/logs.html b/js/js.translator/qunit/logs.html new file mode 100644 index 00000000000..515d4c9fdb3 --- /dev/null +++ b/js/js.translator/qunit/logs.html @@ -0,0 +1,13 @@ + + + + QUnit Test Suite + + + + + +
+
test markup
+ + diff --git a/js/js.translator/qunit/logs.js b/js/js.translator/qunit/logs.js new file mode 100644 index 00000000000..1efd05851fb --- /dev/null +++ b/js/js.translator/qunit/logs.js @@ -0,0 +1,180 @@ +// TODO disable reordering for this suite! + + +var begin = 0, + moduleStart = 0, + moduleDone = 0, + testStart = 0, + testDone = 0, + log = 0, + moduleContext, + moduleDoneContext, + testContext, + testDoneContext, + logContext; + +QUnit.begin(function() { + begin++; +}); +QUnit.done(function() { +}); +QUnit.moduleStart(function(context) { + moduleStart++; + moduleContext = context; +}); +QUnit.moduleDone(function(context) { + moduleDone++; + moduleDoneContext = context; +}); +QUnit.testStart(function(context) { + testStart++; + testContext = context; +}); +QUnit.testDone(function(context) { + testDone++; + testDoneContext = context; +}); +QUnit.log(function(context) { + log++; + logContext = context; +}); + +var logs = ["begin", "testStart", "testDone", "log", "moduleStart", "moduleDone", "done"]; +for (var i = 0; i < logs.length; i++) { + (function() { + var log = logs[i]; + QUnit[log](function() { + console.log(log, arguments); + }); + })(); +} + +module("logs1"); + +test("test1", 13, function() { + equal(begin, 1); + equal(moduleStart, 1); + equal(testStart, 1); + equal(testDone, 0); + equal(moduleDone, 0); + + deepEqual(logContext, { + result: true, + message: undefined, + actual: 0, + expected: 0 + }); + equal("foo", "foo", "msg"); + deepEqual(logContext, { + result: true, + message: "msg", + actual: "foo", + expected: "foo" + }); + strictEqual(testDoneContext, undefined); + deepEqual(testContext, { + module: "logs1", + name: "test1" + }); + strictEqual(moduleDoneContext, undefined); + deepEqual(moduleContext, { + name: "logs1" + }); + + equal(log, 12); +}); +test("test2", 10, function() { + equal(begin, 1); + equal(moduleStart, 1); + equal(testStart, 2); + equal(testDone, 1); + equal(moduleDone, 0); + + deepEqual(testDoneContext, { + module: "logs1", + name: "test1", + failed: 0, + passed: 13, + total: 13 + }); + deepEqual(testContext, { + module: "logs1", + name: "test2" + }); + strictEqual(moduleDoneContext, undefined); + deepEqual(moduleContext, { + name: "logs1" + }); + + equal(log, 22); +}); + +module("logs2"); + +test("test1", 9, function() { + equal(begin, 1); + equal(moduleStart, 2); + equal(testStart, 3); + equal(testDone, 2); + equal(moduleDone, 1); + + deepEqual(testContext, { + module: "logs2", + name: "test1" + }); + deepEqual(moduleDoneContext, { + name: "logs1", + failed: 0, + passed: 23, + total: 23 + }); + deepEqual(moduleContext, { + name: "logs2" + }); + + equal(log, 31); +}); +test("test2", 8, function() { + equal(begin, 1); + equal(moduleStart, 2); + equal(testStart, 4); + equal(testDone, 3); + equal(moduleDone, 1); + + deepEqual(testContext, { + module: "logs2", + name: "test2" + }); + deepEqual(moduleContext, { + name: "logs2" + }); + + equal(log, 39); +}); + +var testAutorun = true; + +QUnit.done(function() { + + if (!testAutorun) { + return; + } + + testAutorun = false; + + module("autorun"); + + test("reset", 0, function() {}); + + moduleStart = moduleDone = 0; + + test("first", function(){ + equal(moduleStart, 1, "test started"); + equal(moduleDone, 0, "test in progress"); + }); + + test("second", function(){ + equal(moduleStart, 2, "test started"); + equal(moduleDone, 1, "test in progress"); + }); +}); diff --git a/js/js.translator/qunit/qunit.css b/js/js.translator/qunit/qunit.css new file mode 100644 index 00000000000..a1dd6a809fc --- /dev/null +++ b/js/js.translator/qunit/qunit.css @@ -0,0 +1,236 @@ +/** + * QUnit v1.7.0pre - A JavaScript Unit Testing Framework + * + * http://docs.jquery.com/QUnit + * + * Copyright (c) 2012 John Resig, Jörn Zaefferer + * Dual licensed under the MIT (MIT-LICENSE.txt) + * or GPL (GPL-LICENSE.txt) licenses. + */ + +/** Font Family and Sizes */ + +#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { + font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; +} + +#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } +#qunit-tests { font-size: smaller; } + + +/** Resets */ + +#qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult { + margin: 0; + padding: 0; +} + + +/** Header */ + +#qunit-header { + padding: 0.5em 0 0.5em 1em; + + color: #8699a4; + background-color: #0d3349; + + font-size: 1.5em; + line-height: 1em; + font-weight: normal; + + border-radius: 15px 15px 0 0; + -moz-border-radius: 15px 15px 0 0; + -webkit-border-top-right-radius: 15px; + -webkit-border-top-left-radius: 15px; +} + +#qunit-header a { + text-decoration: none; + color: #c2ccd1; +} + +#qunit-header a:hover, +#qunit-header a:focus { + color: #fff; +} + +#qunit-header label { + display: inline-block; + padding-left: 0.5em; +} + +#qunit-banner { + height: 5px; +} + +#qunit-testrunner-toolbar { + padding: 0.5em 0 0.5em 2em; + color: #5E740B; + background-color: #eee; +} + +#qunit-userAgent { + padding: 0.5em 0 0.5em 2.5em; + background-color: #2b81af; + color: #fff; + text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; +} + + +/** Tests: Pass/Fail */ + +#qunit-tests { + list-style-position: inside; +} + +#qunit-tests li { + padding: 0.4em 0.5em 0.4em 2.5em; + border-bottom: 1px solid #fff; + list-style-position: inside; +} + +#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { + display: none; +} + +#qunit-tests li strong { + cursor: pointer; +} + +#qunit-tests li a { + padding: 0.5em; + color: #c2ccd1; + text-decoration: none; +} +#qunit-tests li a:hover, +#qunit-tests li a:focus { + color: #000; +} + +#qunit-tests ol { + margin-top: 0.5em; + padding: 0.5em; + + background-color: #fff; + + border-radius: 15px; + -moz-border-radius: 15px; + -webkit-border-radius: 15px; + + box-shadow: inset 0px 2px 13px #999; + -moz-box-shadow: inset 0px 2px 13px #999; + -webkit-box-shadow: inset 0px 2px 13px #999; +} + +#qunit-tests table { + border-collapse: collapse; + margin-top: .2em; +} + +#qunit-tests th { + text-align: right; + vertical-align: top; + padding: 0 .5em 0 0; +} + +#qunit-tests td { + vertical-align: top; +} + +#qunit-tests pre { + margin: 0; + white-space: pre-wrap; + word-wrap: break-word; +} + +#qunit-tests del { + background-color: #e0f2be; + color: #374e0c; + text-decoration: none; +} + +#qunit-tests ins { + background-color: #ffcaca; + color: #500; + text-decoration: none; +} + +/*** Test Counts */ + +#qunit-tests b.counts { color: black; } +#qunit-tests b.passed { color: #5E740B; } +#qunit-tests b.failed { color: #710909; } + +#qunit-tests li li { + margin: 0.5em; + padding: 0.4em 0.5em 0.4em 0.5em; + background-color: #fff; + border-bottom: none; + list-style-position: inside; +} + +/*** Passing Styles */ + +#qunit-tests li li.pass { + color: #5E740B; + background-color: #fff; + border-left: 26px solid #C6E746; +} + +#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } +#qunit-tests .pass .test-name { color: #366097; } + +#qunit-tests .pass .test-actual, +#qunit-tests .pass .test-expected { color: #999999; } + +#qunit-banner.qunit-pass { background-color: #C6E746; } + +/*** Failing Styles */ + +#qunit-tests li li.fail { + color: #710909; + background-color: #fff; + border-left: 26px solid #EE5757; + white-space: pre; +} + +#qunit-tests > li:last-child { + border-radius: 0 0 15px 15px; + -moz-border-radius: 0 0 15px 15px; + -webkit-border-bottom-right-radius: 15px; + -webkit-border-bottom-left-radius: 15px; +} + +#qunit-tests .fail { color: #000000; background-color: #EE5757; } +#qunit-tests .fail .test-name, +#qunit-tests .fail .module-name { color: #000000; } + +#qunit-tests .fail .test-actual { color: #EE5757; } +#qunit-tests .fail .test-expected { color: green; } + +#qunit-banner.qunit-fail { background-color: #EE5757; } + + +/** Result */ + +#qunit-testresult { + padding: 0.5em 0.5em 0.5em 2.5em; + + color: #2b81af; + background-color: #D2E0E6; + + border-bottom: 1px solid white; +} +#qunit-testresult .module-name { + font-weight: bold; +} + +/** Fixture */ + +#qunit-fixture { + position: absolute; + top: -10000px; + left: -10000px; + width: 1000px; + height: 1000px; +} diff --git a/js/js.translator/qunit/qunit.js b/js/js.translator/qunit/qunit.js new file mode 100644 index 00000000000..3b78401fafa --- /dev/null +++ b/js/js.translator/qunit/qunit.js @@ -0,0 +1,1803 @@ +/** + * QUnit v1.7.0pre - A JavaScript Unit Testing Framework + * + * http://docs.jquery.com/QUnit + * + * Copyright (c) 2012 John Resig, Jörn Zaefferer + * Dual licensed under the MIT (MIT-LICENSE.txt) + * or GPL (GPL-LICENSE.txt) licenses. + */ + +(function( window ) { + +var QUnit, + config, + testId = 0, + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + defined = { + setTimeout: typeof window.setTimeout !== "undefined", + sessionStorage: (function() { + var x = "qunit-test-string"; + try { + sessionStorage.setItem( x, x ); + sessionStorage.removeItem( x ); + return true; + } catch( e ) { + return false; + } + }()) +}; + +function Test( settings ) { + extend( this, settings ); + this.assertions = []; + this.testNumber = ++Test.count; +} + +Test.count = 0; + +Test.prototype = { + init: function() { + var a, b, li, + tests = id( "qunit-tests" ); + + if ( tests ) { + b = document.createElement( "strong" ); + b.innerHTML = this.name; + + // `a` initialized at top of scope + a = document.createElement( "a" ); + a.innerHTML = "Rerun"; + a.href = QUnit.url({ testNumber: this.testNumber }); + + li = document.createElement( "li" ); + li.appendChild( b ); + li.appendChild( a ); + li.className = "running"; + li.id = this.id = "qunit-test-output" + testId++; + + tests.appendChild( li ); + } + }, + setup: function() { + if ( this.module !== config.previousModule ) { + if ( config.previousModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + config.previousModule = this.module; + config.moduleStats = { all: 0, bad: 0 }; + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } else if ( config.autorun ) { + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } + + config.current = this; + + this.testEnvironment = extend({ + setup: function() {}, + teardown: function() {} + }, this.moduleTestEnvironment ); + + runLoggingCallbacks( "testStart", QUnit, { + name: this.testName, + module: this.module + }); + + // allow utility functions to access the current test environment + // TODO why?? + QUnit.current_testEnvironment = this.testEnvironment; + + if ( !config.pollution ) { + saveGlobal(); + } + if ( config.notrycatch ) { + this.testEnvironment.setup.call( this.testEnvironment ); + return; + } + try { + this.testEnvironment.setup.call( this.testEnvironment ); + } catch( e ) { + QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); + } + }, + run: function() { + config.current = this; + + var running = id( "qunit-testresult" ); + + if ( running ) { + running.innerHTML = "Running:
" + this.name; + } + + if ( this.async ) { + QUnit.stop(); + } + + if ( config.notrycatch ) { + this.callback.call( this.testEnvironment, QUnit.assert ); + return; + } + + try { + this.callback.call( this.testEnvironment, QUnit.assert ); + } catch( e ) { + QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + ": " + e.message, extractStacktrace( e, 1 ) ); + // else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if ( config.blocking ) { + QUnit.start(); + } + } + }, + teardown: function() { + config.current = this; + if ( config.notrycatch ) { + this.testEnvironment.teardown.call( this.testEnvironment ); + return; + } else { + try { + this.testEnvironment.teardown.call( this.testEnvironment ); + } catch( e ) { + QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); + } + } + checkPollution(); + }, + finish: function() { + config.current = this; + if ( this.expected != null && this.expected != this.assertions.length ) { + QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); + } else if ( this.expected == null && !this.assertions.length ) { + QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); + } + + var assertion, a, b, i, li, ol, + test = this, + good = 0, + bad = 0, + tests = id( "qunit-tests" ); + + config.stats.all += this.assertions.length; + config.moduleStats.all += this.assertions.length; + + if ( tests ) { + ol = document.createElement( "ol" ); + + for ( i = 0; i < this.assertions.length; i++ ) { + assertion = this.assertions[i]; + + li = document.createElement( "li" ); + li.className = assertion.result ? "pass" : "fail"; + li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); + ol.appendChild( li ); + + if ( assertion.result ) { + good++; + } else { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + + // store result when possible + if ( QUnit.config.reorder && defined.sessionStorage ) { + if ( bad ) { + sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); + } else { + sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); + } + } + + if ( bad === 0 ) { + ol.style.display = "none"; + } + + // `b` initialized at top of scope + b = document.createElement( "strong" ); + b.innerHTML = this.name + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; + + addEvent(b, "click", function() { + var next = b.nextSibling.nextSibling, + display = next.style.display; + next.style.display = display === "none" ? "block" : "none"; + }); + + addEvent(b, "dblclick", function( e ) { + var target = e && e.target ? e.target : window.event.srcElement; + if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { + target = target.parentNode; + } + if ( window.location && target.nodeName.toLowerCase() === "strong" ) { + window.location = QUnit.url({ testNumber: test.testNumber }); + } + }); + + // `li` initialized at top of scope + li = id( this.id ); + li.className = bad ? "fail" : "pass"; + li.removeChild( li.firstChild ); + a = li.firstChild; + li.appendChild( b ); + li.appendChild ( a ); + li.appendChild( ol ); + + } else { + for ( i = 0; i < this.assertions.length; i++ ) { + if ( !this.assertions[i].result ) { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + } + + runLoggingCallbacks( "testDone", QUnit, { + name: this.testName, + module: this.module, + failed: bad, + passed: this.assertions.length - bad, + total: this.assertions.length + }); + + QUnit.reset(); + }, + + queue: function() { + var bad, + test = this; + + synchronize(function() { + test.init(); + }); + function run() { + // each of these can by async + synchronize(function() { + test.setup(); + }); + synchronize(function() { + test.run(); + }); + synchronize(function() { + test.teardown(); + }); + synchronize(function() { + test.finish(); + }); + } + + // `bad` initialized at top of scope + // defer when previous test run passed, if storage is available + bad = QUnit.config.reorder && defined.sessionStorage && + +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); + + if ( bad ) { + run(); + } else { + synchronize( run, true ); + } + } +}; + +// Root QUnit object. +// `QUnit` initialized at top of scope +QUnit = { + + // call on start of module test to prepend name to all tests + module: function( name, testEnvironment ) { + config.currentModule = name; + config.currentModuleTestEnviroment = testEnvironment; + }, + + asyncTest: function( testName, expected, callback ) { + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + QUnit.test( testName, expected, callback, true ); + }, + + test: function( testName, expected, callback, async ) { + var test, + name = "" + escapeInnerText( testName ) + ""; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + if ( config.currentModule ) { + name = "" + config.currentModule + ": " + name; + } + + test = new Test({ + name: name, + testName: testName, + expected: expected, + async: async, + callback: callback, + module: config.currentModule, + moduleTestEnvironment: config.currentModuleTestEnviroment, + stack: sourceFromStacktrace( 2 ) + }); + + if ( !validTest( test ) ) { + return; + } + + test.queue(); + }, + + // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. + expect: function( asserts ) { + config.current.expected = asserts; + }, + + start: function( count ) { + config.semaphore -= count || 1; + // don't start until equal number of stop-calls + if ( config.semaphore > 0 ) { + return; + } + // ignore if start is called more often then stop + if ( config.semaphore < 0 ) { + config.semaphore = 0; + } + // A slight delay, to avoid any current callbacks + if ( defined.setTimeout ) { + window.setTimeout(function() { + if ( config.semaphore > 0 ) { + return; + } + if ( config.timeout ) { + clearTimeout( config.timeout ); + } + + config.blocking = false; + process( true ); + }, 13); + } else { + config.blocking = false; + process( true ); + } + }, + + stop: function( count ) { + config.semaphore += count || 1; + config.blocking = true; + + if ( config.testTimeout && defined.setTimeout ) { + clearTimeout( config.timeout ); + config.timeout = window.setTimeout(function() { + QUnit.ok( false, "Test timed out" ); + config.semaphore = 1; + QUnit.start(); + }, config.testTimeout ); + } + } +}; + +// Asssert helpers +// All of these must call either QUnit.push() or manually do: +// - runLoggingCallbacks( "log", .. ); +// - config.current.assertions.push({ .. }); +QUnit.assert = { + /** + * Asserts rough true-ish result. + * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); + */ + ok: function( result, msg ) { + if ( !config.current ) { + throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + result = !!result; + + var source, + details = { + result: result, + message: msg + }; + + msg = escapeInnerText( msg || (result ? "okay" : "failed" ) ); + msg = "" + msg + ""; + + if ( !result ) { + source = sourceFromStacktrace( 2 ); + if ( source ) { + details.source = source; + msg += "
Source:
" + escapeInnerText( source ) + "
"; + } + } + runLoggingCallbacks( "log", QUnit, details ); + config.current.assertions.push({ + result: result, + message: msg + }); + }, + + /** + * Assert that the first two arguments are equal, with an optional message. + * Prints out both actual and expected values. + * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); + */ + equal: function( actual, expected, message ) { + QUnit.push( expected == actual, actual, expected, message ); + }, + + notEqual: function( actual, expected, message ) { + QUnit.push( expected != actual, actual, expected, message ); + }, + + deepEqual: function( actual, expected, message ) { + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + notDeepEqual: function( actual, expected, message ) { + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + strictEqual: function( actual, expected, message ) { + QUnit.push( expected === actual, actual, expected, message ); + }, + + notStrictEqual: function( actual, expected, message ) { + QUnit.push( expected !== actual, actual, expected, message ); + }, + + raises: function( block, expected, message ) { + var actual, + ok = false; + + if ( typeof expected === "string" ) { + message = expected; + expected = null; + } + + try { + block.call( config.current.testEnvironment ); + } catch (e) { + actual = e; + } + + if ( actual ) { + // we don't want to validate thrown error + if ( !expected ) { + ok = true; + // expected is a regexp + } else if ( QUnit.objectType( expected ) === "regexp" ) { + ok = expected.test( actual ); + // expected is a constructor + } else if ( actual instanceof expected ) { + ok = true; + // expected is a validation function which returns true is validation passed + } else if ( expected.call( {}, actual ) === true ) { + ok = true; + } + } + + QUnit.push( ok, actual, null, message ); + } +}; + +// @deprecated: Kept assertion helpers in root for backwards compatibility +extend( QUnit, QUnit.assert ); + +/** + * @deprecated: Kept for backwards compatibility + * next step: remove entirely + */ +QUnit.equals = function() { + QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); +}; +QUnit.same = function() { + QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); +}; + +// We want access to the constructor's prototype +(function() { + function F() {} + F.prototype = QUnit; + QUnit = new F(); + // Make F QUnit's constructor so that we can add to the prototype later + QUnit.constructor = F; +}()); + +/** + * Config object: Maintain internal state + * Later exposed as QUnit.config + * `config` initialized at top of scope + */ +config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true, + + // when enabled, show only failing tests + // gets persisted through sessionStorage and can be changed in UI via checkbox + hidepassed: false, + + // by default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // by default, modify document.title when suite is done + altertitle: true, + + urlConfig: [ "noglobals", "notrycatch" ], + + // logging callback queues + begin: [], + done: [], + log: [], + testStart: [], + testDone: [], + moduleStart: [], + moduleDone: [] +}; + +// Initialize more QUnit.config and QUnit.urlParams +(function() { + var i, + location = window.location || { search: "", protocol: "file:" }, + params = location.search.slice( 1 ).split( "&" ), + length = params.length, + urlParams = {}, + current; + + if ( params[ 0 ] ) { + for ( i = 0; i < length; i++ ) { + current = params[ i ].split( "=" ); + current[ 0 ] = decodeURIComponent( current[ 0 ] ); + // allow just a key to turn on a flag, e.g., test.html?noglobals + current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; + urlParams[ current[ 0 ] ] = current[ 1 ]; + } + } + + QUnit.urlParams = urlParams; + config.filter = urlParams.filter; + config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = location.protocol === "file:"; +}()); + +// Export global variables, unless an 'exports' object exists, +// in that case we assume we're in CommonJS (dealt with on the bottom of the script) +if ( typeof exports === "undefined" ) { + extend( window, QUnit ); + + // Expose QUnit object + window.QUnit = QUnit; +} + +// Extend QUnit object, +// these after set here because they should not be exposed as global functions +extend( QUnit, { + config: config, + + // Initialize the configuration options + init: function() { + extend( config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date(), + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + filter: "", + queue: [], + semaphore: 0 + }); + + var tests, banner, result, + qunit = id( "qunit" ); + + if ( qunit ) { + qunit.innerHTML = + "

" + escapeInnerText( document.title ) + "

" + + "

" + + "
" + + "

" + + "
    "; + } + + tests = id( "qunit-tests" ); + banner = id( "qunit-banner" ); + result = id( "qunit-testresult" ); + + if ( tests ) { + tests.innerHTML = ""; + } + + if ( banner ) { + banner.className = ""; + } + + if ( result ) { + result.parentNode.removeChild( result ); + } + + if ( tests ) { + result = document.createElement( "p" ); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore( result, tests ); + result.innerHTML = "Running...
     "; + } + }, + + // Resets the test setup. Useful for tests that modify the DOM. + // If jQuery is available, uses jQuery's html(), otherwise just innerHTML. + reset: function() { + var fixture; + + if ( window.jQuery ) { + jQuery( "#qunit-fixture" ).html( config.fixture ); + } else { + fixture = id( "qunit-fixture" ); + if ( fixture ) { + fixture.innerHTML = config.fixture; + } + } + }, + + // Trigger an event on an element. + // @example triggerEvent( document.body, "click" ); + triggerEvent: function( elem, type, event ) { + if ( document.createEvent ) { + event = document.createEvent( "MouseEvents" ); + event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, + 0, 0, 0, 0, 0, false, false, false, false, 0, null); + + elem.dispatchEvent( event ); + } else if ( elem.fireEvent ) { + elem.fireEvent( "on" + type ); + } + }, + + // Safe object type checking + is: function( type, obj ) { + return QUnit.objectType( obj ) == type; + }, + + objectType: function( obj ) { + if ( typeof obj === "undefined" ) { + return "undefined"; + // consider: typeof null === object + } + if ( obj === null ) { + return "null"; + } + + var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ""; + + switch ( type ) { + case "Number": + if ( isNaN(obj) ) { + return "nan"; + } + return "number"; + case "String": + case "Boolean": + case "Array": + case "Date": + case "RegExp": + case "Function": + return type.toLowerCase(); + } + if ( typeof obj === "object" ) { + return "object"; + } + return undefined; + }, + + push: function( result, actual, expected, message ) { + if ( !config.current ) { + throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); + } + + var output, source, + details = { + result: result, + message: message, + actual: actual, + expected: expected + }; + + message = escapeInnerText( message ) || ( result ? "okay" : "failed" ); + message = "" + message + ""; + output = message; + + if ( !result ) { + expected = escapeInnerText( QUnit.jsDump.parse(expected) ); + actual = escapeInnerText( QUnit.jsDump.parse(actual) ); + output += ""; + + if ( actual != expected ) { + output += ""; + output += ""; + } + + source = sourceFromStacktrace(); + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
    Expected:
    " + expected + "
    Result:
    " + actual + "
    Diff:
    " + QUnit.diff( expected, actual ) + "
    Source:
    " + escapeInnerText( source ) + "
    "; + } + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: !!result, + message: output + }); + }, + + pushFailure: function( message, source ) { + var output, + details = { + result: false, + message: message + }; + + message = escapeInnerText(message ) || "error"; + message = "" + message + ""; + output = message; + + if ( source ) { + details.source = source; + output += "
    Source:
    " + escapeInnerText( source ) + "
    "; + } + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: false, + message: output + }); + }, + + url: function( params ) { + params = extend( extend( {}, QUnit.urlParams ), params ); + var key, + querystring = "?"; + + for ( key in params ) { + if ( !hasOwn.call( params, key ) ) { + continue; + } + querystring += encodeURIComponent( key ) + "=" + + encodeURIComponent( params[ key ] ) + "&"; + } + return window.location.pathname + querystring.slice( 0, -1 ); + }, + + extend: extend, + id: id, + addEvent: addEvent + // load, equiv, jsDump, diff: Attached later +}); + +/** + * @deprecated: Created for backwards compatibility with test runner that set the hook function + * into QUnit.{hook}, instead of invoking it and passing the hook function. + * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. + * Doing this allows us to tell if the following methods have been overwritten on the actual + * QUnit object. + */ +extend( QUnit.constructor.prototype, { + + // Logging callbacks; all receive a single argument with the listed properties + // run test/logs.html for any related changes + begin: registerLoggingCallback( "begin" ), + + // done: { failed, passed, total, runtime } + done: registerLoggingCallback( "done" ), + + // log: { result, actual, expected, message } + log: registerLoggingCallback( "log" ), + + // testStart: { name } + testStart: registerLoggingCallback( "testStart" ), + + // testDone: { name, failed, passed, total } + testDone: registerLoggingCallback( "testDone" ), + + // moduleStart: { name } + moduleStart: registerLoggingCallback( "moduleStart" ), + + // moduleDone: { name, failed, passed, total } + moduleDone: registerLoggingCallback( "moduleDone" ) +}); + +if ( typeof document === "undefined" || document.readyState === "complete" ) { + config.autorun = true; +} + +QUnit.load = function() { + runLoggingCallbacks( "begin", QUnit, {} ); + + // Initialize the config, saving the execution queue + var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, + urlConfigHtml = "", + oldconfig = extend( {}, config ); + + QUnit.init(); + extend(config, oldconfig); + + config.blocking = false; + + len = config.urlConfig.length; + + for ( i = 0; i < len; i++ ) { + val = config.urlConfig[i]; + config[val] = QUnit.urlParams[val]; + urlConfigHtml += ""; + } + + // `userAgent` initialized at top of scope + userAgent = id( "qunit-userAgent" ); + if ( userAgent ) { + userAgent.innerHTML = navigator.userAgent; + } + + // `banner` initialized at top of scope + banner = id( "qunit-header" ); + if ( banner ) { + banner.innerHTML = "" + banner.innerHTML + " " + urlConfigHtml; + addEvent( banner, "change", function( event ) { + var params = {}; + params[ event.target.name ] = event.target.checked ? true : undefined; + window.location = QUnit.url( params ); + }); + } + + // `toolbar` initialized at top of scope + toolbar = id( "qunit-testrunner-toolbar" ); + if ( toolbar ) { + // `filter` initialized at top of scope + filter = document.createElement( "input" ); + filter.type = "checkbox"; + filter.id = "qunit-filter-pass"; + + addEvent( filter, "click", function() { + var tmp, + ol = document.getElementById( "qunit-tests" ); + + if ( filter.checked ) { + ol.className = ol.className + " hidepass"; + } else { + tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; + ol.className = tmp.replace( / hidepass /, " " ); + } + if ( defined.sessionStorage ) { + if (filter.checked) { + sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); + } else { + sessionStorage.removeItem( "qunit-filter-passed-tests" ); + } + } + }); + + if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { + filter.checked = true; + // `ol` initialized at top of scope + ol = document.getElementById( "qunit-tests" ); + ol.className = ol.className + " hidepass"; + } + toolbar.appendChild( filter ); + + // `label` initialized at top of scope + label = document.createElement( "label" ); + label.setAttribute( "for", "qunit-filter-pass" ); + label.innerHTML = "Hide passed tests"; + toolbar.appendChild( label ); + } + + // `main` initialized at top of scope + main = id( "qunit-fixture" ); + if ( main ) { + config.fixture = main.innerHTML; + } + + if ( config.autostart ) { + QUnit.start(); + } +}; + +addEvent( window, "load", QUnit.load ); + +// addEvent(window, "error" ) gives us a useless event object +window.onerror = function( message, file, line ) { + if ( QUnit.config.current ) { + QUnit.pushFailure( message, file + ":" + line ); + } else { + QUnit.test( "global failure", function() { + QUnit.pushFailure( message, file + ":" + line ); + }); + } +}; + +function done() { + config.autorun = true; + + // Log the last module results + if ( config.currentModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.currentModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + + var i, key, + banner = id( "qunit-banner" ), + tests = id( "qunit-tests" ), + runtime = +new Date() - config.started, + passed = config.stats.all - config.stats.bad, + html = [ + "Tests completed in ", + runtime, + " milliseconds.
    ", + "", + passed, + " tests of ", + config.stats.all, + " passed, ", + config.stats.bad, + " failed." + ].join( "" ); + + if ( banner ) { + banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); + } + + if ( tests ) { + id( "qunit-testresult" ).innerHTML = html; + } + + if ( config.altertitle && typeof document !== "undefined" && document.title ) { + // show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8-charset + document.title = [ + ( config.stats.bad ? "\u2716" : "\u2714" ), + document.title.replace( /^[\u2714\u2716] /i, "" ) + ].join( " " ); + } + + // clear own sessionStorage items if all tests passed + if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { + // `key` & `i` initialized at top of scope + for ( i = 0; i < sessionStorage.length; i++ ) { + key = sessionStorage.key( i++ ); + if ( key.indexOf( "qunit-test-" ) === 0 ) { + sessionStorage.removeItem( key ); + } + } + } + + runLoggingCallbacks( "done", QUnit, { + failed: config.stats.bad, + passed: passed, + total: config.stats.all, + runtime: runtime + }); +} + +function validTest( test ) { + var include, + filter = config.filter && config.filter.toLowerCase(), + fullName = (test.module + ": " + test.testName).toLowerCase(); + + if ( config.testNumber ) { + return test.testNumber === config.testNumber; + } + + if ( !filter ) { + return true; + } + + include = filter.charAt( 0 ) !== "!"; + if ( !include ) { + filter = filter.slice( 1 ); + } + + // If the filter matches, we need to honour include + if ( fullName.indexOf( filter ) !== -1 ) { + return include; + } + + // Otherwise, do the opposite + return !include; +} + +// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) +// Later Safari and IE10 are supposed to support error.stack as well +// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack +function extractStacktrace( e, offset ) { + offset = offset || 3; + + var stack; + + if ( e.stacktrace ) { + // Opera + return e.stacktrace.split( "\n" )[ offset + 3 ]; + } else if ( e.stack ) { + // Firefox, Chrome + stack = e.stack.split( "\n" ); + if (/^error$/i.test( stack[0] ) ) { + stack.shift(); + } + return stack[ offset ]; + } else if ( e.sourceURL ) { + // Safari, PhantomJS + // hopefully one day Safari provides actual stacktraces + // exclude useless self-reference for generated Error objects + if ( /qunit.js$/.test( e.sourceURL ) ) { + return; + } + // for actual exceptions, this is useful + return e.sourceURL + ":" + e.line; + } +} +function sourceFromStacktrace( offset ) { + try { + throw new Error(); + } catch ( e ) { + return extractStacktrace( e, offset ); + } +} + +function escapeInnerText( s ) { + if ( !s ) { + return ""; + } + s = s + ""; + return s.replace( /[\&<>]/g, function( s ) { + switch( s ) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + default: return s; + } + }); +} + +function synchronize( callback, last ) { + config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process( last ); + } +} + +function process( last ) { + function next() { + process( last ); + } + var start = new Date().getTime(); + config.depth = config.depth ? config.depth + 1 : 1; + + while ( config.queue.length && !config.blocking ) { + if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { + config.queue.shift()(); + } else { + window.setTimeout( next, 13 ); + break; + } + } + config.depth--; + if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { + done(); + } +} + +function saveGlobal() { + config.pollution = []; + + if ( config.noglobals ) { + for ( var key in window ) { + // in Opera sometimes DOM element ids show up here, ignore them + if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) { + continue; + } + config.pollution.push( key ); + } + } +} + +function checkPollution( name ) { + var newGlobals, + deletedGlobals, + old = config.pollution; + + saveGlobal(); + + newGlobals = diff( config.pollution, old ); + if ( newGlobals.length > 0 ) { + QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); + } + + deletedGlobals = diff( old, config.pollution ); + if ( deletedGlobals.length > 0 ) { + QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); + } +} + +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var i, j, + result = a.slice(); + + for ( i = 0; i < result.length; i++ ) { + for ( j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice( i, 1 ); + i--; + break; + } + } + } + return result; +} + +function extend( a, b ) { + for ( var prop in b ) { + if ( b[ prop ] === undefined ) { + delete a[ prop ]; + + // Avoid "Member not found" error in IE8 caused by setting window.constructor + } else if ( prop !== "constructor" || a !== window ) { + a[ prop ] = b[ prop ]; + } + } + + return a; +} + +function addEvent( elem, type, fn ) { + if ( elem.addEventListener ) { + elem.addEventListener( type, fn, false ); + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, fn ); + } else { + fn(); + } +} + +function id( name ) { + return !!( typeof document !== "undefined" && document && document.getElementById ) && + document.getElementById( name ); +} + +function registerLoggingCallback( key ) { + return function( callback ) { + config[key].push( callback ); + }; +} + +// Supports deprecated method of completely overwriting logging callbacks +function runLoggingCallbacks( key, scope, args ) { + //debugger; + var i, callbacks; + if ( QUnit.hasOwnProperty( key ) ) { + QUnit[ key ].call(scope, args ); + } else { + callbacks = config[ key ]; + for ( i = 0; i < callbacks.length; i++ ) { + callbacks[ i ].call( scope, args ); + } + } +} + +// Test for equality any JavaScript type. +// Author: Philippe Rathé +QUnit.equiv = (function() { + + // Call the o related callback with the given arguments. + function bindCallbacks( o, callbacks, args ) { + var prop = QUnit.objectType( o ); + if ( prop ) { + if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { + return callbacks[ prop ].apply( callbacks, args ); + } else { + return callbacks[ prop ]; // or undefined + } + } + } + + // the real equiv function + var innerEquiv, + // stack to decide between skip/abort functions + callers = [], + // stack to avoiding loops from circular referencing + parents = [], + + getProto = Object.getPrototypeOf || function ( obj ) { + return obj.__proto__; + }, + callbacks = (function () { + + // for string, boolean, number and null + function useStrictEquality( b, a ) { + if ( b instanceof a.constructor || a instanceof b.constructor ) { + // to catch short annotaion VS 'new' annotation of a + // declaration + // e.g. var i = 1; + // var j = new Number(1); + return a == b; + } else { + return a === b; + } + } + + return { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + + "nan": function( b ) { + return isNaN( b ); + }, + + "date": function( b, a ) { + return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); + }, + + "regexp": function( b, a ) { + return QUnit.objectType( b ) === "regexp" && + // the regex itself + a.source === b.source && + // and its modifers + a.global === b.global && + // (gmi) ... + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline; + }, + + // - skip when the property is a method of an instance (OOP) + // - abort otherwise, + // initial === would have catch identical references anyway + "function": function() { + var caller = callers[callers.length - 1]; + return caller !== Object && typeof caller !== "undefined"; + }, + + "array": function( b, a ) { + var i, j, len, loop; + + // b could be an object literal here + if ( QUnit.objectType( b ) !== "array" ) { + return false; + } + + len = a.length; + if ( len !== b.length ) { + // safe and faster + return false; + } + + // track reference to avoid circular references + parents.push( a ); + for ( i = 0; i < len; i++ ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + if ( parents[j] === a[i] ) { + loop = true;// dont rewalk array + } + } + if ( !loop && !innerEquiv(a[i], b[i]) ) { + parents.pop(); + return false; + } + } + parents.pop(); + return true; + }, + + "object": function( b, a ) { + var i, j, loop, + // Default to true + eq = true, + aProperties = [], + bProperties = []; + + // comparing constructors is more strict than using + // instanceof + if ( a.constructor !== b.constructor ) { + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || + ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { + return false; + } + } + + // stack constructor before traversing properties + callers.push( a.constructor ); + // track reference to avoid circular references + parents.push( a ); + + for ( i in a ) { // be strict: don't ensures hasOwnProperty + // and go deep + loop = false; + for ( j = 0; j < parents.length; j++ ) { + if ( parents[j] === a[i] ) { + // don't go down the same path twice + loop = true; + } + } + aProperties.push(i); // collect a's properties + + if (!loop && !innerEquiv( a[i], b[i] ) ) { + eq = false; + break; + } + } + + callers.pop(); // unstack, we are done + parents.pop(); + + for ( i in b ) { + bProperties.push( i ); // collect b's properties + } + + // Ensures identical properties name + return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); + } + }; + }()); + + innerEquiv = function() { // can take multiple arguments + var args = [].slice.apply( arguments ); + if ( args.length < 2 ) { + return true; // end transition + } + + return (function( a, b ) { + if ( a === b ) { + return true; // catch the most you can + } else if ( a === null || b === null || typeof a === "undefined" || + typeof b === "undefined" || + QUnit.objectType(a) !== QUnit.objectType(b) ) { + return false; // don't lose time with error prone cases + } else { + return bindCallbacks(a, callbacks, [ b, a ]); + } + + // apply transition with (1..n) arguments + }( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) ); + }; + + return innerEquiv; +}()); + +/** + * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | + * http://flesler.blogspot.com Licensed under BSD + * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 + * + * @projectDescription Advanced and extensible data dumping for Javascript. + * @version 1.0.0 + * @author Ariel Flesler + * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} + */ +QUnit.jsDump = (function() { + function quote( str ) { + return '"' + str.toString().replace( /"/g, '\\"' ) + '"'; + } + function literal( o ) { + return o + ""; + } + function join( pre, arr, post ) { + var s = jsDump.separator(), + base = jsDump.indent(), + inner = jsDump.indent(1); + if ( arr.join ) { + arr = arr.join( "," + s + inner ); + } + if ( !arr ) { + return pre + post; + } + return [ pre, inner + arr, base + post ].join(s); + } + function array( arr, stack ) { + var i = arr.length, ret = new Array(i); + this.up(); + while ( i-- ) { + ret[i] = this.parse( arr[i] , undefined , stack); + } + this.down(); + return join( "[", ret, "]" ); + } + + var reName = /^function (\w+)/, + jsDump = { + parse: function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance + stack = stack || [ ]; + var inStack, res, + parser = this.parsers[ type || this.typeOf(obj) ]; + + type = typeof parser; + inStack = inArray( obj, stack ); + + if ( inStack != -1 ) { + return "recursion(" + (inStack - stack.length) + ")"; + } + //else + if ( type == "function" ) { + stack.push( obj ); + res = parser.call( this, obj, stack ); + stack.pop(); + return res; + } + // else + return ( type == "string" ) ? parser : this.parsers.error; + }, + typeOf: function( obj ) { + var type; + if ( obj === null ) { + type = "null"; + } else if ( typeof obj === "undefined" ) { + type = "undefined"; + } else if ( QUnit.is( "regexp", obj) ) { + type = "regexp"; + } else if ( QUnit.is( "date", obj) ) { + type = "date"; + } else if ( QUnit.is( "function", obj) ) { + type = "function"; + } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { + type = "window"; + } else if ( obj.nodeType === 9 ) { + type = "document"; + } else if ( obj.nodeType ) { + type = "node"; + } else if ( + // native arrays + toString.call( obj ) === "[object Array]" || + // NodeList objects + ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) + ) { + type = "array"; + } else { + type = typeof obj; + } + return type; + }, + separator: function() { + return this.multiline ? this.HTML ? "
    " : "\n" : this.HTML ? " " : " "; + }, + indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing + if ( !this.multiline ) { + return ""; + } + var chr = this.indentChar; + if ( this.HTML ) { + chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); + } + return new Array( this._depth_ + (extra||0) ).join(chr); + }, + up: function( a ) { + this._depth_ += a || 1; + }, + down: function( a ) { + this._depth_ -= a || 1; + }, + setParser: function( name, parser ) { + this.parsers[name] = parser; + }, + // The next 3 are exposed so you can use them + quote: quote, + literal: literal, + join: join, + // + _depth_: 1, + // This is the list of parsers, to modify them, use jsDump.setParser + parsers: { + window: "[Window]", + document: "[Document]", + error: "[ERROR]", //when no parser is found, shouldn"t happen + unknown: "[Unknown]", + "null": "null", + "undefined": "undefined", + "function": function( fn ) { + var ret = "function", + name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];//functions never have name in IE + + if ( name ) { + ret += " " + name; + } + ret += "( "; + + ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); + return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); + }, + array: array, + nodelist: array, + "arguments": array, + object: function( map, stack ) { + var ret = [ ], keys, key, val, i; + QUnit.jsDump.up(); + if ( Object.keys ) { + keys = Object.keys( map ); + } else { + keys = []; + for ( key in map ) { + keys.push( key ); + } + } + keys.sort(); + for ( i = 0; i < keys.length; i++ ) { + key = keys[ i ]; + val = map[ key ]; + ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); + } + QUnit.jsDump.down(); + return join( "{", ret, "}" ); + }, + node: function( node ) { + var a, val, + open = QUnit.jsDump.HTML ? "<" : "<", + close = QUnit.jsDump.HTML ? ">" : ">", + tag = node.nodeName.toLowerCase(), + ret = open + tag; + + for ( a in QUnit.jsDump.DOMAttrs ) { + val = node[ QUnit.jsDump.DOMAttrs[a] ]; + if ( val ) { + ret += " " + a + "=" + QUnit.jsDump.parse( val, "attribute" ); + } + } + return ret + close + open + "/" + tag + close; + }, + functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function + var args, + l = fn.length; + + if ( !l ) { + return ""; + } + + args = new Array(l); + while ( l-- ) { + args[l] = String.fromCharCode(97+l);//97 is 'a' + } + return " " + args.join( ", " ) + " "; + }, + key: quote, //object calls it internally, the key part of an item in a map + functionCode: "[code]", //function calls it internally, it's the content of the function + attribute: quote, //node calls it internally, it's an html attribute value + string: quote, + date: quote, + regexp: literal, //regex + number: literal, + "boolean": literal + }, + DOMAttrs: { + //attributes to dump from nodes, name=>realName + id: "id", + name: "name", + "class": "className" + }, + HTML: false,//if true, entities are escaped ( <, >, \t, space and \n ) + indentChar: " ",//indentation unit + multiline: true //if true, items in a collection, are separated by a \n, else just a space. + }; + + return jsDump; +}()); + +// from Sizzle.js +function getText( elems ) { + var i, elem, + ret = ""; + + for ( i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += getText( elem.childNodes ); + } + } + + return ret; +} + +// from jquery.js +function inArray( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; +} + +/* + * Javascript Diff Algorithm + * By John Resig (http://ejohn.org/) + * Modified by Chu Alan "sprite" + * + * Released under the MIT license. + * + * More Info: + * http://ejohn.org/projects/javascript-diff-algorithm/ + * + * Usage: QUnit.diff(expected, actual) + * + * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" + */ +QUnit.diff = (function() { + function diff( o, n ) { + var i, + ns = {}, + os = {}; + + for ( i = 0; i < n.length; i++ ) { + if ( ns[ n[i] ] == null ) { + ns[ n[i] ] = { + rows: [], + o: null + }; + } + ns[ n[i] ].rows.push( i ); + } + + for ( i = 0; i < o.length; i++ ) { + if ( os[ o[i] ] == null ) { + os[ o[i] ] = { + rows: [], + n: null + }; + } + os[ o[i] ].rows.push( i ); + } + + for ( i in ns ) { + if ( !hasOwn.call( ns, i ) ) { + continue; + } + if ( ns[i].rows.length == 1 && typeof os[i] != "undefined" && os[i].rows.length == 1 ) { + n[ ns[i].rows[0] ] = { + text: n[ ns[i].rows[0] ], + row: os[i].rows[0] + }; + o[ os[i].rows[0] ] = { + text: o[ os[i].rows[0] ], + row: ns[i].rows[0] + }; + } + } + + for ( i = 0; i < n.length - 1; i++ ) { + if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && + n[ i + 1 ] == o[ n[i].row + 1 ] ) { + + n[ i + 1 ] = { + text: n[ i + 1 ], + row: n[i].row + 1 + }; + o[ n[i].row + 1 ] = { + text: o[ n[i].row + 1 ], + row: i + 1 + }; + } + } + + for ( i = n.length - 1; i > 0; i-- ) { + if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && + n[ i - 1 ] == o[ n[i].row - 1 ]) { + + n[ i - 1 ] = { + text: n[ i - 1 ], + row: n[i].row - 1 + }; + o[ n[i].row - 1 ] = { + text: o[ n[i].row - 1 ], + row: i - 1 + }; + } + } + + return { + o: o, + n: n + }; + } + + return function( o, n ) { + o = o.replace( /\s+$/, "" ); + n = n.replace( /\s+$/, "" ); + + var i, pre, + str = "", + out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), + oSpace = o.match(/\s+/g), + nSpace = n.match(/\s+/g); + + if ( oSpace == null ) { + oSpace = [ " " ]; + } + else { + oSpace.push( " " ); + } + + if ( nSpace == null ) { + nSpace = [ " " ]; + } + else { + nSpace.push( " " ); + } + + if ( out.n.length === 0 ) { + for ( i = 0; i < out.o.length; i++ ) { + str += "" + out.o[i] + oSpace[i] + ""; + } + } + else { + if ( out.n[0].text == null ) { + for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { + str += "" + out.o[n] + oSpace[n] + ""; + } + } + + for ( i = 0; i < out.n.length; i++ ) { + if (out.n[i].text == null) { + str += "" + out.n[i] + nSpace[i] + ""; + } + else { + // `pre` initialized at top of scope + pre = ""; + + for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { + pre += "" + out.o[n] + oSpace[n] + ""; + } + str += " " + out.n[i].text + nSpace[i] + pre; + } + } + } + + return str; + }; +}()); + +// for CommonJS enviroments, export everything +if ( typeof exports !== "undefined" ) { + extend(exports, QUnit); +} + +// get at whatever the global object is, like window in browsers +}( (function() {return this;}.call()) )); diff --git a/js/js.translator/qunit/swarminject.js b/js/js.translator/qunit/swarminject.js new file mode 100755 index 00000000000..db69326abe1 --- /dev/null +++ b/js/js.translator/qunit/swarminject.js @@ -0,0 +1,9 @@ +// load testswarm agent +(function() { + var url = window.location.search; + url = decodeURIComponent( url.slice( url.indexOf("swarmURL=") + 9 ) ); + if ( !url || url.indexOf("http") !== 0 ) { + return; + } + document.write(""); +})(); diff --git a/js/js.translator/src/org/jetbrains/k2js/config/Config.java b/js/js.translator/src/org/jetbrains/k2js/config/Config.java index 6f34e12eb7a..cbfc0b1b876 100644 --- a/js/js.translator/src/org/jetbrains/k2js/config/Config.java +++ b/js/js.translator/src/org/jetbrains/k2js/config/Config.java @@ -68,7 +68,8 @@ public abstract class Config { "/dom/domcore.kt", "/dom/html/htmlcore.kt", "/dom/html5/canvas.kt", - "/dom/html/window.kt" + "/dom/html/window.kt", + "/junit/core.kt" ); public static final String LIBRARIES_LOCATION = "js/js.libraries/src"; diff --git a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java index db9f8fff9fe..ddd6dc3a352 100644 --- a/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java +++ b/js/js.translator/src/org/jetbrains/k2js/facade/K2JSTranslator.java @@ -67,35 +67,38 @@ public final class K2JSTranslator { @NotNull public String translateStringWithCallToMain(@NotNull String programText, @NotNull String argumentsString) throws TranslationException { JetFile file = JetFileUtils.createPsiFile("test", programText, getProject()); - String programCode = generateProgramCode(file, MainCallParameters.mainWithArguments(parseString(argumentsString))) + "\n"; + String programCode = generateProgramCode(file, MainCallParameters.mainWithArguments(parseString(argumentsString)), null) + "\n"; String flushOutput = "Kotlin.System.flush();\n"; String programOutput = "Kotlin.System.output();\n"; return flushOutput + programCode + programOutput; } @NotNull - public String generateProgramCode(@NotNull JetFile file, @NotNull MainCallParameters mainCallParameters) throws TranslationException { - JsProgram program = generateProgram(Arrays.asList(file), mainCallParameters); + public String generateProgramCode(@NotNull JetFile file, @NotNull MainCallParameters mainCallParameters, List rawStatements) throws TranslationException { + JsProgram program = generateProgram(Arrays.asList(file), mainCallParameters, rawStatements); CodeGenerator generator = new CodeGenerator(); - return generator.generateToString(program); + return generator.generateToString(program, rawStatements); } @NotNull public String generateProgramCode(@NotNull List files, @NotNull MainCallParameters mainCallParameters) throws TranslationException { - JsProgram program = generateProgram(files, mainCallParameters); + List rawStatements = Lists.newArrayList(); + JsProgram program = generateProgram(files, mainCallParameters, rawStatements); CodeGenerator generator = new CodeGenerator(); - return generator.generateToString(program); + return generator.generateToString(program, rawStatements); } @NotNull - public JsProgram generateProgram(@NotNull List filesToTranslate, @NotNull MainCallParameters mainCallParameters) + public JsProgram generateProgram(@NotNull List filesToTranslate, + @NotNull MainCallParameters mainCallParameters, + List rawStatements) throws TranslationException { JetStandardLibrary.initialize(config.getProject()); BindingContext bindingContext = AnalyzerFacadeForJS.analyzeFilesAndCheckErrors(filesToTranslate, config); Collection files = AnalyzerFacadeForJS.withJsLibAdded(filesToTranslate, config); - return Translation.generateAst(bindingContext, Lists.newArrayList(files), mainCallParameters, config.getTarget()); + return Translation.generateAst(bindingContext, Lists.newArrayList(files), mainCallParameters, config.getTarget(), rawStatements); } @NotNull diff --git a/js/js.translator/src/org/jetbrains/k2js/generate/CodeGenerator.java b/js/js.translator/src/org/jetbrains/k2js/generate/CodeGenerator.java index 5acb2cd5ffa..94f8404d526 100644 --- a/js/js.translator/src/org/jetbrains/k2js/generate/CodeGenerator.java +++ b/js/js.translator/src/org/jetbrains/k2js/generate/CodeGenerator.java @@ -25,6 +25,7 @@ import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.util.List; /** * @author Pavel.Talanov @@ -43,8 +44,8 @@ public final class CodeGenerator { } @NotNull - public static String toString(@NotNull JsProgram program) { - return (new CodeGenerator()).generateToString(program); + public static String toString(@NotNull JsProgram program, List rawStatements) { + return (new CodeGenerator()).generateToString(program, rawStatements); } public void generateToFile(@NotNull JsProgram program, @NotNull File file) throws IOException { @@ -58,8 +59,12 @@ public final class CodeGenerator { } @NotNull - public String generateToString(@NotNull JsProgram program) { + public String generateToString(@NotNull JsProgram program, List rawStatements) { generateCode(program); + for (String statement : rawStatements) { + output.print(statement); + output.newline(); + } return output.toString(); } diff --git a/js/js.translator/src/org/jetbrains/k2js/translate/general/JetTestFunctionDetector.java b/js/js.translator/src/org/jetbrains/k2js/translate/general/JetTestFunctionDetector.java new file mode 100644 index 00000000000..12fca89715f --- /dev/null +++ b/js/js.translator/src/org/jetbrains/k2js/translate/general/JetTestFunctionDetector.java @@ -0,0 +1,86 @@ +/* + * Copyright 2010-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.jetbrains.k2js.translate.general; + +import com.google.common.collect.Lists; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.jet.lang.descriptors.FunctionDescriptor; +import org.jetbrains.jet.lang.descriptors.annotations.AnnotationDescriptor; +import org.jetbrains.jet.lang.psi.*; +import org.jetbrains.jet.lang.resolve.BindingContext; +import org.jetbrains.jet.lang.types.JetType; +import org.jetbrains.k2js.translate.utils.BindingUtils; + +import java.util.List; + +/** + * Helps find functions which are annotated with a @Test annotation from junit + */ +public class JetTestFunctionDetector { + private JetTestFunctionDetector() { + } + + public static boolean isTest(@NotNull BindingContext bindingContext, @NotNull JetNamedFunction function) { + FunctionDescriptor functionDescriptor = BindingUtils.getFunctionDescriptor(bindingContext, function); + if (functionDescriptor != null) { + List annotations = functionDescriptor.getAnnotations(); + if (annotations != null) { + for (AnnotationDescriptor annotation : annotations) { + // TODO ideally we should find the fully qualified name here... + JetType type = annotation.getType(); + String name = type.toString(); + if (name.equals("Test")) { + return true; + } + } + } + } + + if (function.getName().startsWith("test")) { + List parameters = function.getValueParameters(); + return parameters.size() == 0; + } + return false; + } + + @Nullable + public static List findTestFunctions(@NotNull BindingContext bindingContext, @NotNull List files) { + List answer = Lists.newArrayList(); + for (JetFile file : files) { + answer.addAll(getTestFunctions(bindingContext, file.getDeclarations())); + } + return answer; + } + + @Nullable + private static List getTestFunctions(@NotNull BindingContext bindingContext, @NotNull List declarations) { + List answer = Lists.newArrayList(); + for (JetDeclaration declaration : declarations) { + if (declaration instanceof JetClass) { + JetClass klass = (JetClass) declaration; + answer.addAll(getTestFunctions(bindingContext, klass.getDeclarations())); + } else if (declaration instanceof JetNamedFunction) { + JetNamedFunction candidateFunction = (JetNamedFunction) declaration; + if (isTest(bindingContext, candidateFunction)) { + answer.add(candidateFunction); + } + } + } + return answer; + } +} diff --git a/js/js.translator/src/org/jetbrains/k2js/translate/general/Translation.java b/js/js.translator/src/org/jetbrains/k2js/translate/general/Translation.java index 65abfa1a6a9..8139783b312 100644 --- a/js/js.translator/src/org/jetbrains/k2js/translate/general/Translation.java +++ b/js/js.translator/src/org/jetbrains/k2js/translate/general/Translation.java @@ -19,7 +19,10 @@ package org.jetbrains.k2js.translate.general; import com.google.dart.compiler.backend.js.JsNamer; import com.google.dart.compiler.backend.js.JsPrettyNamer; import com.google.dart.compiler.backend.js.ast.*; +import com.intellij.openapi.util.text.StringUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.jet.lang.descriptors.ClassDescriptor; +import org.jetbrains.jet.lang.descriptors.DeclarationDescriptor; import org.jetbrains.jet.lang.descriptors.FunctionDescriptor; import org.jetbrains.jet.lang.descriptors.NamespaceDescriptor; import org.jetbrains.jet.lang.psi.*; @@ -46,6 +49,7 @@ import org.jetbrains.k2js.translate.utils.JsAstUtils; import org.jetbrains.k2js.translate.utils.dangerous.DangerousData; import org.jetbrains.k2js.translate.utils.dangerous.DangerousTranslator; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @@ -144,10 +148,10 @@ public final class Translation { @NotNull public static JsProgram generateAst(@NotNull BindingContext bindingContext, @NotNull List files, @NotNull MainCallParameters mainCallParameters, - @NotNull EcmaVersion ecmaVersion) + @NotNull EcmaVersion ecmaVersion, List rawStatements) throws TranslationException { try { - return doGenerateAst(bindingContext, files, mainCallParameters, ecmaVersion); + return doGenerateAst(bindingContext, files, mainCallParameters, ecmaVersion, rawStatements); } catch (UnsupportedOperationException e) { throw new UnsupportedFeatureException("Unsupported feature used.", e); @@ -160,7 +164,7 @@ public final class Translation { @NotNull private static JsProgram doGenerateAst(@NotNull BindingContext bindingContext, @NotNull List files, @NotNull MainCallParameters mainCallParameters, - @NotNull EcmaVersion ecmaVersion) throws MainFunctionNotFoundException { + @NotNull EcmaVersion ecmaVersion, List rawStatements) throws MainFunctionNotFoundException { //TODO: move some of the code somewhere JetStandardLibrary standardLibrary = JetStandardLibrary.getInstance(); StaticContext staticContext = StaticContext.generateStaticContext(standardLibrary, bindingContext, ecmaVersion); @@ -170,6 +174,7 @@ public final class Translation { if (mainCallParameters.shouldBeGenerated()) { block.getStatements().add(generateCallToMain(context, files, mainCallParameters.arguments())); } + generateTestCalls(context, files, block, rawStatements); JsNamer namer = new JsPrettyNamer(); namer.exec(context.program()); return context.program(); @@ -187,6 +192,7 @@ public final class Translation { return translatedCall.makeStmt(); } + @NotNull private static JsInvocation generateInvocation(@NotNull TranslationContext context, @NotNull JetNamedFunction mainFunction) { FunctionDescriptor functionDescriptor = getFunctionDescriptor(context.bindingContext(), mainFunction); @@ -201,4 +207,54 @@ public final class Translation { arrayLiteral.getExpressions().addAll(toStringLiteralList(arguments, context.program())); JsAstUtils.setArguments(translatedCall, Collections.singletonList(arrayLiteral)); } + + @NotNull + private static void generateTestCalls(@NotNull TranslationContext context, + @NotNull List files, + @NotNull JsBlock block, + List rawStatements) { + ClassDescriptor lastClassDescriptor = null; + boolean declaredVar = false; + List functions = JetTestFunctionDetector.findTestFunctions(context.bindingContext(), files); + for (JetNamedFunction function : functions) { + FunctionDescriptor functionDescriptor = getFunctionDescriptor(context.bindingContext(), function); + String funName = functionDescriptor.getName().getName(); + DeclarationDescriptor containingDeclaration = functionDescriptor.getContainingDeclaration(); + if (containingDeclaration instanceof ClassDescriptor) { + ClassDescriptor classDescriptor = (ClassDescriptor) containingDeclaration; + String className = getQualifiedName(classDescriptor); + if (lastClassDescriptor != classDescriptor) { + lastClassDescriptor = classDescriptor; + String prefix = ""; + if (!declaredVar) { + prefix = "var "; + declaredVar = true; + } + rawStatements.add(prefix + "_testCase = new " + className + "();"); + } + rawStatements.add("QUnit.test( \"" + className + "." + funName + "()\" , function() {"); + rawStatements.add(" expect(0);"); + rawStatements.add(" _testCase." + funName + "();"); + } else { + rawStatements.add("QUnit.test( \"" + funName + "()\", function() {"); + rawStatements.add(" expect(0);"); + rawStatements.add(" " + funName + "();"); + } + rawStatements.add("});"); + } + } + + public static String getQualifiedName(ClassDescriptor classDescriptor) { + List parts = new ArrayList(); + DeclarationDescriptor current = classDescriptor; + while (current != null) { + String name = current.getName().getName(); + if (name.startsWith("<")) break; + parts.add(name); + current = current.getContainingDeclaration(); + } + Collections.reverse(parts); + return StringUtil.join(parts, "."); + } + } diff --git a/libraries/stdlib/test/js/SimpleTest.kt b/libraries/stdlib/test/js/SimpleTest.kt new file mode 100644 index 00000000000..6f2bc94f7b0 --- /dev/null +++ b/libraries/stdlib/test/js/SimpleTest.kt @@ -0,0 +1,16 @@ +package testPackage + +import org.junit.Test as test + +class SimpleTest { + + public fun testFoo() { + val name = "world" + val message = "hello $name!" + } + + test fun cheese() { + val name = "world" + val message = "bye $name!" + } +} \ No newline at end of file