From 1bd2b8a24f7d5e051571473a054c3720fd34067b Mon Sep 17 00:00:00 2001 From: plamen5kov Date: Tue, 28 Apr 2015 14:53:47 +0300 Subject: [PATCH 1/4] refactored all tests to work with jasmine tests produce android_unit_test_results.xml file in /sdcard of device, removed old tests and unused files --- test-app/.settings/org.eclipse.jdt.core.prefs | 1 + .../Jasmine/jasmine-2.0.1/boot.js | 139 + .../Jasmine/jasmine-2.0.1/jasmine.js | 2517 +++++++++++++ .../jasmine-reporters/junit_reporter.js | 315 ++ .../jasmine-reporters/terminal_reporter.js | 222 ++ .../app/Infrastructure/Jasmine/jasmine.d.ts | 434 +++ test-app/assets/app/Infrastructure/timers.js | 51 + test-app/assets/app/bootstrap.js | 21 + test-app/assets/app/mainpage.js | 42 +- test-app/assets/app/modules/module.js | 1 + .../tests/dispatchCallbacksOnUiThreadTests.js | 50 +- .../app/tests/exceptionHandlingTests.js | 491 ++- .../assets/app/tests/extendClassNameTests.js | 74 +- .../assets/app/tests/extendedClassesTests.js | 143 +- .../assets/app/tests/finalFieldsSetTests.js | 40 +- .../tests/inheritanceChainResolutionTest.js | 54 +- .../app/tests/numericConversionTests.js | 517 ++- .../assets/app/tests/propertyAccessTests.js | 73 - .../assets/app/tests/stringConversionTests.js | 176 +- test-app/assets/app/tests/testGC.js | 365 +- .../app/tests/testIfAbleToRunExternalFile.js | 59 +- test-app/assets/app/tests/testWeakRef.js | 296 +- test-app/assets/app/tests/tests.js | 3253 ++++++++--------- .../tests/testsForRuntimeBindingGenerator.js | 89 +- .../assets/app/tests/testsForTypescript.js | 967 +++-- .../assets/app/tests/testsMemoryManagement.js | 58 +- test-app/assets/app/tests/testsWithContext.js | 216 +- 27 files changed, 7075 insertions(+), 3589 deletions(-) create mode 100644 test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/boot.js create mode 100644 test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/jasmine.js create mode 100644 test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/junit_reporter.js create mode 100644 test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/terminal_reporter.js create mode 100644 test-app/assets/app/Infrastructure/Jasmine/jasmine.d.ts create mode 100644 test-app/assets/app/Infrastructure/timers.js delete mode 100644 test-app/assets/app/tests/propertyAccessTests.js diff --git a/test-app/.settings/org.eclipse.jdt.core.prefs b/test-app/.settings/org.eclipse.jdt.core.prefs index 7341ab168..d17b6724d 100644 --- a/test-app/.settings/org.eclipse.jdt.core.prefs +++ b/test-app/.settings/org.eclipse.jdt.core.prefs @@ -1,5 +1,6 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve org.eclipse.jdt.core.compiler.compliance=1.7 diff --git a/test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/boot.js b/test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/boot.js new file mode 100644 index 000000000..81b04095c --- /dev/null +++ b/test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/boot.js @@ -0,0 +1,139 @@ +/** + Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. + + If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. + + The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. + + [jasmine-gem]: http://github.com/pivotal/jasmine-gem + */ + +var jasmineRequire = require('./jasmine'); +var JUnitXmlReporter = require('../jasmine-reporters/junit_reporter').JUnitXmlReporter; +var TerminalReporter = require('../jasmine-reporters/terminal_reporter').TerminalReporter; + +(function() { + /** + * ## Require & Instantiate + * + * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. + */ + var jasmine = jasmineRequire.core(jasmineRequire); + + /** + * Create the Jasmine environment. This is used to run all specs in a project. + */ + var env = jasmine.getEnv(); + + /** + * ## The Global Interface + * + * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. + */ + var jasmineInterface = { + describe: function(description, specDefinitions) { + return env.describe(description, specDefinitions); + }, + + xdescribe: function(description, specDefinitions) { + return env.xdescribe(description, specDefinitions); + }, + + it: function(desc, func) { + return env.it(desc, func); + }, + + xit: function(desc, func) { + return env.xit(desc, func); + }, + + beforeEach: function(beforeEachFunction) { + return env.beforeEach(beforeEachFunction); + }, + + afterEach: function(afterEachFunction) { + return env.afterEach(afterEachFunction); + }, + + expect: function(actual) { + return env.expect(actual); + }, + + pending: function() { + return env.pending(); + }, + + spyOn: function(obj, methodName) { + return env.spyOn(obj, methodName); + }, + + jsApiReporter: new jasmine.JsApiReporter({ + timer: new jasmine.Timer() + }), + + execute: function() { + return env.execute(); + }, + + jasmine: jasmine + }; + + /** + * Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. + */ + if (typeof window == "undefined" && typeof global == "object") { + extend(global, jasmineInterface); + } else { + extend(window, jasmineInterface); + } + + /** + * Expose the interface for adding custom equality testers. + */ + jasmine.addCustomEqualityTester = function(tester) { + env.addCustomEqualityTester(tester); + }; + + /** + * Expose the interface for adding custom expectation matchers + */ + jasmine.addMatchers = function(matchers) { + return env.addMatchers(matchers); + }; + + /** + * Expose the mock interface for the JavaScript timeout functions + */ + jasmine.clock = function() { + return env.clock; + }; + + /** + * ## Runner Parameters + */ + + env.catchExceptions(true); + + /** + * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. + */ + env.addReporter(jasmineInterface.jsApiReporter); +// + env.addReporter(new TerminalReporter({ + verbosity: 5 + })); + + env.addReporter(new JUnitXmlReporter()); + + env.specFilter = function(spec) { + return true; + }; + + /** + * Helper function for readability above. + */ + function extend(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; + } +}()); diff --git a/test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/jasmine.js b/test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/jasmine.js new file mode 100644 index 000000000..b590ef6ef --- /dev/null +++ b/test-app/assets/app/Infrastructure/Jasmine/jasmine-2.0.1/jasmine.js @@ -0,0 +1,2517 @@ +/* +Copyright (c) 2008-2014 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +function getJasmineRequireObj() { + if (typeof module !== 'undefined' && module.exports) { + return exports; + } else { + window.jasmineRequire = window.jasmineRequire || {}; + return window.jasmineRequire; + } +} + +getJasmineRequireObj().core = function(jRequire) { + var j$ = {}; + + jRequire.base(j$); + j$.util = jRequire.util(); + j$.Any = jRequire.Any(); + j$.CallTracker = jRequire.CallTracker(); + j$.MockDate = jRequire.MockDate(); + j$.Clock = jRequire.Clock(); + j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(); + j$.Env = jRequire.Env(j$); + j$.ExceptionFormatter = jRequire.ExceptionFormatter(); + j$.Expectation = jRequire.Expectation(); + j$.buildExpectationResult = jRequire.buildExpectationResult(); + j$.JsApiReporter = jRequire.JsApiReporter(); + j$.matchersUtil = jRequire.matchersUtil(j$); + j$.ObjectContaining = jRequire.ObjectContaining(j$); + j$.pp = jRequire.pp(j$); + j$.QueueRunner = jRequire.QueueRunner(j$); + j$.ReportDispatcher = jRequire.ReportDispatcher(); + j$.Spec = jRequire.Spec(j$); + j$.SpyStrategy = jRequire.SpyStrategy(); + j$.Suite = jRequire.Suite(); + j$.Timer = jRequire.Timer(); + j$.version = jRequire.version(); + + j$.matchers = jRequire.requireMatchers(jRequire, j$); + + return j$; +}; + +getJasmineRequireObj().requireMatchers = function(jRequire, j$) { + var availableMatchers = [ + 'toBe', + 'toBeCloseTo', + 'toBeDefined', + 'toBeFalsy', + 'toBeGreaterThan', + 'toBeLessThan', + 'toBeNaN', + 'toBeNull', + 'toBeTruthy', + 'toBeUndefined', + 'toContain', + 'toEqual', + 'toHaveBeenCalled', + 'toHaveBeenCalledWith', + 'toMatch', + 'toThrow', + 'toThrowError' + ], + matchers = {}; + + for (var i = 0; i < availableMatchers.length; i++) { + var name = availableMatchers[i]; + matchers[name] = jRequire[name](j$); + } + + return matchers; +}; + +getJasmineRequireObj().base = (function (jasmineGlobal) { + if (typeof module !== 'undefined' && module.exports) { + jasmineGlobal = global; + } + + return function(j$) { + j$.unimplementedMethod_ = function() { + throw new Error('unimplemented method'); + }; + + j$.MAX_PRETTY_PRINT_DEPTH = 40; + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 100; + j$.DEFAULT_TIMEOUT_INTERVAL = 5000; + + j$.getGlobal = function() { + return jasmineGlobal; + }; + + j$.getEnv = function(options) { + var env = j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options); + //jasmine. singletons in here (setTimeout blah blah). + return env; + }; + + j$.isArray_ = function(value) { + return j$.isA_('Array', value); + }; + + j$.isString_ = function(value) { + return j$.isA_('String', value); + }; + + j$.isNumber_ = function(value) { + return j$.isA_('Number', value); + }; + + j$.isA_ = function(typeName, value) { + return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; + }; + + j$.isDomNode = function(obj) { + return obj.nodeType > 0; + }; + + j$.any = function(clazz) { + return new j$.Any(clazz); + }; + + j$.objectContaining = function(sample) { + return new j$.ObjectContaining(sample); + }; + + j$.createSpy = function(name, originalFn) { + + var spyStrategy = new j$.SpyStrategy({ + name: name, + fn: originalFn, + getSpy: function() { return spy; } + }), + callTracker = new j$.CallTracker(), + spy = function() { + callTracker.track({ + object: this, + args: Array.prototype.slice.apply(arguments) + }); + return spyStrategy.exec.apply(this, arguments); + }; + + for (var prop in originalFn) { + if (prop === 'and' || prop === 'calls') { + throw new Error('Jasmine spies would overwrite the \'and\' and \'calls\' properties on the object being spied upon'); + } + + spy[prop] = originalFn[prop]; + } + + spy.and = spyStrategy; + spy.calls = callTracker; + + return spy; + }; + + j$.isSpy = function(putativeSpy) { + if (!putativeSpy) { + return false; + } + return putativeSpy.and instanceof j$.SpyStrategy && + putativeSpy.calls instanceof j$.CallTracker; + }; + + j$.createSpyObj = function(baseName, methodNames) { + if (!j$.isArray_(methodNames) || methodNames.length === 0) { + throw 'createSpyObj requires a non-empty array of method names to create spies for'; + } + var obj = {}; + for (var i = 0; i < methodNames.length; i++) { + obj[methodNames[i]] = j$.createSpy(baseName + '.' + methodNames[i]); + } + return obj; + }; + }; +})(this); + +getJasmineRequireObj().util = function() { + + var util = {}; + + util.inherit = function(childClass, parentClass) { + var Subclass = function() { + }; + Subclass.prototype = parentClass.prototype; + childClass.prototype = new Subclass(); + }; + + util.htmlEscape = function(str) { + if (!str) { + return str; + } + return str.replace(/&/g, '&') + .replace(//g, '>'); + }; + + util.argsToArray = function(args) { + var arrayOfArgs = []; + for (var i = 0; i < args.length; i++) { + arrayOfArgs.push(args[i]); + } + return arrayOfArgs; + }; + + util.isUndefined = function(obj) { + return obj === void 0; + }; + + util.arrayContains = function(array, search) { + var i = array.length; + while (i--) { + if (array[i] == search) { + return true; + } + } + return false; + }; + + return util; +}; + +getJasmineRequireObj().Spec = function(j$) { + function Spec(attrs) { + this.expectationFactory = attrs.expectationFactory; + this.resultCallback = attrs.resultCallback || function() {}; + this.id = attrs.id; + this.description = attrs.description || ''; + this.fn = attrs.fn; + this.beforeFns = attrs.beforeFns || function() { return []; }; + this.afterFns = attrs.afterFns || function() { return []; }; + this.onStart = attrs.onStart || function() {}; + this.exceptionFormatter = attrs.exceptionFormatter || function() {}; + this.getSpecName = attrs.getSpecName || function() { return ''; }; + this.expectationResultFactory = attrs.expectationResultFactory || function() { }; + this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; + this.catchingExceptions = attrs.catchingExceptions || function() { return true; }; + + if (!this.fn) { + this.pend(); + } + + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + passedExpectations: [] + }; + } + + Spec.prototype.addExpectationResult = function(passed, data) { + var expectationResult = this.expectationResultFactory(data); + if (passed) { + this.result.passedExpectations.push(expectationResult); + } else { + this.result.failedExpectations.push(expectationResult); + } + }; + + Spec.prototype.expect = function(actual) { + return this.expectationFactory(actual, this); + }; + + Spec.prototype.execute = function(onComplete) { + var self = this; + + this.onStart(this); + + if (this.markedPending || this.disabled) { + complete(); + return; + } + + var allFns = this.beforeFns().concat(this.fn).concat(this.afterFns()); + + this.queueRunnerFactory({ + fns: allFns, + onException: onException, + onComplete: complete, + enforceTimeout: function() { return true; } + }); + + function onException(e) { + if (Spec.isPendingSpecException(e)) { + self.pend(); + return; + } + + self.addExpectationResult(false, { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: e + }); + } + + function complete() { + self.result.status = self.status(); + self.resultCallback(self.result); + + if (onComplete) { + onComplete(); + } + } + }; + + Spec.prototype.disable = function() { + this.disabled = true; + }; + + Spec.prototype.pend = function() { + this.markedPending = true; + }; + + Spec.prototype.status = function() { + if (this.disabled) { + return 'disabled'; + } + + if (this.markedPending) { + return 'pending'; + } + + if (this.result.failedExpectations.length > 0) { + return 'failed'; + } else { + return 'passed'; + } + }; + + Spec.prototype.getFullName = function() { + return this.getSpecName(this); + }; + + Spec.pendingSpecExceptionMessage = '=> marked Pending'; + + Spec.isPendingSpecException = function(e) { + return !!(e && e.toString && e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1); + }; + + return Spec; +}; + +if (typeof window == void 0 && typeof exports == 'object') { + exports.Spec = jasmineRequire.Spec; +} + +getJasmineRequireObj().Env = function(j$) { + function Env(options) { + options = options || {}; + + var self = this; + var global = options.global || j$.getGlobal(); + + var totalSpecsDefined = 0; + + var catchExceptions = true; + + var realSetTimeout = j$.getGlobal().setTimeout; + var realClearTimeout = j$.getGlobal().clearTimeout; + + this.clock = new j$.Clock(global, new j$.DelayedFunctionScheduler(), new j$.MockDate(global)); + + var runnableLookupTable = {}; + + var spies = []; + + var currentSpec = null; + var currentSuite = null; + + var reporter = new j$.ReportDispatcher([ + 'jasmineStarted', + 'jasmineDone', + 'suiteStarted', + 'suiteDone', + 'specStarted', + 'specDone' + ]); + + this.specFilter = function() { + return true; + }; + + var equalityTesters = []; + + var customEqualityTesters = []; + this.addCustomEqualityTester = function(tester) { + customEqualityTesters.push(tester); + }; + + j$.Expectation.addCoreMatchers(j$.matchers); + + var nextSpecId = 0; + var getNextSpecId = function() { + return 'spec' + nextSpecId++; + }; + + var nextSuiteId = 0; + var getNextSuiteId = function() { + return 'suite' + nextSuiteId++; + }; + + var expectationFactory = function(actual, spec) { + return j$.Expectation.Factory({ + util: j$.matchersUtil, + customEqualityTesters: customEqualityTesters, + actual: actual, + addExpectationResult: addExpectationResult + }); + + function addExpectationResult(passed, result) { + return spec.addExpectationResult(passed, result); + } + }; + + var specStarted = function(spec) { + currentSpec = spec; + reporter.specStarted(spec.result); + }; + + var beforeFns = function(suite) { + return function() { + var befores = []; + while(suite) { + befores = befores.concat(suite.beforeFns); + suite = suite.parentSuite; + } + return befores.reverse(); + }; + }; + + var afterFns = function(suite) { + return function() { + var afters = []; + while(suite) { + afters = afters.concat(suite.afterFns); + suite = suite.parentSuite; + } + return afters; + }; + }; + + var getSpecName = function(spec, suite) { + return suite.getFullName() + ' ' + spec.description; + }; + + // TODO: we may just be able to pass in the fn instead of wrapping here + var buildExpectationResult = j$.buildExpectationResult, + exceptionFormatter = new j$.ExceptionFormatter(), + expectationResultFactory = function(attrs) { + attrs.messageFormatter = exceptionFormatter.message; + attrs.stackFormatter = exceptionFormatter.stack; + + return buildExpectationResult(attrs); + }; + + // TODO: fix this naming, and here's where the value comes in + this.catchExceptions = function(value) { + catchExceptions = !!value; + return catchExceptions; + }; + + this.catchingExceptions = function() { + return catchExceptions; + }; + + var maximumSpecCallbackDepth = 20; + var currentSpecCallbackDepth = 0; + + function clearStack(fn) { + currentSpecCallbackDepth++; + if (currentSpecCallbackDepth >= maximumSpecCallbackDepth) { + currentSpecCallbackDepth = 0; + realSetTimeout(fn, 0); + } else { + fn(); + } + } + + var catchException = function(e) { + return j$.Spec.isPendingSpecException(e) || catchExceptions; + }; + + var queueRunnerFactory = function(options) { + options.catchException = catchException; + options.clearStack = options.clearStack || clearStack; + options.timer = {setTimeout: setTimeout, clearTimeout: clearTimeout}; + + new j$.QueueRunner(options).execute(); + }; + + var topSuite = new j$.Suite({ + env: this, + id: getNextSuiteId(), + description: 'Jasmine__TopLevel__Suite', + queueRunner: queueRunnerFactory, + resultCallback: function() {} // TODO - hook this up + }); + runnableLookupTable[topSuite.id] = topSuite; + currentSuite = topSuite; + + this.topSuite = function() { + return topSuite; + }; + + this.execute = function(runnablesToRun) { + runnablesToRun = runnablesToRun || [topSuite.id]; + + var allFns = []; + for(var i = 0; i < runnablesToRun.length; i++) { + var runnable = runnableLookupTable[runnablesToRun[i]]; + allFns.push((function(runnable) { return function(done) { runnable.execute(done); }; })(runnable)); + } + + reporter.jasmineStarted({ + totalSpecsDefined: totalSpecsDefined + }); + + queueRunnerFactory({fns: allFns, onComplete: reporter.jasmineDone}); + }; + + this.addReporter = function(reporterToAdd) { + reporter.addReporter(reporterToAdd); + }; + + this.addMatchers = function(matchersToAdd) { + j$.Expectation.addMatchers(matchersToAdd); + }; + + this.spyOn = function(obj, methodName) { + if (j$.util.isUndefined(obj)) { + throw new Error('spyOn could not find an object to spy upon for ' + methodName + '()'); + } + + if (j$.util.isUndefined(obj[methodName])) { + throw new Error(methodName + '() method does not exist'); + } + + if (obj[methodName] && j$.isSpy(obj[methodName])) { + //TODO?: should this return the current spy? Downside: may cause user confusion about spy state + throw new Error(methodName + ' has already been spied upon'); + } + + var spy = j$.createSpy(methodName, obj[methodName]); + + spies.push({ + spy: spy, + baseObj: obj, + methodName: methodName, + originalValue: obj[methodName] + }); + + obj[methodName] = spy; + + return spy; + }; + + var suiteFactory = function(description) { + var suite = new j$.Suite({ + env: self, + id: getNextSuiteId(), + description: description, + parentSuite: currentSuite, + queueRunner: queueRunnerFactory, + onStart: suiteStarted, + resultCallback: function(attrs) { + reporter.suiteDone(attrs); + } + }); + + runnableLookupTable[suite.id] = suite; + return suite; + }; + + this.describe = function(description, specDefinitions) { + var suite = suiteFactory(description); + + var parentSuite = currentSuite; + parentSuite.addChild(suite); + currentSuite = suite; + + var declarationError = null; + try { + specDefinitions.call(suite); + } catch (e) { + declarationError = e; + } + + if (declarationError) { + this.it('encountered a declaration exception', function() { + throw declarationError; + }); + } + + currentSuite = parentSuite; + + return suite; + }; + + this.xdescribe = function(description, specDefinitions) { + var suite = this.describe(description, specDefinitions); + suite.disable(); + return suite; + }; + + var specFactory = function(description, fn, suite) { + totalSpecsDefined++; + + var spec = new j$.Spec({ + id: getNextSpecId(), + beforeFns: beforeFns(suite), + afterFns: afterFns(suite), + expectationFactory: expectationFactory, + exceptionFormatter: exceptionFormatter, + resultCallback: specResultCallback, + getSpecName: function(spec) { + return getSpecName(spec, suite); + }, + onStart: specStarted, + description: description, + expectationResultFactory: expectationResultFactory, + queueRunnerFactory: queueRunnerFactory, + fn: fn + }); + + runnableLookupTable[spec.id] = spec; + + if (!self.specFilter(spec)) { + spec.disable(); + } + + return spec; + + function removeAllSpies() { + for (var i = 0; i < spies.length; i++) { + var spyEntry = spies[i]; + spyEntry.baseObj[spyEntry.methodName] = spyEntry.originalValue; + } + spies = []; + } + + function specResultCallback(result) { + removeAllSpies(); + j$.Expectation.resetMatchers(); + customEqualityTesters = []; + currentSpec = null; + reporter.specDone(result); + } + }; + + var suiteStarted = function(suite) { + reporter.suiteStarted(suite.result); + }; + + this.it = function(description, fn) { + var spec = specFactory(description, fn, currentSuite); + currentSuite.addChild(spec); + return spec; + }; + + this.xit = function(description, fn) { + var spec = this.it(description, fn); + spec.pend(); + return spec; + }; + + this.expect = function(actual) { + if (!currentSpec) { + throw new Error('\'expect\' was used when there was no current spec, this could be because an asynchronous test timed out'); + } + + return currentSpec.expect(actual); + }; + + this.beforeEach = function(beforeEachFunction) { + currentSuite.beforeEach(beforeEachFunction); + }; + + this.afterEach = function(afterEachFunction) { + currentSuite.afterEach(afterEachFunction); + }; + + this.pending = function() { + throw j$.Spec.pendingSpecExceptionMessage; + }; + } + + return Env; +}; + +getJasmineRequireObj().JsApiReporter = function() { + + var noopTimer = { + start: function(){}, + elapsed: function(){ return 0; } + }; + + function JsApiReporter(options) { + var timer = options.timer || noopTimer, + status = 'loaded'; + + this.started = false; + this.finished = false; + + this.jasmineStarted = function() { + this.started = true; + status = 'started'; + timer.start(); + }; + + var executionTime; + + this.jasmineDone = function() { + this.finished = true; + executionTime = timer.elapsed(); + status = 'done'; + }; + + this.status = function() { + return status; + }; + + var suites = {}; + + this.suiteStarted = function(result) { + storeSuite(result); + }; + + this.suiteDone = function(result) { + storeSuite(result); + }; + + function storeSuite(result) { + suites[result.id] = result; + } + + this.suites = function() { + return suites; + }; + + var specs = []; + this.specStarted = function(result) { }; + + this.specDone = function(result) { + specs.push(result); + }; + + this.specResults = function(index, length) { + return specs.slice(index, index + length); + }; + + this.specs = function() { + return specs; + }; + + this.executionTime = function() { + return executionTime; + }; + + } + + return JsApiReporter; +}; + +getJasmineRequireObj().Any = function() { + + function Any(expectedObject) { + this.expectedObject = expectedObject; + } + + Any.prototype.jasmineMatches = function(other) { + if (this.expectedObject == String) { + return typeof other == 'string' || other instanceof String; + } + + if (this.expectedObject == Number) { + return typeof other == 'number' || other instanceof Number; + } + + if (this.expectedObject == Function) { + return typeof other == 'function' || other instanceof Function; + } + + if (this.expectedObject == Object) { + return typeof other == 'object'; + } + + if (this.expectedObject == Boolean) { + return typeof other == 'boolean'; + } + + return other instanceof this.expectedObject; + }; + + Any.prototype.jasmineToString = function() { + return ''; + }; + + return Any; +}; + +getJasmineRequireObj().CallTracker = function() { + + function CallTracker() { + var calls = []; + + this.track = function(context) { + calls.push(context); + }; + + this.any = function() { + return !!calls.length; + }; + + this.count = function() { + return calls.length; + }; + + this.argsFor = function(index) { + var call = calls[index]; + return call ? call.args : []; + }; + + this.all = function() { + return calls; + }; + + this.allArgs = function() { + var callArgs = []; + for(var i = 0; i < calls.length; i++){ + callArgs.push(calls[i].args); + } + + return callArgs; + }; + + this.first = function() { + return calls[0]; + }; + + this.mostRecent = function() { + return calls[calls.length - 1]; + }; + + this.reset = function() { + calls = []; + }; + } + + return CallTracker; +}; + +getJasmineRequireObj().Clock = function() { + function Clock(global, delayedFunctionScheduler, mockDate) { + var self = this, + realTimingFunctions = { + setTimeout: global.setTimeout, + clearTimeout: global.clearTimeout, + setInterval: global.setInterval, + clearInterval: global.clearInterval + }, + fakeTimingFunctions = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setInterval: setInterval, + clearInterval: clearInterval + }, + installed = false, + timer; + + + self.install = function() { + replace(global, fakeTimingFunctions); + timer = fakeTimingFunctions; + installed = true; + + return self; + }; + + self.uninstall = function() { + delayedFunctionScheduler.reset(); + mockDate.uninstall(); + replace(global, realTimingFunctions); + + timer = realTimingFunctions; + installed = false; + }; + + self.mockDate = function(initialDate) { + mockDate.install(initialDate); + }; + + self.setTimeout = function(fn, delay, params) { + if (legacyIE()) { + if (arguments.length > 2) { + throw new Error('IE < 9 cannot support extra params to setTimeout without a polyfill'); + } + return timer.setTimeout(fn, delay); + } + return Function.prototype.apply.apply(timer.setTimeout, [global, arguments]); + }; + + self.setInterval = function(fn, delay, params) { + if (legacyIE()) { + if (arguments.length > 2) { + throw new Error('IE < 9 cannot support extra params to setInterval without a polyfill'); + } + return timer.setInterval(fn, delay); + } + return Function.prototype.apply.apply(timer.setInterval, [global, arguments]); + }; + + self.clearTimeout = function(id) { + return Function.prototype.call.apply(timer.clearTimeout, [global, id]); + }; + + self.clearInterval = function(id) { + return Function.prototype.call.apply(timer.clearInterval, [global, id]); + }; + + self.tick = function(millis) { + if (installed) { + mockDate.tick(millis); + delayedFunctionScheduler.tick(millis); + } else { + throw new Error('Mock clock is not installed, use jasmine.clock().install()'); + } + }; + + return self; + + function legacyIE() { + //if these methods are polyfilled, apply will be present + return !(realTimingFunctions.setTimeout || realTimingFunctions.setInterval).apply; + } + + function replace(dest, source) { + for (var prop in source) { + dest[prop] = source[prop]; + } + } + + function setTimeout(fn, delay) { + return delayedFunctionScheduler.scheduleFunction(fn, delay, argSlice(arguments, 2)); + } + + function clearTimeout(id) { + return delayedFunctionScheduler.removeFunctionWithId(id); + } + + function setInterval(fn, interval) { + return delayedFunctionScheduler.scheduleFunction(fn, interval, argSlice(arguments, 2), true); + } + + function clearInterval(id) { + return delayedFunctionScheduler.removeFunctionWithId(id); + } + + function argSlice(argsObj, n) { + return Array.prototype.slice.call(argsObj, n); + } + } + + return Clock; +}; + +getJasmineRequireObj().DelayedFunctionScheduler = function() { + function DelayedFunctionScheduler() { + var self = this; + var scheduledLookup = []; + var scheduledFunctions = {}; + var currentTime = 0; + var delayedFnCount = 0; + + self.tick = function(millis) { + millis = millis || 0; + var endTime = currentTime + millis; + + runScheduledFunctions(endTime); + currentTime = endTime; + }; + + self.scheduleFunction = function(funcToCall, millis, params, recurring, timeoutKey, runAtMillis) { + var f; + if (typeof(funcToCall) === 'string') { + /* jshint evil: true */ + f = function() { return eval(funcToCall); }; + /* jshint evil: false */ + } else { + f = funcToCall; + } + + millis = millis || 0; + timeoutKey = timeoutKey || ++delayedFnCount; + runAtMillis = runAtMillis || (currentTime + millis); + + var funcToSchedule = { + runAtMillis: runAtMillis, + funcToCall: f, + recurring: recurring, + params: params, + timeoutKey: timeoutKey, + millis: millis + }; + + if (runAtMillis in scheduledFunctions) { + scheduledFunctions[runAtMillis].push(funcToSchedule); + } else { + scheduledFunctions[runAtMillis] = [funcToSchedule]; + scheduledLookup.push(runAtMillis); + scheduledLookup.sort(function (a, b) { + return a - b; + }); + } + + return timeoutKey; + }; + + self.removeFunctionWithId = function(timeoutKey) { + for (var runAtMillis in scheduledFunctions) { + var funcs = scheduledFunctions[runAtMillis]; + var i = indexOfFirstToPass(funcs, function (func) { + return func.timeoutKey === timeoutKey; + }); + + if (i > -1) { + if (funcs.length === 1) { + delete scheduledFunctions[runAtMillis]; + deleteFromLookup(runAtMillis); + } else { + funcs.splice(i, 1); + } + + // intervals get rescheduled when executed, so there's never more + // than a single scheduled function with a given timeoutKey + break; + } + } + }; + + self.reset = function() { + currentTime = 0; + scheduledLookup = []; + scheduledFunctions = {}; + delayedFnCount = 0; + }; + + return self; + + function indexOfFirstToPass(array, testFn) { + var index = -1; + + for (var i = 0; i < array.length; ++i) { + if (testFn(array[i])) { + index = i; + break; + } + } + + return index; + } + + function deleteFromLookup(key) { + var value = Number(key); + var i = indexOfFirstToPass(scheduledLookup, function (millis) { + return millis === value; + }); + + if (i > -1) { + scheduledLookup.splice(i, 1); + } + } + + function reschedule(scheduledFn) { + self.scheduleFunction(scheduledFn.funcToCall, + scheduledFn.millis, + scheduledFn.params, + true, + scheduledFn.timeoutKey, + scheduledFn.runAtMillis + scheduledFn.millis); + } + + function runScheduledFunctions(endTime) { + if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { + return; + } + + do { + currentTime = scheduledLookup.shift(); + + var funcsToRun = scheduledFunctions[currentTime]; + delete scheduledFunctions[currentTime]; + + for (var i = 0; i < funcsToRun.length; ++i) { + var funcToRun = funcsToRun[i]; + funcToRun.funcToCall.apply(null, funcToRun.params || []); + + if (funcToRun.recurring) { + reschedule(funcToRun); + } + } + } while (scheduledLookup.length > 0 && + // checking first if we're out of time prevents setTimeout(0) + // scheduled in a funcToRun from forcing an extra iteration + currentTime !== endTime && + scheduledLookup[0] <= endTime); + } + } + + return DelayedFunctionScheduler; +}; + +getJasmineRequireObj().ExceptionFormatter = function() { + function ExceptionFormatter() { + this.message = function(error) { + var message = ''; + + if (error.name && error.message) { + message += error.name + ': ' + error.message; + } else { + message += error.toString() + ' thrown'; + } + + if (error.fileName || error.sourceURL) { + message += ' in ' + (error.fileName || error.sourceURL); + } + + if (error.line || error.lineNumber) { + message += ' (line ' + (error.line || error.lineNumber) + ')'; + } + + return message; + }; + + this.stack = function(error) { + return error ? error.stack : null; + }; + } + + return ExceptionFormatter; +}; + +getJasmineRequireObj().Expectation = function() { + + var matchers = {}; + + function Expectation(options) { + this.util = options.util || { buildFailureMessage: function() {} }; + this.customEqualityTesters = options.customEqualityTesters || []; + this.actual = options.actual; + this.addExpectationResult = options.addExpectationResult || function(){}; + this.isNot = options.isNot; + + for (var matcherName in matchers) { + this[matcherName] = matchers[matcherName]; + } + } + + Expectation.prototype.wrapCompare = function(name, matcherFactory) { + return function() { + var args = Array.prototype.slice.call(arguments, 0), + expected = args.slice(0), + message = ''; + + args.unshift(this.actual); + + var matcher = matcherFactory(this.util, this.customEqualityTesters), + matcherCompare = matcher.compare; + + function defaultNegativeCompare() { + var result = matcher.compare.apply(null, args); + result.pass = !result.pass; + return result; + } + + if (this.isNot) { + matcherCompare = matcher.negativeCompare || defaultNegativeCompare; + } + + var result = matcherCompare.apply(null, args); + + if (!result.pass) { + if (!result.message) { + args.unshift(this.isNot); + args.unshift(name); + message = this.util.buildFailureMessage.apply(null, args); + } else { + if (Object.prototype.toString.apply(result.message) === '[object Function]') { + message = result.message(); + } else { + message = result.message; + } + } + } + + if (expected.length == 1) { + expected = expected[0]; + } + + // TODO: how many of these params are needed? + this.addExpectationResult( + result.pass, + { + matcherName: name, + passed: result.pass, + message: message, + actual: this.actual, + expected: expected // TODO: this may need to be arrayified/sliced + } + ); + }; + }; + + Expectation.addCoreMatchers = function(matchers) { + var prototype = Expectation.prototype; + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = prototype.wrapCompare(matcherName, matcher); + } + }; + + Expectation.addMatchers = function(matchersToAdd) { + for (var name in matchersToAdd) { + var matcher = matchersToAdd[name]; + matchers[name] = Expectation.prototype.wrapCompare(name, matcher); + } + }; + + Expectation.resetMatchers = function() { + for (var name in matchers) { + delete matchers[name]; + } + }; + + Expectation.Factory = function(options) { + options = options || {}; + + var expect = new Expectation(options); + + // TODO: this would be nice as its own Object - NegativeExpectation + // TODO: copy instead of mutate options + options.isNot = true; + expect.not = new Expectation(options); + + return expect; + }; + + return Expectation; +}; + +//TODO: expectation result may make more sense as a presentation of an expectation. +getJasmineRequireObj().buildExpectationResult = function() { + function buildExpectationResult(options) { + var messageFormatter = options.messageFormatter || function() {}, + stackFormatter = options.stackFormatter || function() {}; + + return { + matcherName: options.matcherName, + expected: options.expected, + actual: options.actual, + message: message(), + stack: stack(), + passed: options.passed + }; + + function message() { + if (options.passed) { + return 'Passed.'; + } else if (options.message) { + return options.message; + } else if (options.error) { + return messageFormatter(options.error); + } + return ''; + } + + function stack() { + if (options.passed) { + return ''; + } + + var error = options.error; + if (!error) { + try { + throw new Error(message()); + } catch (e) { + error = e; + } + } + return stackFormatter(error); + } + } + + return buildExpectationResult; +}; + +getJasmineRequireObj().MockDate = function() { + function MockDate(global) { + var self = this; + var currentTime = 0; + + if (!global || !global.Date) { + self.install = function() {}; + self.tick = function() {}; + self.uninstall = function() {}; + return self; + } + + var GlobalDate = global.Date; + + self.install = function(mockDate) { + if (mockDate instanceof GlobalDate) { + currentTime = mockDate.getTime(); + } else { + currentTime = new GlobalDate().getTime(); + } + + global.Date = FakeDate; + }; + + self.tick = function(millis) { + millis = millis || 0; + currentTime = currentTime + millis; + }; + + self.uninstall = function() { + currentTime = 0; + global.Date = GlobalDate; + }; + + createDateProperties(); + + return self; + + function FakeDate() { + if (arguments.length === 0) { + return new GlobalDate(currentTime); + } else { + return new GlobalDate(arguments[0], arguments[1], arguments[2], + arguments[3], arguments[4], arguments[5], arguments[6]); + } + } + + function createDateProperties() { + + FakeDate.now = function() { + if (GlobalDate.now) { + return currentTime; + } else { + throw new Error('Browser does not support Date.now()'); + } + }; + + FakeDate.toSource = GlobalDate.toSource; + FakeDate.toString = GlobalDate.toString; + FakeDate.parse = GlobalDate.parse; + FakeDate.UTC = GlobalDate.UTC; + } + } + + return MockDate; +}; + +getJasmineRequireObj().ObjectContaining = function(j$) { + + function ObjectContaining(sample) { + this.sample = sample; + } + + ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { + if (typeof(this.sample) !== 'object') { throw new Error('You must provide an object to objectContaining, not \''+this.sample+'\'.'); } + + mismatchKeys = mismatchKeys || []; + mismatchValues = mismatchValues || []; + + var hasKey = function(obj, keyName) { + return obj !== null && !j$.util.isUndefined(obj[keyName]); + }; + + for (var property in this.sample) { + if (!hasKey(other, property) && hasKey(this.sample, property)) { + mismatchKeys.push('expected has key \'' + property + '\', but missing from actual.'); + } + else if (!j$.matchersUtil.equals(other[property], this.sample[property])) { + mismatchValues.push('\'' + property + '\' was \'' + (other[property] ? j$.util.htmlEscape(other[property].toString()) : other[property]) + '\' in actual, but was \'' + (this.sample[property] ? j$.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + '\' in expected.'); + } + } + + return (mismatchKeys.length === 0 && mismatchValues.length === 0); + }; + + ObjectContaining.prototype.jasmineToString = function() { + return ''; + }; + + return ObjectContaining; +}; + +getJasmineRequireObj().pp = function(j$) { + + function PrettyPrinter() { + this.ppNestLevel_ = 0; + this.seen = []; + } + + PrettyPrinter.prototype.format = function(value) { + this.ppNestLevel_++; + try { + if (j$.util.isUndefined(value)) { + this.emitScalar('undefined'); + } else if (value === null) { + this.emitScalar('null'); + } else if (value === 0 && 1/value === -Infinity) { + this.emitScalar('-0'); + } else if (value === j$.getGlobal()) { + this.emitScalar(''); + } else if (value.jasmineToString) { + this.emitScalar(value.jasmineToString()); + } else if (typeof value === 'string') { + this.emitString(value); + } else if (j$.isSpy(value)) { + this.emitScalar('spy on ' + value.and.identity()); + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()); + } else if (typeof value === 'function') { + this.emitScalar('Function'); + } else if (typeof value.nodeType === 'number') { + this.emitScalar('HTMLNode'); + } else if (value instanceof Date) { + this.emitScalar('Date(' + value + ')'); + } else if (j$.util.arrayContains(this.seen, value)) { + this.emitScalar(''); + } else if (j$.isArray_(value) || j$.isA_('Object', value)) { + this.seen.push(value); + if (j$.isArray_(value)) { + this.emitArray(value); + } else { + this.emitObject(value); + } + this.seen.pop(); + } else { + this.emitScalar(value.toString()); + } + } finally { + this.ppNestLevel_--; + } + }; + + PrettyPrinter.prototype.iterateObject = function(obj, fn) { + for (var property in obj) { + if (!Object.prototype.hasOwnProperty.call(obj, property)) { continue; } + fn(property, obj.__lookupGetter__ ? (!j$.util.isUndefined(obj.__lookupGetter__(property)) && + obj.__lookupGetter__(property) !== null) : false); + } + }; + + PrettyPrinter.prototype.emitArray = j$.unimplementedMethod_; + PrettyPrinter.prototype.emitObject = j$.unimplementedMethod_; + PrettyPrinter.prototype.emitScalar = j$.unimplementedMethod_; + PrettyPrinter.prototype.emitString = j$.unimplementedMethod_; + + function StringPrettyPrinter() { + PrettyPrinter.call(this); + + this.string = ''; + } + + j$.util.inherit(StringPrettyPrinter, PrettyPrinter); + + StringPrettyPrinter.prototype.emitScalar = function(value) { + this.append(value); + }; + + StringPrettyPrinter.prototype.emitString = function(value) { + this.append('\'' + value + '\''); + }; + + StringPrettyPrinter.prototype.emitArray = function(array) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append('Array'); + return; + } + var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); + this.append('[ '); + for (var i = 0; i < length; i++) { + if (i > 0) { + this.append(', '); + } + this.format(array[i]); + } + if(array.length > length){ + this.append(', ...'); + } + this.append(' ]'); + }; + + StringPrettyPrinter.prototype.emitObject = function(obj) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append('Object'); + return; + } + + var self = this; + this.append('{ '); + var first = true; + + this.iterateObject(obj, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.append(property); + self.append(': '); + if (isGetter) { + self.append(''); + } else { + self.format(obj[property]); + } + }); + + this.append(' }'); + }; + + StringPrettyPrinter.prototype.append = function(value) { + this.string += value; + }; + + return function(value) { + var stringPrettyPrinter = new StringPrettyPrinter(); + stringPrettyPrinter.format(value); + return stringPrettyPrinter.string; + }; +}; + +getJasmineRequireObj().QueueRunner = function(j$) { + + function once(fn) { + var called = false; + return function() { + if (!called) { + called = true; + fn(); + } + }; + } + + function QueueRunner(attrs) { + this.fns = attrs.fns || []; + this.onComplete = attrs.onComplete || function() {}; + this.clearStack = attrs.clearStack || function(fn) {fn();}; + this.onException = attrs.onException || function() {}; + this.catchException = attrs.catchException || function() { return true; }; + this.enforceTimeout = attrs.enforceTimeout || function() { return false; }; + this.userContext = {}; + this.timer = attrs.timeout || {setTimeout: setTimeout, clearTimeout: clearTimeout}; + } + + QueueRunner.prototype.execute = function() { + this.run(this.fns, 0); + }; + + QueueRunner.prototype.run = function(fns, recursiveIndex) { + var length = fns.length, + self = this, + iterativeIndex; + + for(iterativeIndex = recursiveIndex; iterativeIndex < length; iterativeIndex++) { + var fn = fns[iterativeIndex]; + if (fn.length > 0) { + return attemptAsync(fn); + } else { + attemptSync(fn); + } + } + + var runnerDone = iterativeIndex >= length; + + if (runnerDone) { + this.clearStack(this.onComplete); + } + + function attemptSync(fn) { + try { + fn.call(self.userContext); + } catch (e) { + handleException(e); + } + } + + function attemptAsync(fn) { + var clearTimeout = function () { + Function.prototype.apply.apply(self.timer.clearTimeout, [j$.getGlobal(), [timeoutId]]); + }, + next = once(function () { + clearTimeout(timeoutId); + self.run(fns, iterativeIndex + 1); + }), + timeoutId; + + if (self.enforceTimeout()) { + timeoutId = Function.prototype.apply.apply(self.timer.setTimeout, [j$.getGlobal(), [function() { + self.onException(new Error('Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.')); + next(); + }, j$.DEFAULT_TIMEOUT_INTERVAL]]); + } + + try { + fn.call(self.userContext, next); + } catch (e) { + handleException(e); + next(); + } + } + + function handleException(e) { + self.onException(e); + if (!self.catchException(e)) { + //TODO: set a var when we catch an exception and + //use a finally block to close the loop in a nice way.. + throw e; + } + } + }; + + return QueueRunner; +}; + +getJasmineRequireObj().ReportDispatcher = function() { + function ReportDispatcher(methods) { + + var dispatchedMethods = methods || []; + + for (var i = 0; i < dispatchedMethods.length; i++) { + var method = dispatchedMethods[i]; + this[method] = (function(m) { + return function() { + dispatch(m, arguments); + }; + }(method)); + } + + var reporters = []; + + this.addReporter = function(reporter) { + reporters.push(reporter); + }; + + return this; + + function dispatch(method, args) { + for (var i = 0; i < reporters.length; i++) { + var reporter = reporters[i]; + if (reporter[method]) { + reporter[method].apply(reporter, args); + } + } + } + } + + return ReportDispatcher; +}; + + +getJasmineRequireObj().SpyStrategy = function() { + + function SpyStrategy(options) { + options = options || {}; + + var identity = options.name || 'unknown', + originalFn = options.fn || function() {}, + getSpy = options.getSpy || function() {}, + plan = function() {}; + + this.identity = function() { + return identity; + }; + + this.exec = function() { + return plan.apply(this, arguments); + }; + + this.callThrough = function() { + plan = originalFn; + return getSpy(); + }; + + this.returnValue = function(value) { + plan = function() { + return value; + }; + return getSpy(); + }; + + this.throwError = function(something) { + var error = (something instanceof Error) ? something : new Error(something); + plan = function() { + throw error; + }; + return getSpy(); + }; + + this.callFake = function(fn) { + plan = fn; + return getSpy(); + }; + + this.stub = function(fn) { + plan = function() {}; + return getSpy(); + }; + } + + return SpyStrategy; +}; + +getJasmineRequireObj().Suite = function() { + function Suite(attrs) { + this.env = attrs.env; + this.id = attrs.id; + this.parentSuite = attrs.parentSuite; + this.description = attrs.description; + this.onStart = attrs.onStart || function() {}; + this.resultCallback = attrs.resultCallback || function() {}; + this.clearStack = attrs.clearStack || function(fn) {fn();}; + + this.beforeFns = []; + this.afterFns = []; + this.queueRunner = attrs.queueRunner || function() {}; + this.disabled = false; + + this.children = []; + + this.result = { + id: this.id, + status: this.disabled ? 'disabled' : '', + description: this.description, + fullName: this.getFullName() + }; + } + + Suite.prototype.getFullName = function() { + var fullName = this.description; + for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { + if (parentSuite.parentSuite) { + fullName = parentSuite.description + ' ' + fullName; + } + } + return fullName; + }; + + Suite.prototype.disable = function() { + this.disabled = true; + }; + + Suite.prototype.beforeEach = function(fn) { + this.beforeFns.unshift(fn); + }; + + Suite.prototype.afterEach = function(fn) { + this.afterFns.unshift(fn); + }; + + Suite.prototype.addChild = function(child) { + this.children.push(child); + }; + + Suite.prototype.execute = function(onComplete) { + var self = this; + if (this.disabled) { + complete(); + return; + } + + var allFns = []; + + for (var i = 0; i < this.children.length; i++) { + allFns.push(wrapChildAsAsync(this.children[i])); + } + + this.onStart(this); + + this.queueRunner({ + fns: allFns, + onComplete: complete + }); + + function complete() { + self.resultCallback(self.result); + + if (onComplete) { + onComplete(); + } + } + + function wrapChildAsAsync(child) { + return function(done) { child.execute(done); }; + } + }; + + return Suite; +}; + +if (typeof window == void 0 && typeof exports == 'object') { + exports.Suite = jasmineRequire.Suite; +} + +getJasmineRequireObj().Timer = function() { + var defaultNow = (function(Date) { + return function() { return new Date().getTime(); }; + })(Date); + + function Timer(options) { + options = options || {}; + + var now = options.now || defaultNow, + startTime; + + this.start = function() { + startTime = now(); + }; + + this.elapsed = function() { + return now() - startTime; + }; + } + + return Timer; +}; + +getJasmineRequireObj().matchersUtil = function(j$) { + // TODO: what to do about jasmine.pp not being inject? move to JSON.stringify? gut PrettyPrinter? + + return { + equals: function(a, b, customTesters) { + customTesters = customTesters || []; + + return eq(a, b, [], [], customTesters); + }, + + contains: function(haystack, needle, customTesters) { + customTesters = customTesters || []; + + if (Object.prototype.toString.apply(haystack) === '[object Array]') { + for (var i = 0; i < haystack.length; i++) { + if (eq(haystack[i], needle, [], [], customTesters)) { + return true; + } + } + return false; + } + return !!haystack && haystack.indexOf(needle) >= 0; + }, + + buildFailureMessage: function() { + var args = Array.prototype.slice.call(arguments, 0), + matcherName = args[0], + isNot = args[1], + actual = args[2], + expected = args.slice(3), + englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); + + var message = 'Expected ' + + j$.pp(actual) + + (isNot ? ' not ' : ' ') + + englishyPredicate; + + if (expected.length > 0) { + for (var i = 0; i < expected.length; i++) { + if (i > 0) { + message += ','; + } + message += ' ' + j$.pp(expected[i]); + } + } + + return message + '.'; + } + }; + + // Equality function lovingly adapted from isEqual in + // [Underscore](http://underscorejs.org) + function eq(a, b, aStack, bStack, customTesters) { + var result = true; + + for (var i = 0; i < customTesters.length; i++) { + var customTesterResult = customTesters[i](a, b); + if (!j$.util.isUndefined(customTesterResult)) { + return customTesterResult; + } + } + + if (a instanceof j$.Any) { + result = a.jasmineMatches(b); + if (result) { + return true; + } + } + + if (b instanceof j$.Any) { + result = b.jasmineMatches(a); + if (result) { + return true; + } + } + + if (b instanceof j$.ObjectContaining) { + result = b.jasmineMatches(a); + if (result) { + return true; + } + } + + if (a instanceof Error && b instanceof Error) { + return a.message == b.message; + } + + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) { return a !== 0 || 1 / a == 1 / b; } + // A strict comparison is necessary because `null == undefined`. + if (a === null || b === null) { return a === b; } + var className = Object.prototype.toString.call(a); + if (className != Object.prototype.toString.call(b)) { return false; } + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return a == String(b); + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b); + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase; + } + if (typeof a != 'object' || typeof b != 'object') { return false; } + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) { return bStack[length] == b; } + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0; + // Recursively compare objects and arrays. + if (className == '[object Array]') { + // Compare array lengths to determine if a deep comparison is necessary. + size = a.length; + result = size == b.length; + if (result) { + // Deep compare the contents, ignoring non-numeric properties. + while (size--) { + if (!(result = eq(a[size], b[size], aStack, bStack, customTesters))) { break; } + } + } + } else { + // Objects with different constructors are not equivalent, but `Object`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) && + isFunction(bCtor) && (bCtor instanceof bCtor))) { + return false; + } + // Deep compare objects. + for (var key in a) { + if (has(a, key)) { + // Count the expected number of properties. + size++; + // Deep compare each member. + if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break; } + } + } + // Ensure that both objects contain the same number of properties. + if (result) { + for (key in b) { + if (has(b, key) && !(size--)) { break; } + } + result = !size; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + + return result; + + function has(obj, key) { + return obj.hasOwnProperty(key); + } + + function isFunction(obj) { + return typeof obj === 'function'; + } + } +}; + +getJasmineRequireObj().toBe = function() { + function toBe() { + return { + compare: function(actual, expected) { + return { + pass: actual === expected + }; + } + }; + } + + return toBe; +}; + +getJasmineRequireObj().toBeCloseTo = function() { + + function toBeCloseTo() { + return { + compare: function(actual, expected, precision) { + if (precision !== 0) { + precision = precision || 2; + } + + return { + pass: Math.abs(expected - actual) < (Math.pow(10, -precision) / 2) + }; + } + }; + } + + return toBeCloseTo; +}; + +getJasmineRequireObj().toBeDefined = function() { + function toBeDefined() { + return { + compare: function(actual) { + return { + pass: (void 0 !== actual) + }; + } + }; + } + + return toBeDefined; +}; + +getJasmineRequireObj().toBeFalsy = function() { + function toBeFalsy() { + return { + compare: function(actual) { + return { + pass: !!!actual + }; + } + }; + } + + return toBeFalsy; +}; + +getJasmineRequireObj().toBeGreaterThan = function() { + + function toBeGreaterThan() { + return { + compare: function(actual, expected) { + return { + pass: actual > expected + }; + } + }; + } + + return toBeGreaterThan; +}; + + +getJasmineRequireObj().toBeLessThan = function() { + function toBeLessThan() { + return { + + compare: function(actual, expected) { + return { + pass: actual < expected + }; + } + }; + } + + return toBeLessThan; +}; +getJasmineRequireObj().toBeNaN = function(j$) { + + function toBeNaN() { + return { + compare: function(actual) { + var result = { + pass: (actual !== actual) + }; + + if (result.pass) { + result.message = 'Expected actual not to be NaN.'; + } else { + result.message = function() { return 'Expected ' + j$.pp(actual) + ' to be NaN.'; }; + } + + return result; + } + }; + } + + return toBeNaN; +}; + +getJasmineRequireObj().toBeNull = function() { + + function toBeNull() { + return { + compare: function(actual) { + return { + pass: actual === null + }; + } + }; + } + + return toBeNull; +}; + +getJasmineRequireObj().toBeTruthy = function() { + + function toBeTruthy() { + return { + compare: function(actual) { + return { + pass: !!actual + }; + } + }; + } + + return toBeTruthy; +}; + +getJasmineRequireObj().toBeUndefined = function() { + + function toBeUndefined() { + return { + compare: function(actual) { + return { + pass: void 0 === actual + }; + } + }; + } + + return toBeUndefined; +}; + +getJasmineRequireObj().toContain = function() { + function toContain(util, customEqualityTesters) { + customEqualityTesters = customEqualityTesters || []; + + return { + compare: function(actual, expected) { + + return { + pass: util.contains(actual, expected, customEqualityTesters) + }; + } + }; + } + + return toContain; +}; + +getJasmineRequireObj().toEqual = function() { + + function toEqual(util, customEqualityTesters) { + customEqualityTesters = customEqualityTesters || []; + + return { + compare: function(actual, expected) { + var result = { + pass: false + }; + + result.pass = util.equals(actual, expected, customEqualityTesters); + + return result; + } + }; + } + + return toEqual; +}; + +getJasmineRequireObj().toHaveBeenCalled = function(j$) { + + function toHaveBeenCalled() { + return { + compare: function(actual) { + var result = {}; + + if (!j$.isSpy(actual)) { + throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); + } + + if (arguments.length > 1) { + throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); + } + + result.pass = actual.calls.any(); + + result.message = result.pass ? + 'Expected spy ' + actual.and.identity() + ' not to have been called.' : + 'Expected spy ' + actual.and.identity() + ' to have been called.'; + + return result; + } + }; + } + + return toHaveBeenCalled; +}; + +getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { + + function toHaveBeenCalledWith(util, customEqualityTesters) { + return { + compare: function() { + var args = Array.prototype.slice.call(arguments, 0), + actual = args[0], + expectedArgs = args.slice(1), + result = { pass: false }; + + if (!j$.isSpy(actual)) { + throw new Error('Expected a spy, but got ' + j$.pp(actual) + '.'); + } + + if (!actual.calls.any()) { + result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but it was never called.'; }; + return result; + } + + if (util.contains(actual.calls.allArgs(), expectedArgs, customEqualityTesters)) { + result.pass = true; + result.message = function() { return 'Expected spy ' + actual.and.identity() + ' not to have been called with ' + j$.pp(expectedArgs) + ' but it was.'; }; + } else { + result.message = function() { return 'Expected spy ' + actual.and.identity() + ' to have been called with ' + j$.pp(expectedArgs) + ' but actual calls were ' + j$.pp(actual.calls.allArgs()).replace(/^\[ | \]$/g, '') + '.'; }; + } + + return result; + } + }; + } + + return toHaveBeenCalledWith; +}; + +getJasmineRequireObj().toMatch = function() { + + function toMatch() { + return { + compare: function(actual, expected) { + var regexp = new RegExp(expected); + + return { + pass: regexp.test(actual) + }; + } + }; + } + + return toMatch; +}; + +getJasmineRequireObj().toThrow = function(j$) { + + function toThrow(util) { + return { + compare: function(actual, expected) { + var result = { pass: false }, + threw = false, + thrown; + + if (typeof actual != 'function') { + throw new Error('Actual is not a Function'); + } + + try { + actual(); + } catch (e) { + threw = true; + thrown = e; + } + + if (!threw) { + result.message = 'Expected function to throw an exception.'; + return result; + } + + if (arguments.length == 1) { + result.pass = true; + result.message = function() { return 'Expected function not to throw, but it threw ' + j$.pp(thrown) + '.'; }; + + return result; + } + + if (util.equals(thrown, expected)) { + result.pass = true; + result.message = function() { return 'Expected function not to throw ' + j$.pp(expected) + '.'; }; + } else { + result.message = function() { return 'Expected function to throw ' + j$.pp(expected) + ', but it threw ' + j$.pp(thrown) + '.'; }; + } + + return result; + } + }; + } + + return toThrow; +}; + +getJasmineRequireObj().toThrowError = function(j$) { + function toThrowError (util) { + return { + compare: function(actual) { + var threw = false, + pass = {pass: true}, + fail = {pass: false}, + thrown, + errorType, + message, + regexp, + name, + constructorName; + + if (typeof actual != 'function') { + throw new Error('Actual is not a Function'); + } + + extractExpectedParams.apply(null, arguments); + + try { + actual(); + } catch (e) { + threw = true; + thrown = e; + } + + if (!threw) { + fail.message = 'Expected function to throw an Error.'; + return fail; + } + + if (!(thrown instanceof Error)) { + fail.message = function() { return 'Expected function to throw an Error, but it threw ' + j$.pp(thrown) + '.'; }; + return fail; + } + + if (arguments.length == 1) { + pass.message = 'Expected function not to throw an Error, but it threw ' + fnNameFor(thrown) + '.'; + return pass; + } + + if (errorType) { + name = fnNameFor(errorType); + constructorName = fnNameFor(thrown.constructor); + } + + if (errorType && message) { + if (thrown.constructor == errorType && util.equals(thrown.message, message)) { + pass.message = function() { return 'Expected function not to throw ' + name + ' with message ' + j$.pp(message) + '.'; }; + return pass; + } else { + fail.message = function() { return 'Expected function to throw ' + name + ' with message ' + j$.pp(message) + + ', but it threw ' + constructorName + ' with message ' + j$.pp(thrown.message) + '.'; }; + return fail; + } + } + + if (errorType && regexp) { + if (thrown.constructor == errorType && regexp.test(thrown.message)) { + pass.message = function() { return 'Expected function not to throw ' + name + ' with message matching ' + j$.pp(regexp) + '.'; }; + return pass; + } else { + fail.message = function() { return 'Expected function to throw ' + name + ' with message matching ' + j$.pp(regexp) + + ', but it threw ' + constructorName + ' with message ' + j$.pp(thrown.message) + '.'; }; + return fail; + } + } + + if (errorType) { + if (thrown.constructor == errorType) { + pass.message = 'Expected function not to throw ' + name + '.'; + return pass; + } else { + fail.message = 'Expected function to throw ' + name + ', but it threw ' + constructorName + '.'; + return fail; + } + } + + if (message) { + if (thrown.message == message) { + pass.message = function() { return 'Expected function not to throw an exception with message ' + j$.pp(message) + '.'; }; + return pass; + } else { + fail.message = function() { return 'Expected function to throw an exception with message ' + j$.pp(message) + + ', but it threw an exception with message ' + j$.pp(thrown.message) + '.'; }; + return fail; + } + } + + if (regexp) { + if (regexp.test(thrown.message)) { + pass.message = function() { return 'Expected function not to throw an exception with a message matching ' + j$.pp(regexp) + '.'; }; + return pass; + } else { + fail.message = function() { return 'Expected function to throw an exception with a message matching ' + j$.pp(regexp) + + ', but it threw an exception with message ' + j$.pp(thrown.message) + '.'; }; + return fail; + } + } + + function fnNameFor(func) { + return func.name || func.toString().match(/^\s*function\s*(\w*)\s*\(/)[1]; + } + + function extractExpectedParams() { + if (arguments.length == 1) { + return; + } + + if (arguments.length == 2) { + var expected = arguments[1]; + + if (expected instanceof RegExp) { + regexp = expected; + } else if (typeof expected == 'string') { + message = expected; + } else if (checkForAnErrorType(expected)) { + errorType = expected; + } + + if (!(errorType || message || regexp)) { + throw new Error('Expected is not an Error, string, or RegExp.'); + } + } else { + if (checkForAnErrorType(arguments[1])) { + errorType = arguments[1]; + } else { + throw new Error('Expected error type is not an Error.'); + } + + if (arguments[2] instanceof RegExp) { + regexp = arguments[2]; + } else if (typeof arguments[2] == 'string') { + message = arguments[2]; + } else { + throw new Error('Expected error message is not a string or RegExp.'); + } + } + } + + function checkForAnErrorType(type) { + if (typeof type !== 'function') { + return false; + } + + var Surrogate = function() {}; + Surrogate.prototype = type.prototype; + return (new Surrogate()) instanceof Error; + } + } + }; + } + + return toThrowError; +}; + +getJasmineRequireObj().version = function() { + return '2.0.1'; +}; diff --git a/test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/junit_reporter.js b/test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/junit_reporter.js new file mode 100644 index 000000000..0c1ade7b6 --- /dev/null +++ b/test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/junit_reporter.js @@ -0,0 +1,315 @@ +/* global java, __phantom_writeFile */ +(function(global) { + var UNDEFINED, + exportObject; + + if (typeof module !== "undefined" && module.exports) { + exportObject = exports; + } else { + exportObject = global.jasmineReporters = global.jasmineReporters || {}; + } + + function trim(str) { return str.replace(/^\s+/, "" ).replace(/\s+$/, "" ); } + function elapsed(start, end) { return (end - start)/1000; } + function isFailed(obj) { return obj.status === "failed"; } + function isSkipped(obj) { return obj.status === "pending"; } + function pad(n) { return n < 10 ? '0'+n : n; } + function extend(dupe, obj) { // performs a shallow copy of all props of `obj` onto `dupe` + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + dupe[prop] = obj[prop]; + } + } + return dupe; + } + function ISODateString(d) { + return d.getFullYear() + '-' + + pad(d.getMonth()+1) + '-' + + pad(d.getDate()) + 'T' + + pad(d.getHours()) + ':' + + pad(d.getMinutes()) + ':' + + pad(d.getSeconds()); + } + function escapeInvalidXmlChars(str) { + return str.replace(//g, ">") + .replace(/\"/g, """) + .replace(/\'/g, "'") + .replace(/\&/g, "&"); + } + function getQualifiedFilename(path, filename, separator) { + if (path && path.substr(-1) !== separator && filename.substr(0) !== separator) { + path += separator; + } + return path + filename; + } + function log(str) { + __log(str); +// var con = global.console || console; +// if (con && con.log) { +// con.log(str); +// } + } + + + /** + * Generates JUnit XML for the given spec run. There are various options + * to control where the results are written, and the default values are + * set to create as few .xml files as possible. It is possible to save a + * single XML file, or an XML file for each top-level `describe`, or an + * XML file for each `describe` regardless of nesting. + * + * Usage: + * + * jasmine.getEnv().addReporter(new jasmineReporters.JUnitXmlReporter(options); + * + * @param {object} [options] + * @param {string} [savePath] directory to save the files (default: '') + * @param {boolean} [consolidateAll] whether to save all test results in a + * single file (default: true) + * NOTE: if true, {filePrefix} is treated as the full filename (excluding + * extension) + * @param {boolean} [consolidate] whether to save nested describes within the + * same file as their parent (default: true) + * NOTE: true does nothing if consolidateAll is also true. + * NOTE: false also sets consolidateAll to false. + * @param {boolean} [useDotNotation] whether to separate suite names with + * dots instead of spaces, ie "Class.init" not "Class init" (default: true) + * @param {string} [filePrefix] is the string value that is prepended to the + * xml output file (default: junitresults-) + * NOTE: if consolidateAll is true, the default is simply "junitresults" and + * this becomes the actual filename, ie "junitresults.xml" + */ + exportObject.JUnitXmlReporter = function(options) { + var self = this; + self.started = false; + self.finished = false; + // sanitize arguments + options = options || {}; + self.savePath = options.savePath || ''; + self.consolidate = options.consolidate === UNDEFINED ? true : options.consolidate; + self.consolidateAll = self.consolidate !== false && (options.consolidateAll === UNDEFINED ? true : options.consolidateAll); + self.useDotNotation = options.useDotNotation === UNDEFINED ? true : options.useDotNotation; + self.filePrefix = options.filePrefix || (self.consolidateAll ? 'junitresults' : 'junitresults-'); + + var suites = [], + currentSuite = null, + totalSpecsExecuted = 0, + totalSpecsDefined; + + var __suites = {}, __specs = {}; + function getSuite(suite) { + __suites[suite.id] = extend(__suites[suite.id] || {}, suite); + return __suites[suite.id]; + } + function getSpec(spec) { + __specs[spec.id] = extend(__specs[spec.id] || {}, spec); + return __specs[spec.id]; + } + + self.jasmineStarted = function(summary) { + totalSpecsDefined = summary && summary.totalSpecsDefined || NaN; + exportObject.startTime = new Date(); + self.started = true; + }; + self.suiteStarted = function(suite) { + suite = getSuite(suite); + suite._startTime = new Date(); + suite._specs = []; + suite._suites = []; + suite._failures = 0; + suite._skipped = 0; + suite._parent = currentSuite; + if (!currentSuite) { + suites.push(suite); + } else { + currentSuite._suites.push(suite); + } + currentSuite = suite; + }; + self.specStarted = function(spec) { + spec = getSpec(spec); + spec._startTime = new Date(); + spec._suite = currentSuite; + currentSuite._specs.push(spec); + }; + self.specDone = function(spec) { + spec = getSpec(spec); + spec._endTime = new Date(); + if (isSkipped(spec)) { spec._suite._skipped++; } + if (isFailed(spec)) { spec._suite._failures++; } + totalSpecsExecuted++; + }; + self.suiteDone = function(suite) { + suite = getSuite(suite); + // disabled suite (xdescribe) -- suiteStarted was never called + if (suite._parent === UNDEFINED) { + self.suiteStarted(suite); + suite._disabled = true; + } + suite._endTime = new Date(); + currentSuite = suite._parent; + }; + self.jasmineDone = function() { + var output = ''; + for (var i = 0; i < suites.length; i++) { + output += self.getOrWriteNestedOutput(suites[i]); + } + // if we have anything to write here, write out the consolidated file + if (output) { + wrapOutputAndWriteFile(self.filePrefix, output); + } + //log("Specs skipped but not reported (entire suite skipped)", totalSpecsDefined - totalSpecsExecuted); + + self.finished = true; + // this is so phantomjs-testrunner.js can tell if we're done executing + exportObject.endTime = new Date(); + }; + + self.getOrWriteNestedOutput = function(suite) { + var output = suiteAsXml(suite); + + for (var i = 0; i < suite._suites.length; i++) { + output += self.getOrWriteNestedOutput(suite._suites[i]); + } + if (self.consolidateAll || self.consolidate && suite._parent) { + return output; + } else { + // if we aren't supposed to consolidate output, just write it now + wrapOutputAndWriteFile(generateFilename(suite), output); + return ''; + } + }; + + self.writeFile = function(filename, text) { + var errors = []; + var path = self.savePath; + + function phantomWrite(path, filename, text) { + // turn filename into a qualified path + filename = getQualifiedFilename(path, filename, window.fs_path_separator); + // write via a method injected by phantomjs-testrunner.js + __phantom_writeFile(filename, text); + } + + function nodeWrite(path, filename, text) { + var fs = require("fs"); + var nodejs_path = require("path"); + require("mkdirp").sync(path); // make sure the path exists + var filepath = nodejs_path.join(path, filename); + var xmlfile = fs.openSync(filepath, "w"); + fs.writeSync(xmlfile, text, 0); + fs.closeSync(xmlfile); + return; + } + + // Attempt writing with each possible environment. + // Track errors in case no write succeeds + try { + phantomWrite(path, filename, text); + return; + } catch (e) { errors.push(' PhantomJs attempt: ' + e.message); } + try { + nodeWrite(path, filename, text); + return; + } catch (f) { errors.push(' NodeJS attempt: ' + f.message); } + try { + __JUnitSaveResults(text); + return; + } catch (f) { errors.push(' tns-android attempt: ' + f.message); } + + // If made it here, no write succeeded. Let user know. + log("Warning: writing junit report failed for '" + path + "', '" + + filename + "'. Reasons:\n" + + errors.join("\n") + ); + }; + + /******** Helper functions with closure access for simplicity ********/ + function generateFilename(suite) { + return self.filePrefix + getFullyQualifiedSuiteName(suite, true) + '.xml'; + } + + function getFullyQualifiedSuiteName(suite, isFilename) { + var fullName; + if (self.useDotNotation || isFilename) { + fullName = suite.description; + for (var parent = suite._parent; parent; parent = parent._parent) { + fullName = parent.description + '.' + fullName; + } + } else { + fullName = suite.fullName; + } + + // Either remove or escape invalid XML characters + if (isFilename) { + var fileName = "", + rFileChars = /[\w\.]/, + chr; + while (fullName.length) { + chr = fullName[0]; + fullName = fullName.substr(1); + if (rFileChars.test(chr)) { + fileName += chr; + } + } + return fileName; + } else { + var finalName = escapeInvalidXmlChars(fullName); + return finalName; + } + } + + function suiteAsXml(suite) { + + var fullyQualifiedSuiteName = getFullyQualifiedSuiteName(suite); + var xml = '\n '; + xml += '\n '; + } + } + xml += '\n '; + return xml; + } + + // To remove complexity and be more DRY about the silly preamble and element + var prefix = ''; + prefix += '\n'; + var suffix = '\n'; + function wrapOutputAndWriteFile(filename, text) { + if (filename.substr(-4) !== '.xml') { filename += '.xml'; } + self.writeFile(filename, (prefix + text + suffix)); + } + }; +})(this); diff --git a/test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/terminal_reporter.js b/test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/terminal_reporter.js new file mode 100644 index 000000000..4b8472157 --- /dev/null +++ b/test-app/assets/app/Infrastructure/Jasmine/jasmine-reporters/terminal_reporter.js @@ -0,0 +1,222 @@ +(function(global) { + var UNDEFINED, + exportObject; + + if (typeof module !== "undefined" && module.exports) { + exportObject = exports; + } else { + exportObject = global.jasmineReporters = global.jasmineReporters || {}; + } + + function elapsed(start, end) { return (end - start)/1000; } + function isFailed(obj) { return obj.status === "failed"; } + function isSkipped(obj) { return obj.status === "pending"; } + function extend(dupe, obj) { // performs a shallow copy of all props of `obj` onto `dupe` + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + dupe[prop] = obj[prop]; + } + } + return dupe; + } + function log(str) { + __log(str); +// var con = global.console || console; +// if (con && con.log && str) { +// con.log(str); +// } + } + + + /** + * Basic reporter that outputs spec results to the terminal. + * Use this reporter in your build pipeline. + * + * Usage: + * + * jasmine.getEnv().addReporter(new jasmineReporters.TerminalReporter(options); + * + * @param {object} [options] + * @param {number} [options.verbosity] meaningful values are 0 through 3; anything + * greater than 3 is treated as 3 (default: 2) + * @param {boolean} [options.color] print in color or not (default: true) + */ + var DEFAULT_VERBOSITY = 2, + ATTRIBUTES_TO_ANSI = { + "off": 0, + "bold": 1, + "red": 31, + "green": 32 + }; + + exportObject.TerminalReporter = function(options) { + var self = this; + self.started = false; + self.finished = false; + + // sanitize arguments + options = options || {}; + self.verbosity = typeof options.verbosity === "number" ? options.verbosity : DEFAULT_VERBOSITY; + self.color = options.color; + + var indent_string = ' ', + startTime, + suites = [], + currentSuite = null, + totalSpecsExecuted = 0, + totalSpecsSkipped = 0, + totalSpecsFailed = 0, + totalSpecsDefined; + + var __suites = {}, __specs = {}; + function getSuite(suite) { + __suites[suite.id] = extend(__suites[suite.id] || {}, suite); + return __suites[suite.id]; + } + function getSpec(spec) { + __specs[spec.id] = extend(__specs[spec.id] || {}, spec); + return __specs[spec.id]; + } + + self.jasmineStarted = function(summary) { + totalSpecsDefined = summary && summary.totalSpecsDefined || NaN; + startTime = exportObject.startTime = new Date(); + self.started = true; + }; + self.suiteStarted = function(suite) { + suite = getSuite(suite); + suite._specs = 0; + suite._nestedSpecs = 0; + suite._failures = 0; + suite._nestedFailures = 0; + suite._skipped = 0; + suite._nestedSkipped = 0; + suite._depth = currentSuite ? currentSuite._depth+1 : 1; + suite._parent = currentSuite; + currentSuite = suite; + if (self.verbosity > 2) { + log(indentWithLevel(suite._depth, inColor(suite.description, "bold"))); + } + }; + self.specStarted = function(spec) { + spec = getSpec(spec); + spec._suite = currentSuite; + spec._depth = currentSuite._depth+1; + currentSuite._specs++; + if (self.verbosity > 2) { + log(indentWithLevel(spec._depth, spec.description + ' ...')); + } + }; + self.specDone = function(spec) { + spec = getSpec(spec); + var failed = false, + skipped = false, + color = 'green', + resultText = ''; + if (isSkipped(spec)) { + skipped = true; + color = ''; + spec._suite._skipped++; + totalSpecsSkipped++; + } + if (isFailed(spec)) { + failed = true; + color = 'red'; + spec._suite._failures++; + totalSpecsFailed++; + } + totalSpecsExecuted++; + + if (self.verbosity === 2) { + resultText = failed ? 'F' : skipped ? 'S' : ''; + } else if (self.verbosity > 2) { + resultText = ' ' + (failed ? 'Failed' : skipped ? 'Skipped' : 'Passed'); + } + log(inColor(resultText, color)); + + if (failed) { + if (self.verbosity === 1) { + log(spec.fullName); + } else if (self.verbosity === 2) { + log(' '); + log(indentWithLevel(spec._depth, spec.fullName)); + } + + for (var i = 0, failure; i < spec.failedExpectations.length; i++) { + log(inColor(indentWithLevel(spec._depth, indent_string + spec.failedExpectations[i].message), color)); + } + } + }; + self.suiteDone = function(suite) { + suite = getSuite(suite); + // disabled suite (xdescribe) -- suiteStarted was never called + if (suite._parent === UNDEFINED) { + self.suiteStarted(suite); + suite._disabled = true; + } + if (suite._parent) { + suite._parent._specs += suite._specs + suite._nestedSpecs; + suite._parent._failures += suite._failures + suite._nestedFailures; + suite._parent._skipped += suite._skipped + suite._nestedSkipped; + } + currentSuite = suite._parent; + if (self.verbosity < 3) { + return; + } + + var total = suite._specs + suite._nestedSpecs, + failed = suite._failures + suite._nestedFailures, + skipped = suite._skipped + suite._nestedSkipped, + passed = total - failed - skipped, + color = failed ? 'red+bold' : 'green+bold', + str = passed + ' of ' + total + ' passed (' + skipped + ' skipped)'; + log(indentWithLevel(suite._depth, inColor(str+'.', color))); + }; + self.jasmineDone = function() { + var now = new Date(), + dur = elapsed(startTime, now), + total = totalSpecsDefined || totalSpecsExecuted, + disabled = total - totalSpecsExecuted, + skipped = totalSpecsSkipped, + spec_str = total + (total === 1 ? " spec, " : " specs, "), + fail_str = totalSpecsFailed + (totalSpecsFailed === 1 ? " failure, " : " failures, "), + skip_str = skipped + " skipped, ", + disabled_str = disabled + " disabled in ", + summary_str = spec_str + fail_str + skip_str + disabled_str + dur + "s.", + result_str = (totalSpecsFailed && "FAILURE: " || "SUCCESS: ") + summary_str, + result_color = totalSpecsFailed && "red+bold" || "green+bold"; + + if (self.verbosity === 2) { + log(''); + } + + if (self.verbosity > 0) { + log(inColor(result_str, result_color)); + } + //log("Specs skipped but not reported (entire suite skipped)", totalSpecsDefined - totalSpecsExecuted); + + self.finished = true; + // this is so phantomjs-testrunner.js can tell if we're done executing + exportObject.endTime = now; + }; + function indentWithLevel(level, string) { + return new Array(level).join(indent_string) + string; + } + function inColor(string, color) { + var color_attributes = color && color.split("+"), + ansi_string = "", + i, attr; + + if (!self.color || !color_attributes) { + return string; + } + + for(i = 0; i < color_attributes.length; i++) { + ansi_string += "\033[" + ATTRIBUTES_TO_ANSI[color_attributes[i]] + "m"; + } + ansi_string += string + "\033[" + ATTRIBUTES_TO_ANSI["off"] + "m"; + + return ansi_string; + } + }; +})(this); diff --git a/test-app/assets/app/Infrastructure/Jasmine/jasmine.d.ts b/test-app/assets/app/Infrastructure/Jasmine/jasmine.d.ts new file mode 100644 index 000000000..7ccfa9594 --- /dev/null +++ b/test-app/assets/app/Infrastructure/Jasmine/jasmine.d.ts @@ -0,0 +1,434 @@ +// Type definitions for Jasmine 2.0 +// Project: http://pivotal.github.com/jasmine/ +// Definitions by: Boris Yankov , Theodore Brown +// Definitions: https://github.com/borisyankov/DefinitelyTyped + + +// For ddescribe / iit use : https://github.com/borisyankov/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts + +declare function describe(description: string, specDefinitions: () => void): void; +// declare function ddescribe(description: string, specDefinitions: () => void): void; Not a part of jasmine. Angular team adds these +declare function xdescribe(description: string, specDefinitions: () => void): void; + +declare function it(expectation: string, assertion?: () => void): void; +declare function it(expectation: string, assertion?: (done: () => void) => void): void; +// declare function iit(expectation: string, assertion?: () => void): void; Not a part of jasmine. Angular team adds these +// declare function iit(expectation: string, assertion?: (done: () => void) => void): void; Not a part of jasmine. Angular team adds these +declare function xit(expectation: string, assertion?: () => void): void; +declare function xit(expectation: string, assertion?: (done: () => void) => void): void; + +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(): void; + +declare function beforeEach(action: () => void): void; +declare function beforeEach(action: (done: () => void) => void): void; +declare function afterEach(action: () => void): void; +declare function afterEach(action: (done: () => void) => void): void; + +declare function expect(spy: Function): jasmine.Matchers; +declare function expect(actual: any): jasmine.Matchers; + +declare function spyOn(object: any, method: string): jasmine.Spy; + +declare function runs(asyncMethod: Function): void; +declare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void; +declare function waits(timeout?: number): void; + +declare module jasmine { + + var clock: () => Clock; + + function any(aclass: any): Any; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function getEnv(): Env; + function addMatchers(matchers: any): Any; + + interface Any { + + new (expectedClass: any): any; + + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Block { + + new (env: Env, func: SpecFunction, spec: Spec): any; + + execute(onComplete: () => void): void; + } + + interface WaitsBlock extends Block { + new (env: Env, timeout: number, spec: Spec): any; + } + + interface WaitsForBlock extends Block { + new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any; + } + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + } + + interface Env { + setTimeout: any; + clearTimeout: void; + setInterval: any; + clearInterval: void; + updateInterval: number; + + currentSpec: Spec; + + matchersClass: Matchers; + + version(): any; + versionString(): string; + nextSpecId(): number; + addReporter(reporter: Reporter): void; + execute(): void; + describe(description: string, specDefinitions: () => void): Suite; + // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these + beforeEach(beforeEachFunction: () => void): void; + currentRunner(): Runner; + afterEach(afterEachFunction: () => void): void; + xdescribe(desc: string, specDefinitions: () => void): XSuite; + it(description: string, func: () => void): Spec; + // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these + xit(desc: string, func: () => void): XSpec; + compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean; + compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean; + contains_(haystack: any, needle: any): boolean; + addEqualityTester(equalityTester: (a: any, b: any, env: Env, mismatchKeys: string[], mismatchValues: string[]) => boolean): void; + specFilter(spec: Spec): boolean; + } + + interface FakeTimer { + + new (): any; + + reset(): void; + tick(millis: number): void; + runFunctionsWithinRange(oldMillis: number, nowMillis: number): void; + scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void; + } + + interface HtmlReporter { + new (): any; + } + + interface HtmlSpecFilter { + new (): any; + } + + interface Result { + type: string; + } + + interface NestedResults extends Result { + description: string; + + totalCount: number; + passedCount: number; + failedCount: number; + + skipped: boolean; + + rollupCounts(result: NestedResults): void; + log(values: any): void; + getItems(): Result[]; + addResult(result: Result): void; + passed(): boolean; + } + + interface MessageResult extends Result { + values: any; + trace: Trace; + } + + interface ExpectationResult extends Result { + matcherName: string; + passed(): boolean; + expected: any; + actual: any; + message: string; + trace: Trace; + } + + interface Trace { + name: string; + message: string; + stack: any; + } + + interface PrettyPrinter { + + new (): any; + + format(value: any): void; + iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void; + emitScalar(value: any): void; + emitString(value: string): void; + emitArray(array: any[]): void; + emitObject(obj: any): void; + append(value: any): void; + } + + interface StringPrettyPrinter extends PrettyPrinter { + } + + interface Queue { + + new (env: any): any; + + env: Env; + ensured: boolean[]; + blocks: Block[]; + running: boolean; + index: number; + offset: number; + abort: boolean; + + addBefore(block: Block, ensure?: boolean): void; + add(block: any, ensure?: boolean): void; + insertNext(block: any, ensure?: boolean): void; + start(onComplete?: () => void): void; + isRunning(): boolean; + next_(): void; + results(): NestedResults; + } + + interface Matchers { + + new (env: Env, actual: any, spec: Env, isNot?: boolean): any; + + env: Env; + actual: any; + spec: Env; + isNot?: boolean; + message(): any; + + toBe(expected: any): boolean; + toNotBe(expected: any): boolean; + toEqual(expected: any): boolean; + toNotEqual(expected: any): boolean; + toMatch(expected: any): boolean; + toNotMatch(expected: any): boolean; + toBeDefined(): boolean; + toBeUndefined(): boolean; + toBeNull(): boolean; + toBeNaN(): boolean; + toBeTruthy(): boolean; + toBeFalsy(): boolean; + toHaveBeenCalled(): boolean; + wasNotCalled(): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toContain(expected: any): boolean; + toNotContain(expected: any): boolean; + toBeLessThan(expected: any): boolean; + toBeGreaterThan(expected: any): boolean; + toBeCloseTo(expected: any, precision: any): boolean; + toContainHtml(expected: string): boolean; + toContainText(expected: string): boolean; + toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; + not: Matchers; + + Any: Any; + } + + interface Reporter { + reportRunnerStarting(runner: Runner): void; + reportRunnerResults(runner: Runner): void; + reportSuiteResults(suite: Suite): void; + reportSpecStarting(spec: Spec): void; + reportSpecResults(spec: Spec): void; + log(str: string): void; + } + + interface MultiReporter extends Reporter { + addReporter(reporter: Reporter): void; + } + + interface Runner { + + new (env: Env): any; + + execute(): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + finishCallback(): void; + addSuite(suite: Suite): void; + add(block: Block): void; + specs(): Spec[]; + suites(): Suite[]; + topLevelSuites(): Suite[]; + results(): NestedResults; + } + + interface SpecFunction { + (spec?: Spec): void; + } + + interface SuiteOrSpec { + id: number; + env: Env; + description: string; + queue: Queue; + } + + interface Spec extends SuiteOrSpec { + + new (env: Env, suite: Suite, description: string): any; + + suite: Suite; + + afterCallbacks: SpecFunction[]; + spies_: Spy[]; + + results_: NestedResults; + matchersClass: Matchers; + + getFullName(): string; + results(): NestedResults; + log(arguments: any): any; + runs(func: SpecFunction): Spec; + addToQueue(block: Block): void; + addMatcherResult(result: Result): void; + expect(actual: any): any; + waits(timeout: number): Spec; + waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec; + fail(e?: any): void; + getMatchersClass_(): Matchers; + addMatchers(matchersPrototype: any): void; + finishCallback(): void; + finish(onComplete?: () => void): void; + after(doAfter: SpecFunction): void; + execute(onComplete?: () => void): any; + addBeforesAndAftersToQueue(): void; + explodes(): void; + spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy; + removeAllSpies(): void; + } + + interface XSpec { + id: number; + runs(): void; + } + + interface Suite extends SuiteOrSpec { + + new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any; + + parentSuite: Suite; + + getFullName(): string; + finish(onComplete?: () => void): void; + beforeEach(beforeEachFunction: SpecFunction): void; + afterEach(afterEachFunction: SpecFunction): void; + results(): NestedResults; + add(suiteOrSpec: SuiteOrSpec): void; + specs(): Spec[]; + suites(): Suite[]; + children(): any[]; + execute(onComplete?: () => void): void; + } + + interface XSuite { + execute(): void; + } + + interface Spy { + (...params: any[]): any; + + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + callCount: number; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): void; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): void; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): void; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): void; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): void; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called **/ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/ + all(): any; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/ + mostRecent(): any; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/ + first(): any; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/ + reset(): void; + } + + interface Util { + inherit(childClass: Function, parentClass: Function): any; + formatException(e: any): any; + htmlEscape(str: string): string; + argsToArray(args: any): any; + extend(destination: any, source: any): any; + } + + interface JsApiReporter extends Reporter { + + started: boolean; + finished: boolean; + result: any; + messages: any; + + new (): any; + + suites(): Suite[]; + summarize_(suiteOrSpec: SuiteOrSpec): any; + results(): any; + resultsForSpec(specId: any): any; + log(str: any): any; + resultsForSpecs(specIds: any): any; + summarizeResult_(result: any): any; + } + + interface Jasmine { + Spec: Spec; + clock: Clock; + util: Util; + } + + export var HtmlReporter: HtmlReporter; + export var HtmlSpecFilter: HtmlSpecFilter; + export var DEFAULT_TIMEOUT_INTERVAL: number; +} diff --git a/test-app/assets/app/Infrastructure/timers.js b/test-app/assets/app/Infrastructure/timers.js new file mode 100644 index 000000000..130d6b3c2 --- /dev/null +++ b/test-app/assets/app/Infrastructure/timers.js @@ -0,0 +1,51 @@ +var timeoutHandler; +var timeoutCallbacks = {}; +function createHadlerAndGetId() { + if (!timeoutHandler) { + timeoutHandler = new android.os.Handler(android.os.Looper.getMainLooper()); + } + return new Date().getUTCMilliseconds(); +} +function setTimeout(callback, milliseconds) { + if (milliseconds === void 0) { milliseconds = 0; } + var id = createHadlerAndGetId(); + var runnable = new java.lang.Runnable({ + run: function () { + callback(); + if (timeoutCallbacks && timeoutCallbacks[id]) { + timeoutCallbacks[id] = null; + } + } + }); + if (!timeoutCallbacks[id]) { + timeoutCallbacks[id] = runnable; + } + timeoutHandler.postDelayed(runnable, long(milliseconds)); + return id; +} +global.setTimeout = setTimeout; +function clearTimeout(id) { + if (timeoutCallbacks[id]) { + timeoutHandler.removeCallbacks(timeoutCallbacks[id]); + timeoutCallbacks[id] = null; + } +} +global.clearTimeout = clearTimeout; +function setInterval(callback, milliseconds) { + if (milliseconds === void 0) { milliseconds = 0; } + var id = createHadlerAndGetId(); + var handler = timeoutHandler; + var runnable = new java.lang.Runnable({ + run: function () { + callback(); + handler.postDelayed(runnable, long(milliseconds)); + } + }); + if (!timeoutCallbacks[id]) { + timeoutCallbacks[id] = runnable; + } + timeoutHandler.postDelayed(runnable, long(milliseconds)); + return id; +} +global.setInterval = setInterval; +global.clearInterval = clearTimeout; diff --git a/test-app/assets/app/bootstrap.js b/test-app/assets/app/bootstrap.js index 0e23b86ae..6d66c0b49 100644 --- a/test-app/assets/app/bootstrap.js +++ b/test-app/assets/app/bootstrap.js @@ -10,4 +10,25 @@ global.__onUncaughtError = function(error){ return true; } +require('./Infrastructure/timers'); + +global.__JUnitSaveResults = function (unitTestResults) { + var pathToSdcard = '/sdcard'; + var unitTestFileName = 'android_unit_test_results.xml'; + try { + var javaFile = new java.io.File(pathToSdcard, unitTestFileName); + var stream = new java.io.FileOutputStream(javaFile); + var actualEncoding = 'UTF-8'; + var writer = new java.io.OutputStreamWriter(stream, actualEncoding); + writer.write(unitTestResults); + writer.close(); + } + catch (exception) { + __log('failed writing to files dir: ' + exception); + } +}; + +require('./Infrastructure/Jasmine/jasmine-2.0.1/boot'); //runs jasmine, attaches the junitOutputter + + require("./mainpage"); \ No newline at end of file diff --git a/test-app/assets/app/mainpage.js b/test-app/assets/app/mainpage.js index 0efdffde5..b959a84c6 100644 --- a/test-app/assets/app/mainpage.js +++ b/test-app/assets/app/mainpage.js @@ -1,15 +1,14 @@ __disableVerboseLogging(); -require("./tests/testWeakRef"); -require("./tests/tests"); +require("./tests/testWeakRef"); +require("./tests/tests"); require("./tests/testsForRuntimeBindingGenerator"); -//require("./tests/propertyAccessTests"); -require("./tests/numericConversionTests"); -require("./tests/inheritanceChainResolutionTest"); +require("./tests/numericConversionTests"); +require("./tests/inheritanceChainResolutionTest"); require("./tests/exceptionHandlingTests"); require("./tests/dispatchCallbacksOnUiThreadTests"); require("./tests/stringConversionTests"); -require("./tests/testsForTypescript"); +require("./tests/testsForTypescript"); require("./tests/testGC"); require("./tests/testsMemoryManagement"); require("./tests/testIfAbleToRunExternalFile"); @@ -17,34 +16,6 @@ require("./tests/finalFieldsSetTests"); require("./tests/extendedClassesTests"); require("./tests/extendClassNameTests"); - -//var MainActivity = com.tns.NativeScriptActivity.extend("MainActivity", { -// onCreate: function() { -// this.super.onCreate(null); -// -// require("./tests/testsWithContext").run(this); -// -// var layout = new android.widget.LinearLayout(this); -// layout.setOrientation(1); -// this.setContentView(layout); -// -// var textView = new android.widget.TextView(this); -// textView.setText("Hit that sucker"); -// layout.addView(textView); -// -// var button = new android.widget.Button(this); -// button.setText("Hit me"); -// layout.addView(button); -// var counter = 0; -// button.setOnClickListener(new android.view.View.OnClickListener("AppClickListener", { -// onClick: function() { -// __log("onClick called"); -// button.setText("Hit that sucker one more time " + ++counter); -// }})); -// }}); - - - var MainActivity = (function (_super) { __extends(MainActivity, _super); function MainActivity() { @@ -56,8 +27,9 @@ var MainActivity = (function (_super) { __log("this.toString " + k); _super.prototype.onCreate.call(this, null); //this.super.onCreate(null); - + require("./tests/testsWithContext").run(this); + execute(); //run jasmine var layout = new android.widget.LinearLayout(this); layout.setOrientation(1); diff --git a/test-app/assets/app/modules/module.js b/test-app/assets/app/modules/module.js index 3b753516d..91b4a4762 100644 --- a/test-app/assets/app/modules/module.js +++ b/test-app/assets/app/modules/module.js @@ -14,5 +14,6 @@ var tnsExtends = this.__extends; module.exports = { accessGlobalObject: function(s) { __log("global is working " + global); + return true; } } \ No newline at end of file diff --git a/test-app/assets/app/tests/dispatchCallbacksOnUiThreadTests.js b/test-app/assets/app/tests/dispatchCallbacksOnUiThreadTests.js index 69e855523..fba118c8e 100644 --- a/test-app/assets/app/tests/dispatchCallbacksOnUiThreadTests.js +++ b/test-app/assets/app/tests/dispatchCallbacksOnUiThreadTests.js @@ -1,30 +1,28 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestProcessDataCallbackShouldBeExecutedOnUiThread = function() { +describe("Tests dispatch callbacks on UI thread ", function () { + + it("TestProcessDataCallbackShouldBeExecutedOnUiThread", function () { - __log("TEST: TestProcessDataCallbackShouldBeExecutedOnUiThread"); + __log("TEST: TestProcessDataCallbackShouldBeExecutedOnUiThread"); - var D = com.tns.tests.DispatchAsyncOpOnUIThreadTest.extend("DispatchAsyncOpOnUIThreadTest", { - processData: function(index, data) { - if (index === 0) { - Assert(data === 123, "TestProcessDataCallbackShouldBeExecutedOnUiThread FAILED: Expected value is 123, actual value=" + data); - } else if (index === 1) { - Assert(data === 456, "TestProcessDataCallbackShouldBeExecutedOnUiThread FAILED: Expected value is 456, actual value=" + data); - } else if (index === 2) { - Assert(data === 789, "TestProcessDataCallbackShouldBeExecutedOnUiThread FAILED: Expected value is 789, actual value=" + data); - } else { - Assert(false, "TestProcessDataCallbackShouldBeExecutedOnUiThread FAILED: Expected index is 0, 1 or 2. Actual value=" + index); + var D = com.tns.tests.DispatchAsyncOpOnUIThreadTest.extend("DispatchAsyncOpOnUIThreadTest", { + processData: function(index, data) { + it("inner spec", function () { + if (index === 0) { + expect(data).toBe(123); + } else if (index === 1) { + expect(data).toBe(456); + } else if (index === 2) { + expect(data).toBe(789); + } else { + //one of the above has to be called ... else fail + expect(true).toBe(false); + } + }); } - } + }); + + var d = new D(); + + d.processDataAsync([123, 456, 789]); }); - - var d = new D(); - - d.processDataAsync([123, 456, 789]); -} - -TestProcessDataCallbackShouldBeExecutedOnUiThread(); +}); diff --git a/test-app/assets/app/tests/exceptionHandlingTests.js b/test-app/assets/app/tests/exceptionHandlingTests.js index d36f6f261..9d0cf230b 100644 --- a/test-app/assets/app/tests/exceptionHandlingTests.js +++ b/test-app/assets/app/tests/exceptionHandlingTests.js @@ -1,276 +1,269 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestThrowJSExceptionThroughJavaAndCatchInJS = function() { - - __log("TEST: TestThrowJSExceptionThroughJavaAndCatchInJS"); +describe("Tests exception handling ", function () { - var exceptionThrown = false; - var exceptionCaught = false; - var sameExObject = false; + var myCustomEquality = function(first, second) { + return first == second; + }; - var ex = { myProp: "SomeValue" }; + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); - var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest", { - onEvent1: function(s) { - exceptionThrown = true; - throw ex; + it("TestThrowJSExceptionThroughJavaAndCatchInJS", function () { + + __log("TEST: TestThrowJSExceptionThroughJavaAndCatchInJS"); + + var exceptionThrown = false; + var exceptionCaught = false; + var sameExObject = false; + + var ex = { myProp: "SomeValue" }; + + var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest", { + onEvent1: function(s) { + exceptionThrown = true; + throw ex; + } + }); + + var eh = new EH(); + + try + { + eh.triggerEvent1("test"); } + catch (e) + { + exceptionCaught = true; + sameExObject = e === ex; + __log("e=" + e); + } + + expect(exceptionThrown).toBe(true); + expect(exceptionCaught).toBe(true); + expect(sameExObject).toBe(true); }); - var eh = new EH(); - - try - { - eh.triggerEvent1("test"); - } - catch (e) - { - exceptionCaught = true; - sameExObject = e === ex; - __log("e=" + e); - } - - Assert(exceptionThrown === true, "TestThrowJSExceptionThroughJavaAndCatchInJS FAILED: Exception should be thrown"); - Assert(exceptionCaught === true, "TestThrowJSExceptionThroughJavaAndCatchInJS FAILED: Exception should be caught"); - Assert(sameExObject === true, "TestThrowJSExceptionThroughJavaAndCatchInJS FAILED: The expected caught object should be strict equal to 'ex'"); -} + it("TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS", function () { -var TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS = function() { + __log("TEST: TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS"); + + var exceptionThrown = false; + var exceptionCaught = false; + var nativeExceptionFound = false; + var exMsg = ""; + + var ex = new java.lang.Exception("This exception is thrown from JavaScript!"); + + var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest53", { + onEvent1: function(s) { + exceptionThrown = true; + throw ex; + } + }); + + var eh = new EH(); + + try + { + eh.triggerEvent1("test"); + } + catch (e) + { + exceptionCaught = true; + nativeExceptionFound = e.nativeException !== undefined; + if (nativeExceptionFound) + { + exMsg = e.nativeException.getMessage(); + } + } - __log("TEST: TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS"); - - var exceptionThrown = false; - var exceptionCaught = false; - var nativeExceptionFound = false; - var exMsg = ""; - - var ex = new java.lang.Exception("This exception is thrown from JavaScript!"); + expect(exceptionThrown).toBe(true); + expect(exceptionCaught).toBe(true); + expect(nativeExceptionFound).toBe(true); + expect(exMsg).toBe("This exception is thrown from JavaScript!"); + }); - var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest53", { - onEvent1: function(s) { - exceptionThrown = true; - throw ex; + it("TestThrowJSExceptionAndCatchInJava", function () { + + __log("TEST: TestThrowJSExceptionAndCatchInJava"); + + var exceptionThrown = false; + var exceptionCaught = true; + + var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest89", { + onEvent1: function(s) { + exceptionThrown = true; + throw "My Exception String"; + } + }); + + var eh = new EH(); + + try + { + eh.triggerEvent1WithCatchClause("test"); + exceptionCaught = false; } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionThrown).toBe(true); + expect(exceptionCaught).toBe(false); }); - var eh = new EH(); - - try - { - eh.triggerEvent1("test"); - } - catch (e) - { - exceptionCaught = true; - nativeExceptionFound = e.nativeException !== undefined; - if (nativeExceptionFound) + it("TestThrowJavaExceptionFromJsAndCatchInJava", function () { + + __log("TEST: TestThrowJavaExceptionFromJsAndCatchInJava"); + + var exceptionThrown = false; + var exceptionCaught = true; + + var ex = new java.lang.Exception("This exception is thrown from JavaScript!"); + + var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest121", { + onEvent1: function(s) { + exceptionThrown = true; + throw ex; + } + }); + + var eh = new EH(); + + try { - exMsg = e.nativeException.getMessage(); + eh.triggerEvent1WithCatchClause("test"); + exceptionCaught = false; + } + catch (e) + { + exceptionCaught = true; } - } - - Assert(exceptionThrown === true, "TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS FAILED: Exception should be thrown"); - Assert(exceptionCaught === true, "TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS FAILED: Exception should be caught"); - Assert(nativeExceptionFound === true, "TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS FAILED: The expected caught object should have 'nativeException' property set"); - Assert(exMsg === "This exception is thrown from JavaScript!", "TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS FAILED: Expected value is 'This exception is thrown from JavaScript!', actual value=" + exMsg); -} - -var TestThrowJSExceptionAndCatchInJava = function() { - __log("TEST: TestThrowJSExceptionAndCatchInJava"); - - var exceptionThrown = false; - var exceptionCaught = true; + expect(exceptionThrown).toBe(true); + expect(exceptionCaught).toBe(false); + }); - var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest89", { - onEvent1: function(s) { - exceptionThrown = true; - throw "My Exception String"; + it("TestMethodThatThrowsException", function () { + + __log("TEST: TestMethodThatThrowsException"); + + var exceptionCaught = false; + + var dummy = new com.tns.tests.DummyClass(); + + try + { + dummy.methodThatThrowsException(); + } + catch (e) + { + exceptionCaught = true; } + + expect(exceptionCaught).toBe(true); }); - var eh = new EH(); - - try - { - eh.triggerEvent1WithCatchClause("test"); - exceptionCaught = false; - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionThrown === true, "TestThrowJSExceptionAndCatchInJava FAILED: Exception should be thrown"); - Assert(exceptionCaught === false, "TestThrowJSExceptionAndCatchInJava FAILED: Exception should not be caught"); -} - -var TestThrowJavaExceptionFromJsAndCatchInJava = function() { + it("TestErrorObjectContainsJavaNativeException", function () { + + + __log("TEST: TestErrorObjectContainsJavaNativeException"); + + var nativeException = undefined; + + var dummy = new com.tns.tests.DummyClass(); + + try + { + dummy.methodThatThrowsException(); + } + catch (e) + { + var nativeException = e.nativeException; + } - __log("TEST: TestThrowJavaExceptionFromJsAndCatchInJava"); - - var exceptionThrown = false; - var exceptionCaught = true; - - var ex = new java.lang.Exception("This exception is thrown from JavaScript!"); + __log("nativeException=" + nativeException); + + expect(nativeException).not.toEqual(undefined); + + var nativeExceptionFrameCount = nativeException.getStackTrace().length; + + expect(nativeExceptionFrameCount).toBeGreaterThan(0); + }); - var EH = com.tns.tests.ExceptionHandlingTest.extend("ExceptionHandlingTest121", { - onEvent1: function(s) { - exceptionThrown = true; - throw ex; + it("TestConstructorThatThrowsException", function () { + + __log("TEST: TestConstructorThatThrowsException"); + + var exceptionCaught = false; + + try + { + var dummy = new com.tns.tests.DummyClass(true /* throwsException */); + } + catch (e) + { + exceptionCaught = true; } + + expect(exceptionCaught).toBe(true); }); - var eh = new EH(); - - try - { - eh.triggerEvent1WithCatchClause("test"); - exceptionCaught = false; - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionThrown === true, "TestThrowJavaExceptionFromJsAndCatchInJava FAILED: Exception should be thrown"); - Assert(exceptionCaught === false, "TestThrowJavaExceptionFromJsAndCatchInJava FAILED: Exception should not be caught"); -} - -var TestMethodThatThrowsException = function() { - - __log("TEST: TestMethodThatThrowsException"); - - var exceptionCaught = false; - - var dummy = new com.tns.tests.DummyClass(); - - try - { - dummy.methodThatThrowsException(); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestMethodThatThrowsException FAILED: Java exception was not caught") -} - -var TestErrorObjectContainsJavaNativeException = function() { - - __log("TEST: TestErrorObjectContainsJavaNativeException"); - - var nativeException = undefined; - - var dummy = new com.tns.tests.DummyClass(); - - try - { - dummy.methodThatThrowsException(); - } - catch (e) - { - var nativeException = e.nativeException; - } - - __log("nativeException=" + nativeException); - - Assert(nativeException != undefined, "TestErrorObjectContainsJavaNativeException FAILED: Error object does not contain Java native exception"); - - var nativeExceptionFrameCount = nativeException.getStackTrace().length; - - Assert(nativeExceptionFrameCount > 0, "TestErrorObjectContainsJavaNativeException FAILED: Java native exception does not contains stack frames"); -} - -var TestConstructorThatThrowsException = function() { - - __log("TEST: TestConstructorThatThrowsException"); - - var exceptionCaught = false; - - try - { - var dummy = new com.tns.tests.DummyClass(true /* throwsException */); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestConstructorThatThrowsException FAILED: Java exception was not caught"); -} - -var TestArrayElementGetAccessThatThrowsException = function() { - - __log("TEST: TestArrayElementGetAccessThatThrowsException"); - - var exceptionCaught = false; - - var d = new com.tns.tests.DummyClass(); - - var arr = d.getDummyClassArrayAsObject(); - - var arrLength = arr.length; - - Assert(arrLength == 1, "TestArrayElementGetAccessThatThrowsException FAILED: Expected array length is 1, actual length=" + arrLength); - - try - { - var dummy = arr[arrLength]; - - var name = dummy.getName(); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestArrayElementGetAccessThatThrowsException FAILED: Java exception was not caught during getting array element"); -} - -var TestArrayElementSetAccessThatThrowsException = function() { - - __log("TEST: TestArrayElementSetAccessThatThrowsException"); - - var exceptionCaught = false; + it("TestArrayElementGetAccessThatThrowsException", function () { + + __log("TEST: TestArrayElementGetAccessThatThrowsException"); + + var exceptionCaught = false; - var d = new com.tns.tests.DummyClass(); - - var arr = d.getDummyClassArrayAsObject(); - - var arrLength = arr.length; - - Assert(arrLength == 1, "TestArrayElementSetAccessThatThrowsException FAILED: Expected array length is 1, actual length=" + arrLength); - - var last = arr[arrLength - 1]; - - try - { - arr[arrLength] = last; - } - catch (e) - { - exceptionCaught = true; - } + var d = new com.tns.tests.DummyClass(); + + var arr = d.getDummyClassArrayAsObject(); + + var arrLength = arr.length; + + expect(arrLength).toEqual(1); + + try + { + var dummy = arr[arrLength]; + + var name = dummy.getName(); + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); - Assert(exceptionCaught === true, "TestArrayElementSetAccessThatThrowsException FAILED: Java exception was not caught during setting array element"); -} - -TestThrowJSExceptionThroughJavaAndCatchInJS(); -TestThrowJavaExceptionFromJsThroughJavaAndCatchInJS(); -TestThrowJSExceptionAndCatchInJava(); -TestThrowJavaExceptionFromJsAndCatchInJava(); -TestMethodThatThrowsException(); -TestErrorObjectContainsJavaNativeException(); -TestConstructorThatThrowsException(); -TestArrayElementGetAccessThatThrowsException(); -TestArrayElementSetAccessThatThrowsException(); - - - + it("TestArrayElementSetAccessThatThrowsException", function () { + + __log("TEST: TestArrayElementSetAccessThatThrowsException"); + + var exceptionCaught = false; + var d = new com.tns.tests.DummyClass(); + + var arr = d.getDummyClassArrayAsObject(); + + var arrLength = arr.length; + + expect(arrLength).toEqual(1); + + var last = arr[arrLength - 1]; + + try + { + arr[arrLength] = last; + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/extendClassNameTests.js b/test-app/assets/app/tests/extendClassNameTests.js index a03998b19..9419fa0ee 100644 --- a/test-app/assets/app/tests/extendClassNameTests.js +++ b/test-app/assets/app/tests/extendClassNameTests.js @@ -1,41 +1,43 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -//the class name valid symbols are [a-z , A-Z , 0-9, _] -var When_naming_extension_class_user_should_give_valid_name = function() { +describe("Tests extend class name ", function () { - var exceptionCaught = false; - try - { - var O = java.lang.Object.extend("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", {}); - } - catch(e) - { - exceptionCaught = true; - __log("Validation is wrong"); - } + var myCustomEquality = function(first, second) { + return first == second; + }; - Assert(exceptionCaught === false, "FAILED: When_naming_extension_class_user_should_give_valid_name."); -} - -var When_naming_extension_contains_invalid_symbols_should_throw_exception = function() { + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); - var exceptionCaught = false; - try - { - var O = java.lang.Object.extend("1235!", {}); //[!] is invalid symbol - } - catch(e) - { - __log('message: ' + e.message); - exceptionCaught = true; - } + //the class name valid symbols are [a-z , A-Z , 0-9, _] + it("When_naming_extension_class_user_should_give_valid_name", function () { + + var exceptionCaught = false; + try + { + var O = java.lang.Object.extend("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", {}); + } + catch(e) + { + exceptionCaught = true; + __log("Validation is wrong"); + } + + expect(exceptionCaught).toBe(false); + }); - Assert(exceptionCaught === true, "FAILED: When_naming_extension_doesnt_have_valid_name_should_throw_exception."); -} + it("When_naming_extension_contains_invalid_symbols_should_throw_exception", function () { + + var exceptionCaught = false; + try + { + var O = java.lang.Object.extend("1235!", {}); //[!] is invalid symbol + } + catch(e) + { + __log('message: ' + e.message); + exceptionCaught = true; + } -When_naming_extension_class_user_should_give_valid_name(); -When_naming_extension_contains_invalid_symbols_should_throw_exception(); \ No newline at end of file + expect(exceptionCaught).toBe(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/extendedClassesTests.js b/test-app/assets/app/tests/extendedClassesTests.js index f4fae3838..639a7cee3 100644 --- a/test-app/assets/app/tests/extendedClassesTests.js +++ b/test-app/assets/app/tests/extendedClassesTests.js @@ -1,83 +1,76 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} +describe("Tests extended classes ", function () { -var Instance_with_no_extension_shouldnt_use_previously_defined_implementation_object = function() { - var MyButton = new com.tns.tests.Button1.extend({ - toString: function () { - return "overriden toString method of chronometer instance"; - }, - getIMAGE_ID_PROP: function () { - return "overriden getIMAGE_ID_PROP method on button"; - } + it("Instance_with_no_extension_shouldnt_use_previously_defined_implementation_object", function () { + var MyButton = new com.tns.tests.Button1.extend({ + toString: function () { + return "overriden toString method of chronometer instance"; + }, + getIMAGE_ID_PROP: function () { + return "overriden getIMAGE_ID_PROP method on button"; + } + }); + var button = new MyButton(); + var labelToString = button.toString(); + var labelgetIMAGE_ID_PROP = button.getIMAGE_ID_PROP(); + // + + var button1 = new com.tns.tests.Button1(); + var labelToString1 = button1.toString(); + var labelgetIMAGE_ID_PROP1 = button1.getIMAGE_ID_PROP(); + + expect(labelToString).not.toBe(labelToString1); + expect(labelgetIMAGE_ID_PROP).not.toBe(labelgetIMAGE_ID_PROP1); }); - var button = new MyButton(); - var labelToString = button.toString(); - var labelgetIMAGE_ID_PROP = button.getIMAGE_ID_PROP(); - // - var button1 = new com.tns.tests.Button1(); - var labelToString1 = button1.toString(); - var labelgetIMAGE_ID_PROP1 = button1.getIMAGE_ID_PROP(); - - - Assert((labelToString !== labelToString1) && (labelgetIMAGE_ID_PROP !== labelgetIMAGE_ID_PROP1), "Instance_with_no_extension_it_shouldnt_use_previously_defined_implementation_object FAILED! Labels need to be different"); -} + it("Instance_with_extension_shouldnt_use_previously_defined_implementation_object", function () { + + var MyButton = new com.tns.tests.Button1.extend({ + toString: function () { + return "overriden toString method of button instance"; + }, + getIMAGE_ID_PROP: function () { + return "overriden getIMAGE_ID_PROP method on button"; + } + }); + var button = new MyButton(); + var labelToString = button.toString(); + var labelgetIMAGE_ID_PROP = button.getIMAGE_ID_PROP(); + // + + var MyButton1 = new com.tns.tests.Button1.extend({ + toString: function () { + return "overriden toString method of button1 instance "; + }, + getIMAGE_ID_PROP: function () { + return "overriden getIMAGE_ID_PROP method on button1"; + } + }); + var button1 = new MyButton1(); + var labelToString1 = button1.toString(); + var labelgetIMAGE_ID_PROP1 = button1.getIMAGE_ID_PROP(); -var Instance_with_extension_shouldnt_use_previously_defined_implementation_object = function() { - var MyButton = new com.tns.tests.Button1.extend({ - toString: function () { - return "overriden toString method of button instance"; - }, - getIMAGE_ID_PROP: function () { - return "overriden getIMAGE_ID_PROP method on button"; - } - }); - var button = new MyButton(); - var labelToString = button.toString(); - var labelgetIMAGE_ID_PROP = button.getIMAGE_ID_PROP(); - // - - var MyButton1 = new com.tns.tests.Button1.extend({ - toString: function () { - return "overriden toString method of button1 instance "; - }, - getIMAGE_ID_PROP: function () { - return "overriden getIMAGE_ID_PROP method on button1"; - } + expect(labelToString).not.toBe(labelToString1); + expect(labelgetIMAGE_ID_PROP).not.toBe(labelgetIMAGE_ID_PROP1); }); - var button1 = new MyButton1(); - var labelToString1 = button1.toString(); - var labelgetIMAGE_ID_PROP1 = button1.getIMAGE_ID_PROP(); - - Assert((labelToString !== labelToString1) && (labelgetIMAGE_ID_PROP !== labelgetIMAGE_ID_PROP1), "Instance_with_no_extension_it_shouldnt_use_previously_defined_implementation_object FAILED! Labels need to be different"); -} + it("Newly_created_instances_should_behave_the_same_and_not_use_previously_defined_implementation_objects", function () { -var Newly_created_instances_should_behave_the_same_and_not_use_previously_defined_implementation_objects = function() { - - var button1 = new com.tns.tests.Button1(); - var labelgetIMAGE_ID_PROP1 = button1.getIMAGE_ID_PROP(); - - // - var MyButton = new com.tns.tests.Button1.extend({ - getIMAGE_ID_PROP: function () { - return "overriden getIMAGE_ID_PROP method on button"; - } + var button1 = new com.tns.tests.Button1(); + var labelgetIMAGE_ID_PROP1 = button1.getIMAGE_ID_PROP(); + + // + var MyButton = new com.tns.tests.Button1.extend({ + getIMAGE_ID_PROP: function () { + return "overriden getIMAGE_ID_PROP method on button"; + } + }); + var button = new MyButton(); + var labelgetIMAGE_ID_PROP = button.getIMAGE_ID_PROP(); + // + + var button2 = new com.tns.tests.Button1(); + var labelgetIMAGE_ID_PROP2 = button2.getIMAGE_ID_PROP(); + + expect(labelgetIMAGE_ID_PROP1).toBe(labelgetIMAGE_ID_PROP2); }); - var button = new MyButton(); - var labelgetIMAGE_ID_PROP = button.getIMAGE_ID_PROP(); - // - - var button2 = new com.tns.tests.Button1(); - var labelgetIMAGE_ID_PROP2 = button2.getIMAGE_ID_PROP(); - - Assert(labelgetIMAGE_ID_PROP1 === labelgetIMAGE_ID_PROP2, "Instance_with_no_extension_it_shouldnt_use_previously_defined_implementation_object FAILED! Labels need to be different"); - -} - -Instance_with_no_extension_shouldnt_use_previously_defined_implementation_object(); -Instance_with_extension_shouldnt_use_previously_defined_implementation_object(); -Newly_created_instances_should_behave_the_same_and_not_use_previously_defined_implementation_objects(); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/finalFieldsSetTests.js b/test-app/assets/app/tests/finalFieldsSetTests.js index 3cd755fc4..81bf388ff 100644 --- a/test-app/assets/app/tests/finalFieldsSetTests.js +++ b/test-app/assets/app/tests/finalFieldsSetTests.js @@ -1,23 +1,17 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var When_a_java_final_field_is_set_exception_is_thrown = function() { - - var exceptionCaught = false; - try - { - com.tns.tests.Button1.STATIC_IMAGE_ID = "NEW STATIC IMAGE ID VALUE"; - } - catch (e) - { - __log("Don't try to SET a final field " + e); - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "When_a_java_final_field_is_set_exception_is_thrown FAILED: Exception(illegal access) should be thrown"); -} - -When_a_java_final_field_is_set_exception_is_thrown(); +describe("Tests final fields set", function () { + + it("When trying to set a final field throw exception", function () { + + var exceptionCaught = false; + try + { + com.tns.tests.Button1.STATIC_IMAGE_ID = "NEW STATIC IMAGE ID VALUE"; + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/inheritanceChainResolutionTest.js b/test-app/assets/app/tests/inheritanceChainResolutionTest.js index 3a8ffbc50..35ac44cfe 100644 --- a/test-app/assets/app/tests/inheritanceChainResolutionTest.js +++ b/test-app/assets/app/tests/inheritanceChainResolutionTest.js @@ -1,30 +1,32 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestCallWithStringArgumentWhenThereIsStringOverload = function() { - - __log("TEST: TestCallWithStringArgumentWhenThereIsStringOverload"); +describe("Tests inheritance chain resolution", function () { - var i = new com.tns.tests.InheritanceChainResolutionTest(); + var myCustomEquality = function(first, second) { + return first == second; + }; - var s = i.echo1("test123"); + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); - Assert(s === "String=test123", "TestCallWithStringArgumentWhenThereIsStringOverload FAILED: Expected value is 'String=test123', actual value=" + s); -} - -var TestCallWithStringArgumentWhenThereIsNoStringOverload = function() { - - __log("TEST: TestCallWithStringArgumentWhenThereIsNoStringOverload"); + it("TestCallWithStringArgumentWhenThereIsStringOverload", function () { + + __log("TEST: TestCallWithStringArgumentWhenThereIsStringOverload"); + + var i = new com.tns.tests.InheritanceChainResolutionTest(); + + var s = i.echo1("test123"); + + expect(s).toBe("String=test123"); + }); - var i = new com.tns.tests.InheritanceChainResolutionTest(); - - var s = i.echo2("test123"); - - Assert(s === "Object=test123", "TestCallWithStringArgumentWhenThereIsNoStringOverload FAILED: Expected value is 'Object=test123', actual value=" + s); -} - -TestCallWithStringArgumentWhenThereIsStringOverload(); -TestCallWithStringArgumentWhenThereIsNoStringOverload(); \ No newline at end of file + it("TestCallWithStringArgumentWhenThereIsNoStringOverload", function () { + + __log("TEST: TestCallWithStringArgumentWhenThereIsNoStringOverload"); + + var i = new com.tns.tests.InheritanceChainResolutionTest(); + + var s = i.echo2("test123"); + + expect(s).toBe("Object=test123"); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/numericConversionTests.js b/test-app/assets/app/tests/numericConversionTests.js index f99c0e651..d79eff981 100644 --- a/test-app/assets/app/tests/numericConversionTests.js +++ b/test-app/assets/app/tests/numericConversionTests.js @@ -1,270 +1,247 @@ -/* - Test suite for numeric conversions and constructor/method resolutions. -*/ - -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestCreateInstanceWithConstructorResolutionWithNumberLiteral = function() { - - __log("TEST: TestCreateInstanceWithConstructorResolutionWithNumberLiteral"); - - var n = new com.tns.tests.NumericConversionTest(123); - - var s = n.getInit(); - - Assert(s === "byte", "TestCreateInstanceWithConstructorResolutionWithNumberLiteral FAILED: Expected value is 'byte', actual value=" + s); -} - -var TestCreateInstanceWithConstructorResolutionWithCastFunctions = function() { - - __log("TEST: TestCreateInstanceWithConstructorResolutionWithCastFunctions"); - - var n1 = new com.tns.tests.NumericConversionTest(byte(123)); - var s1 = n1.getInit(); - Assert(s1 === "byte", "TestCreateInstanceWithConstructorResolutionWithCastFunctions FAILED: Expected value is 'byte', actual value=" + s1); - - var n2 = new com.tns.tests.NumericConversionTest(short(123)); - var s2 = n2.getInit(); - Assert(s2 === "byte", "TestCreateInstanceWithConstructorResolutionWithCastFunctions FAILED: Expected value is 'byte', actual value=" + s2); - - var n3 = new com.tns.tests.NumericConversionTest(long(123)); - var s3 = n3.getInit(); - Assert(s3 === "byte", "TestCreateInstanceWithConstructorResolutionWithCastFunctions FAILED: Expected value is 'byte', actual value=" + s3); -} - -var TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls = function() { - - __log("TEST: TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls"); - - var b = java.lang.Byte.parseByte("123"); - var n1 = new com.tns.tests.NumericConversionTest(b); - var s1 = n1.getInit(); - Assert(s1 === "byte", "TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls FAILED: Expected value is 'byte', actual value=" + s1); - - var i = java.lang.Integer.parseInt("12345"); - var n2 = new com.tns.tests.NumericConversionTest(i); - var s2 = n2.getInit(); - Assert(s2 === "byte", "TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls FAILED: Expected value is 'byte', actual value=" + s2); -} - -var TestCreateInstanceWithConstructorResolutionWithPromotingValueUp = function() { - - __log("TEST: TestCreateInstanceWithConstructorResolutionWithPromotingValueUp"); - - var n = new com.tns.tests.NumericConversionTest(null, short(1)); - var s = n.getInit(); - Assert(s === "Object,int", "TestCreateInstanceWithConstructorResolutionWithPromotingValueUp FAILED: Expected value is 'Object,int', actual value=" + s); -} - -var TestCreateInstanceWithConstructorResolutionWithPromotingValueDown = function() { - - __log("TEST: TestCreateInstanceWithConstructorResolutionWithPromotingValueDown"); - - var n = new com.tns.tests.NumericConversionTest(null, null, long(1)); - var s = n.getInit(); - Assert(s === "Object,Object,short", "TestCreateInstanceWithConstructorResolutionWithPromotingValueDown FAILED: Expected value is 'Object,Object,short', actual value=" + s); -} - -var TestCallMethodWithResolutionWithPromotingValueUp = function() { - - __log("TEST: TestCallMethodWithResolutionWithPromotingValueUp"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method1(byte(1)); - Assert(s === "short=1", "TestCallMethodWithResolutionWithPromotingValueUp FAILED: Expected value is 'short=1', actual value=" + s); -} - -var TestCallMethodWithResolutionWithPromotingValueDown = function() { - - __log("TEST: TestCallMethodWithResolutionWithPromotingValueDown"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method1(1); - Assert(s === "short=1", "TestCallMethodWithResolutionWithPromotingValueDown FAILED: Expected value is 'short=1', actual value=" + s); - - var n1 = new com.tns.tests.NumericConversionTest(); - var s1 = n1.method1(long((1 << 16) + 2)); - Assert(s1 === "short=2", "TestCallMethodWithResolutionWithPromotingValueDown FAILED: Expected value is 'short=2', actual value=" + s1); -} - -var TestLongCastToFloatConversionWhenThereIsDoubleOverload = function() { - - __log("TEST: TestLongCastToFloatConversionWhenThereIsDoubleOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method2(long(65536 + 2)); - Assert(s === "float=65538.0", "TestLongCastToFloatConversionWhenThereIsDoubleOverload FAILED: Expected value is 'float=65538.0', actual value=" + s); -} - -var TestByteCastToFloatConversionWhenThereIsDoubleOverload = function() { - - __log("TEST: TestByteCastToFloatConversionWhenThereIsDoubleOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method2(byte(65536 + 2)); - Assert(s === "float=2.0", "TestByteCastToFloatConversionWhenThereIsDoubleOverload FAILED: Expected value is 'float=2.0', actual value=" + s); -} - -var TestShortCastToFloatConversionWhenThereIsDoubleOverload = function() { - - __log("TEST: TestShortCastToFloatConversionWhenThereIsDoubleOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method2(short(65536 + 2)); - Assert(s === "float=2.0", "TestShortCastToFloatConversionWhenThereIsDoubleOverload FAILED: Expected value is 'float=2.0', actual value=" + s); -} - -var TestDoubleCastWhenThereIsDoubleOverload = function() { - - __log("TEST: TestDoubleCastWhenThereIsDoubleOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method2(double(65536 + 2)); - Assert(s === "double=65538.0", "TestDoubleCastWhenThereIsDoubleOverload FAILED: Expected value is 'double=65538.0', actual value=" + s); -} - -var TestNumberExpressionToFloatConversionWhenThereIsDoubleOverload = function() { - - __log("TEST: TestNumberExpressionToFloatConversionWhenThereIsDoubleOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method2(65536 + 2); - Assert(s === "float=65538.0", "TestNumberExpressionToFloatConversionWhenThereIsDoubleOverload FAILED: Expected value is 'float=65538.0', actual value=" + s); -} - -var TestDoubleCastToLongConversionWhenThereIsShortOverload = function() { - - __log("TEST: TestDoubleCastToLongConversionWhenThereIsShortOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method3(double(65536 + 2)); - Assert(s === "long=65538", "TestDoubleCastToLongConversionWhenThereIsShortOverload FAILED: Expected value is 'long=65538', actual value=" + s); -} - -var TestFloatCastToLongConversionWhenThereIsShortOverload = function() { - - __log("TEST: TestFloatCastToLongConversionWhenThereIsShortOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method3(float(65536 + 2)); - Assert(s === "long=65538", "TestFloatCastToLongConversionWhenThereIsShortOverload FAILED: Expected value is 'long=65538', actual value=" + s); -} - -var TestFloatCastToShortConversionWhenThereIsObjectOverload = function() { - - __log("TEST: TestFloatCastToShortConversionWhenThereIsObjectOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method4(float(65536 + 2)); - Assert(s === "short=2", "TestFloatCastToShortConversionWhenThereIsObjectOverload FAILED: Expected value is 'short=2', actual value=" + s); -} - -var TestByteCastToShortConversionWhenThereIsObjectOverload = function() { - - __log("TEST: TestByteCastToShortConversionWhenThereIsObjectOverload"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method4(byte(65536 + 2)); - Assert(s === "short=2", "TestByteCastToShortConversionWhenThereIsObjectOverload FAILED: Expected value is 'short=2', actual value=" + s); -} - -var TestResolveMethodWithByteCast = function() { - - __log("TEST: TestResolveMethodWithByteCast"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(byte(65536 + 123)); - Assert(s === "byte=123", "TestResolveMethodWithByteCast FAILED: Expected value is 'byte=123', actual value=" + s); -} - -var TestResolveMethodWithShortCast = function() { - - __log("TEST: TestResolveMethodWithShortCast"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(short(65536 + 1234)); - Assert(s === "short=1234", "TestResolveMethodWithShortCast FAILED: Expected value is 'short=1234', actual value=" + s); -} - -var TestResolveMethodWithoutCastFunction = function() { - - __log("TEST: TestResolveMethodWithoutCastFunction"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(123456); - Assert(s === "int=123456", "TestResolveMethodWithoutCastFunction FAILED: Expected value is 'int=123456', actual value=" + s); -} - -var TestResolveMethodWithLongCast = function() { - - __log("TEST: TestResolveMethodWithLongCast"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(long("123456789012")); - Assert(s === "long=123456789012", "TestResolveMethodWithLongCast FAILED: Expected value is 'long=123456789012', actual value=" + s); -} - -var TestResolveMethodWithFloatCast = function() { - - __log("TEST: TestResolveMethodWithFloatCast"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(float(1.23)); - Assert(s === "float=1.23", "TestResolveMethodWithFloatCast FAILED: Expected value is 'float=1.23', actual value=" + s); -} - -var TestResolveMethodWithDoubleCast = function() { - - __log("TEST: TestResolveMethodWithDoubleCast"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(double(1)); - Assert(s === "double=1.0", "TestResolveMethodWithDoubleCast FAILED: Expected value is 'double=1.0', actual value=" + s); -} - -var TestResolveIntMethodWithNumberObjectWithIntArgument = function() { - - __log("TEST: TestResolveIntMethodWithNumberObjectWithIntArgument"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(new Number(1)); - Assert(s === "int=1", "TestResolveIntMethodWithNumberObjectWithIntArgument FAILED: Expected value is 'int=1', actual value=" + s); -} - -var TestResolveIntMethodWithNumberObjectWithDoubleArgument = function() { - - __log("TEST: TestResolveIntMethodWithNumberObjectWithDoubleArgument"); - - var n = new com.tns.tests.NumericConversionTest(); - var s = n.method5(new Number(1.23)); - Assert(s === "double=1.23", "TestResolveIntMethodWithNumberObjectWithDoubleArgument 123FAILED: Expected value is 'double=1.23', actual value=" + s); -} - -TestCreateInstanceWithConstructorResolutionWithNumberLiteral(); -TestCreateInstanceWithConstructorResolutionWithCastFunctions(); -TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls(); -TestCreateInstanceWithConstructorResolutionWithPromotingValueUp(); -TestCreateInstanceWithConstructorResolutionWithPromotingValueDown(); -TestCallMethodWithResolutionWithPromotingValueUp(); -TestCallMethodWithResolutionWithPromotingValueDown(); -TestLongCastToFloatConversionWhenThereIsDoubleOverload(); -TestByteCastToFloatConversionWhenThereIsDoubleOverload(); -TestShortCastToFloatConversionWhenThereIsDoubleOverload(); -TestDoubleCastWhenThereIsDoubleOverload(); -TestNumberExpressionToFloatConversionWhenThereIsDoubleOverload(); -TestDoubleCastToLongConversionWhenThereIsShortOverload(); -TestFloatCastToLongConversionWhenThereIsShortOverload(); -TestFloatCastToShortConversionWhenThereIsObjectOverload(); -TestByteCastToShortConversionWhenThereIsObjectOverload(); -TestResolveMethodWithByteCast(); -TestResolveMethodWithShortCast(); -TestResolveMethodWithoutCastFunction(); -TestResolveMethodWithLongCast(); -TestResolveMethodWithFloatCast(); -TestResolveMethodWithDoubleCast(); -TestResolveIntMethodWithNumberObjectWithIntArgument(); -TestResolveIntMethodWithNumberObjectWithDoubleArgument(); \ No newline at end of file +describe("Tests numeric conversions and constructor/method resolutions", function () { + + var myCustomEquality = function(first, second) { + return first == second; + }; + + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); + + it("TestCreateInstanceWithConstructorResolutionWithNumberLiteral", function () { + + __log("TEST: TestCreateInstanceWithConstructorResolutionWithNumberLiteral"); + + var n = new com.tns.tests.NumericConversionTest(123); + + var s = n.getInit(); + + expect(s).toBe("byte"); + }); + + it("TestCreateInstanceWithConstructorResolutionWithCastFunctions", function () { + + __log("TEST: TestCreateInstanceWithConstructorResolutionWithCastFunctions"); + + var n1 = new com.tns.tests.NumericConversionTest(byte(123)); + var s1 = n1.getInit(); + expect(s1).toBe("byte"); + + var n2 = new com.tns.tests.NumericConversionTest(short(123)); + var s2 = n2.getInit(); + expect(s2).toBe("byte"); + + var n3 = new com.tns.tests.NumericConversionTest(long(123)); + var s3 = n3.getInit(); + expect(s3).toBe("byte"); + }); + + it("TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls", function () { + + __log("TEST: TestCreateInstanceWithConstructorResolutionWithValuesFromJavaCalls"); + + var b = java.lang.Byte.parseByte("123"); + var n1 = new com.tns.tests.NumericConversionTest(b); + var s1 = n1.getInit(); + expect(s1).toBe("byte"); + + var i = java.lang.Integer.parseInt("12345"); + var n2 = new com.tns.tests.NumericConversionTest(i); + var s2 = n2.getInit(); + expect(s2).toBe("byte"); + }); + + it("TestCreateInstanceWithConstructorResolutionWithPromotingValueUp", function () { + + __log("TEST: TestCreateInstanceWithConstructorResolutionWithPromotingValueUp"); + + var n = new com.tns.tests.NumericConversionTest(null, short(1)); + var s = n.getInit(); + expect(s).toBe("Object,int"); + }); + + it("TestCreateInstanceWithConstructorResolutionWithPromotingValueDown", function () { + + __log("TEST: TestCreateInstanceWithConstructorResolutionWithPromotingValueDown"); + + var n = new com.tns.tests.NumericConversionTest(null, null, long(1)); + var s = n.getInit(); + expect(s).toBe("Object,Object,short"); + }); + + it("TestCallMethodWithResolutionWithPromotingValueUp", function () { + + __log("TEST: TestCallMethodWithResolutionWithPromotingValueUp"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method1(byte(1)); + expect(s).toBe("short=1"); + }); + + it("TestCallMethodWithResolutionWithPromotingValueDown", function () { + + __log("TEST: TestCallMethodWithResolutionWithPromotingValueDown"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method1(1); + expect(s).toBe("short=1"); + + var n1 = new com.tns.tests.NumericConversionTest(); + var s1 = n1.method1(long((1 << 16) + 2)); + expect(s1).toBe("short=2"); + }); + + it("TestLongCastToFloatConversionWhenThereIsDoubleOverload", function () { + + __log("TEST: TestLongCastToFloatConversionWhenThereIsDoubleOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method2(long(65536 + 2)); + expect(s).toBe("float=65538.0"); + }); + + it("TestByteCastToFloatConversionWhenThereIsDoubleOverload", function () { + + __log("TEST: TestByteCastToFloatConversionWhenThereIsDoubleOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method2(byte(65536 + 2)); + expect(s).toBe("float=2.0"); + }); + + it("TestShortCastToFloatConversionWhenThereIsDoubleOverload", function () { + + __log("TEST: TestShortCastToFloatConversionWhenThereIsDoubleOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method2(short(65536 + 2)); + expect(s).toBe("float=2.0"); + }); + + it("TestDoubleCastWhenThereIsDoubleOverload", function () { + + __log("TEST: TestDoubleCastWhenThereIsDoubleOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method2(double(65536 + 2)); + expect(s).toBe("double=65538.0"); + }); + + it("TestNumberExpressionToFloatConversionWhenThereIsDoubleOverload", function () { + + __log("TEST: TestNumberExpressionToFloatConversionWhenThereIsDoubleOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method2(65536 + 2); + expect(s).toBe("float=65538.0"); + expect(true).toEqual(true); + }); + + it("TestDoubleCastToLongConversionWhenThereIsShortOverload", function () { + + __log("TEST: TestDoubleCastToLongConversionWhenThereIsShortOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method3(double(65536 + 2)); + expect(s).toBe("long=65538"); + }); + + it("TestFloatCastToLongConversionWhenThereIsShortOverload", function () { + + __log("TEST: TestFloatCastToLongConversionWhenThereIsShortOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method3(float(65536 + 2)); + expect(s).toBe("long=65538"); + }); + + it("TestFloatCastToShortConversionWhenThereIsObjectOverload", function () { + + __log("TEST: TestFloatCastToShortConversionWhenThereIsObjectOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method4(float(65536 + 2)); + expect(s).toBe("short=2"); + }); + + it("TestByteCastToShortConversionWhenThereIsObjectOverload", function () { + + __log("TEST: TestByteCastToShortConversionWhenThereIsObjectOverload"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method4(byte(65536 + 2)); + expect(s).toBe("short=2"); + }); + + it("TestResolveMethodWithByteCast", function () { + + __log("TEST: TestResolveMethodWithByteCast"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(byte(65536 + 123)); + expect(s).toBe("byte=123"); + }); + + it("TestResolveMethodWithShortCast", function () { + + __log("TEST: TestResolveMethodWithShortCast"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(short(65536 + 1234)); + expect(s).toBe("short=1234"); + }); + + it("TestResolveMethodWithoutCastFunction", function () { + + __log("TEST: TestResolveMethodWithoutCastFunction"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(123456); + expect(s).toBe("int=123456"); + }); + + it("TestResolveMethodWithLongCast", function () { + + __log("TEST: TestResolveMethodWithLongCast"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(long("123456789012")); + expect(s).toBe("long=123456789012"); + }); + + it("TestResolveMethodWithFloatCast", function () { + + __log("TEST: TestResolveMethodWithFloatCast"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(float(1.23)); + expect(s).toBe("float=1.23"); + }); + + it("TestResolveMethodWithDoubleCast", function () { + + __log("TEST: TestResolveMethodWithDoubleCast"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(double(1)); + expect(s).toBe("double=1.0"); + }); + + it("TestResolveIntMethodWithNumberObjectWithIntArgument", function () { + + __log("TEST: TestResolveIntMethodWithNumberObjectWithIntArgument"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(new Number(1)); + expect(s).toBe("int=1"); + }); + + it("TestResolveIntMethodWithNumberObjectWithDoubleArgument", function () { + + __log("TEST: TestResolveIntMethodWithNumberObjectWithDoubleArgument"); + + var n = new com.tns.tests.NumericConversionTest(); + var s = n.method5(new Number(1.23)); + expect(s).toBe("double=1.23"); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/propertyAccessTests.js b/test-app/assets/app/tests/propertyAccessTests.js deleted file mode 100644 index ed70b043b..000000000 --- a/test-app/assets/app/tests/propertyAccessTests.js +++ /dev/null @@ -1,73 +0,0 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestAccessPropertyGetterStartingWithLowerLetter = function() { - - __log("TEST: TestAccessPropertyStartingWithLowerLetter"); - - var dummyClass = com.tns.tests.DummyClass.class; - - var name1 = dummyClass.getName(); - Assert(name1 === "com.tns.tests.DummyClass", "TestAccessPropertyStartingWithLowerLetter FAILED: Expected value is 'com.tns.tests.DummyClass', actual value=" + name1); - - var name2 = dummyClass.Name; - Assert(name2 === "com.tns.tests.DummyClass", "TestAccessPropertyStartingWithLowerLetter FAILED: Expected value is 'com.tns.tests.DummyClass', actual value=" + name2); - - var name3 = dummyClass.name; - Assert(name3 === "com.tns.tests.DummyClass", "TestAccessPropertyStartingWithLowerLetter FAILED: Expected value is 'com.tns.tests.DummyClass', actual value=" + name3); -} - -var TestAccessPropertySetterStartingWithLowerLetter = function() { - - __log("TEST: TestAccessPropertySetterStartingWithLowerLetter"); - - var dummy = new com.tns.tests.DummyClass(); - - var name = dummy.getName(); - - var newName = name + "!"; - - dummy.name = newName; - - var name1 = dummy.getName(); - - Assert(name1 === newName, "TestAccessPropertySetterStartingWithLowerLetter FAILED: Expected value should be equal to='" + newName + "' but actual value=" + name1); -} - -var TestAccessNonCamelCasePropertyWithoutGetter = function() { - - __log("TEST: TestAccessNonCamelCasePropertyWithoutGetter"); - - var d = new com.tns.tests.DummyClass("test"); - - var name1 = d.getname2(); - Assert(name1 === "test", "TestAccessNonCamelCasePropertyWithoutGetter FAILED: Expected value is 'test', actual value=" + name1); - - var name2 = d.name2; - Assert(name2 === "test", "TestAccessNonCamelCasePropertyWithoutGetter FAILED: Expected value is 'test', actual value=" + name2); -} - -var TestAccessNonCamelCasePropertyWithoutSetter = function() { - - __log("TEST: TestAccessNonCamelCasePropertyWithoutSetter"); - - var dummy = new com.tns.tests.DummyClass(); - - var name = dummy.getname2(); - - var newName = name + "!"; - - dummy.name2 = newName; - - var name1 = dummy.getname2(); - - Assert(name1 === newName, "TestAccessNonCamelCasePropertyWithoutSetter FAILED: Expected value should be equal to='" + newName + "' but actual value=" + name1); -} - -TestAccessPropertyGetterStartingWithLowerLetter(); -TestAccessPropertySetterStartingWithLowerLetter(); -TestAccessNonCamelCasePropertyWithoutGetter(); -TestAccessNonCamelCasePropertyWithoutSetter(); diff --git a/test-app/assets/app/tests/stringConversionTests.js b/test-app/assets/app/tests/stringConversionTests.js index c87b653af..32ff7a7df 100644 --- a/test-app/assets/app/tests/stringConversionTests.js +++ b/test-app/assets/app/tests/stringConversionTests.js @@ -1,98 +1,100 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestCanConvertNonTrivalJavaString1 = function() { - - __log("TEST: TestCanConvertNonTrivalJavaString1"); - - var strConvTest = new com.tns.tests.StringConversionTest(); - - var s = strConvTest.getString(); - - var len = strConvTest.getLength(); - - var isEqualsLength = strConvTest.equalsLength(s); - - Assert(isEqualsLength === true, "TestCanConvertNonTrivalJavaString1 FAILED: Expected value is " + len + ", actual value=" + s.length); - - var isEqualsString = strConvTest.equalsString(s); - - Assert(isEqualsString === true, "TestCanConvertNonTrivalJavaString1 FAILED: Expected value is 'true', actual value=" + isEqualsString); -} - -var TestCanConvertNonTrivalJavaString2 = function() { - - __log("TEST: TestCanConvertNonTrivalJavaString2"); - - var strConvTest = new com.tns.tests.StringConversionTest(); - - var s = strConvTest.getString(1); - - var arr = strConvTest.getStringArr(); - - arr[0] = s; - - var newS = arr[0]; +describe("Tests string conversion ", function () { - var isEqualsLength = strConvTest.equalsLength(newS); + var myCustomEquality = function(first, second) { + return first == second; + }; - Assert(isEqualsLength === true, "TestCanConvertNonTrivalJavaString2 FAILED: Expected value is " + s.length + ", actual value=" + newS.length); + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); - var isEqualsString = strConvTest.equalsString(newS); + it("TestCanConvertNonTrivalJavaString1", function () { + + __log("TEST: TestCanConvertNonTrivalJavaString1"); + + var strConvTest = new com.tns.tests.StringConversionTest(); + + var s = strConvTest.getString(); + + var len = strConvTest.getLength(); + + var isEqualsLength = strConvTest.equalsLength(s); + + expect(isEqualsLength).toBe(true); + + var isEqualsString = strConvTest.equalsString(s); + + expect(isEqualsString).toBe(true); + + }); - Assert(isEqualsString === true, "TestCanConvertNonTrivalJavaString2 FAILED: Expected value is 'true', actual value=" + isEqualsString); -} - -var TestCanConvertNonTrivalJavaString3 = function() { + it("TestCanConvertNonTrivalJavaString2", function () { + - __log("TEST: TestCanConvertNonTrivalJavaString3"); + __log("TEST: TestCanConvertNonTrivalJavaString2"); - var strConvTest = new com.tns.tests.StringConversionTest(); - - var s = strConvTest.s; - - var len = strConvTest.getLength(); - - var isEqualsLength = strConvTest.equalsLength(s); - - Assert(isEqualsLength === true, "TestCanConvertNonTrivalJavaString3 FAILED: Expected value is " + len + ", actual value=" + s.length); - - var isEqualsString = strConvTest.equalsString(s); + var strConvTest = new com.tns.tests.StringConversionTest(); + + var s = strConvTest.getString(1); + + var arr = strConvTest.getStringArr(); + + arr[0] = s; + + var newS = arr[0]; + + var isEqualsLength = strConvTest.equalsLength(newS); + + expect(isEqualsLength).toBe(true); + + var isEqualsString = strConvTest.equalsString(newS); + + expect(isEqualsString).toBe(true); + }); - Assert(isEqualsString === true, "TestCanConvertNonTrivalJavaString3 FAILED: Expected value is 'true', actual value=" + isEqualsString); -} - -var TestCanConvertNonTrivalJavaString4 = function() { + it("TestCanConvertNonTrivalJavaString3", function () { + + __log("TEST: TestCanConvertNonTrivalJavaString3"); - __log("TEST: TestCanConvertNonTrivalJavaString4"); - - var s = ""; - var len = 0; - var isEqualsLength = false; - var isEqualsString = false; - - var MyStringConversionTest = com.tns.tests.StringConversionTest.extend("StringConversionTest77", { - callback: function(str) { - s = str; - len = this.getLength(); - isEqualsLength = this.equalsLength(s); - isEqualsString = this.equalsString(s); - } + var strConvTest = new com.tns.tests.StringConversionTest(); + + var s = strConvTest.s; + + var len = strConvTest.getLength(); + + var isEqualsLength = strConvTest.equalsLength(s); + + expect(isEqualsLength).toBe(true); + + var isEqualsString = strConvTest.equalsString(s); + + expect(isEqualsString).toBe(true); }); - var strConvTest = new MyStringConversionTest(); - - strConvTest.triggerCallback(); - - Assert(isEqualsLength === true, "TestCanConvertNonTrivalJavaString4 FAILED: Expected value is " + len + ", actual value=" + s.length); + it("TestCanConvertNonTrivalJavaString4", function () { - Assert(isEqualsString === true, "TestCanConvertNonTrivalJavaString4 FAILED: Expected value is 'true', actual value=" + isEqualsString); -} - -TestCanConvertNonTrivalJavaString1(); -TestCanConvertNonTrivalJavaString2(); -TestCanConvertNonTrivalJavaString3(); -TestCanConvertNonTrivalJavaString4(); \ No newline at end of file + __log("TEST: TestCanConvertNonTrivalJavaString4"); + + var s = ""; + var len = 0; + var isEqualsLength = false; + var isEqualsString = false; + + var MyStringConversionTest = com.tns.tests.StringConversionTest.extend("StringConversionTest77", { + callback: function(str) { + s = str; + len = this.getLength(); + isEqualsLength = this.equalsLength(s); + isEqualsString = this.equalsString(s); + } + }); + + var strConvTest = new MyStringConversionTest(); + + strConvTest.triggerCallback(); + + expect(isEqualsLength).toBe(true); + + expect(isEqualsString).toBe(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testGC.js b/test-app/assets/app/tests/testGC.js index c613ffc77..8ef3859c2 100644 --- a/test-app/assets/app/tests/testGC.js +++ b/test-app/assets/app/tests/testGC.js @@ -1,204 +1,197 @@ -///START: Extends tests -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - - -// this test has implicit assert in com.tns.Platform.getJavaObjectByID method -function test1() { - - function createObjects(name) { - var c1 = new com.tns.tests.Class1(); +describe("Tests garbage collection", function () { + + var myCustomEquality = function(first, second) { + return first == second; + }; + + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); + + // this test has implicit assert in com.tns.Platform.getJavaObjectByID method + it("test1", function () { + + function createObjects(name) { + var c1 = new com.tns.tests.Class1(); + + var cb1 = new com.tns.tests.Class1.Callback1(name, { + getMessage: function() { + var msg = c1.getMessage(); + return msg; + } + }); + + return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); + } - var cb1 = new com.tns.tests.Class1.Callback1(name, { - getMessage: function() { - var msg = c1.getMessage(); - return msg; - } - }); + expect(createObjects("Callback5")).toBe(true); + expect(createObjects("Callback26")).toBe(true); - return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); - } + gc(); + java.lang.System.gc(); + }); - Assert(createObjects("Callback5") === true, "test1 FAILED: to enqueue first message"); - Assert(createObjects("Callback26") === true, "test1 FAILED: to enqueue second message"); - gc(); - java.lang.System.gc(); -} - - -// this test has implicit assert in com.tns.Platform.getJavaObjectByID method -function test2() { - - function indref1() { - this.class1 = new com.tns.tests.Class1(); - } - indref1.prototype.getMessage = function() { - return "~~~" + this.class1.getMessage(); - } - - function createObjects(name) { - var c1 = new indref1(); + // this test has implicit assert in com.tns.Platform.getJavaObjectByID method + it("test2", function () { - var cb1 = new com.tns.tests.Class1.Callback1(name, { - getMessage: function() { - var msg = c1.getMessage(); - return msg; - } - }); + function indref1() { + this.class1 = new com.tns.tests.Class1(); + } + indref1.prototype.getMessage = function() { + return "~~~" + this.class1.getMessage(); + } + + function createObjects(name) { + var c1 = new indref1(); + + var cb1 = new com.tns.tests.Class1.Callback1(name, { + getMessage: function() { + var msg = c1.getMessage(); + return msg; + } + }); + + return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); + } - return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); - } + expect(createObjects("Callback55")).toBe(true); + expect(createObjects("Callback56")).toBe(true); + gc(); + java.lang.System.gc(); + }); - Assert(createObjects("Callback55") === true, "test2 FAILED: to enqueue first message"); - Assert(createObjects("Callback56") === true, "test2 FAILED: to enqueue second message"); - gc(); - java.lang.System.gc(); -} - - -// this test has implicit assert in com.tns.Platform.getJavaObjectByID method -function test3() { - - function indref2() { - this.helper = new indref2helper(); - } - indref2.prototype.getMessage = function() { - return "---" + this.helper.getMessage(); - } - function indref2helper() { - this.class1 = new com.tns.tests.Class1(); - } - indref2helper.prototype.getMessage = function() { - return "***" + this.class1.getMessage(); - } - - function createObjects(name) { - var c1 = new indref2(); + // this test has implicit assert in com.tns.Platform.getJavaObjectByID method + it("test3", function () { - var cb1 = new com.tns.tests.Class1.Callback1(name, { - getMessage: function() { - var msg = c1.getMessage(); - return msg; - } - }); + function indref2() { + this.helper = new indref2helper(); + } + indref2.prototype.getMessage = function() { + return "---" + this.helper.getMessage(); + } + function indref2helper() { + this.class1 = new com.tns.tests.Class1(); + } + indref2helper.prototype.getMessage = function() { + return "***" + this.class1.getMessage(); + } + + function createObjects(name) { + var c1 = new indref2(); + + var cb1 = new com.tns.tests.Class1.Callback1(name, { + getMessage: function() { + var msg = c1.getMessage(); + return msg; + } + }); + + return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); + } - return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); - } + expect(createObjects("Callback91")).toBe(true); + expect(createObjects("Callback92")).toBe(true); + gc(); + java.lang.System.gc(); + }); - Assert(createObjects("Callback91") === true, "test3 FAILED: to enqueue first message"); - Assert(createObjects("Callback92") === true, "test3 FAILED: to enqueue second message"); - gc(); - java.lang.System.gc(); -} - - -// this test has implicit assert in com.tns.Platform.getJavaObjectByID method -function test4() { - - function indref3() { - this.helper = new indref3helper(); - } - indref3.prototype.getMessage = function() { - return "+++" + this.helper.getMessage(); - } - function indref3helper() { - this._class1 = new com.tns.tests.Class1(); - - Object.defineProperty(this, "class1", { - get: function() { - return this._class1 - } - }); - } - indref3helper.prototype.getMessage = function() { - return "^^^" + this.class1.getMessage(); - } - - function createObjects(name) { - var c1 = new indref3(); + // this test has implicit assert in com.tns.Platform.getJavaObjectByID method + it("test4", function () { - var cb1 = new com.tns.tests.Class1.Callback1(name, { - getMessage: function() { - var msg = c1.getMessage(); - return msg; - } - }); + function indref3() { + this.helper = new indref3helper(); + } + indref3.prototype.getMessage = function() { + return "+++" + this.helper.getMessage(); + } + function indref3helper() { + this._class1 = new com.tns.tests.Class1(); - return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); - } - - Assert(createObjects("Callback1133") === true, "test4 FAILED: to enqueue first message"); - Assert(createObjects("Callback1134") === true, "test4 FAILED: to enqueue second message"); - gc(); - java.lang.System.gc(); -} - - -// this test has implicit assert in com.tns.Platform.getJavaObjectByID method -function test5() { - - function indref4() { - this.helper = new indref4helper(); - } - indref4.prototype.getMessage = function() { - return "&&&" + this.helper.getMessageZZZ(); - } - function indref4helper() { - var _class1 = new com.tns.tests.Class1(); + Object.defineProperty(this, "class1", { + get: function() { + return this._class1 + } + }); + } + indref3helper.prototype.getMessage = function() { + return "^^^" + this.class1.getMessage(); + } + + function createObjects(name) { + var c1 = new indref3(); + + var cb1 = new com.tns.tests.Class1.Callback1(name, { + getMessage: function() { + var msg = c1.getMessage(); + return msg; + } + }); + + return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); + } - __log("indref4helper _class1=" + _class1); + expect(createObjects("Callback1133")).toBe(true); + expect(createObjects("Callback1134")).toBe(true); + gc(); + java.lang.System.gc(); + }); - Object.defineProperty(this, "class1", { - get: function() { - return _class1 - } - ,enumerable: false - }); - } - indref4helper.prototype.getMessageZZZ = function() { - return "```" + this.class1.getMessage(); - } - - function createObjects(name) { - var c1 = new indref4(); + // this test has implicit assert in com.tns.Platform.getJavaObjectByID method + //originally test was commented out + xit("test5", function () { - var cb1 = new com.tns.tests.Class1.Callback1(name, { - getMessage: function() { - var msg = c1.getMessage(); - return msg; - } - }); + function indref4() { + this.helper = new indref4helper(); + } + indref4.prototype.getMessage = function() { + return "&&&" + this.helper.getMessageZZZ(); + } + function indref4helper() { + var _class1 = new com.tns.tests.Class1(); + + __log("indref4helper _class1=" + _class1); - return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); - } - - Assert(createObjects("Callback1178") === true, "test5 FAILED: to enqueue first message"); - Assert(createObjects("Callback1179") === true, "test5 FAILED: to enqueue second message"); - gc(); - java.lang.System.gc(); -} - -function testAccessingStringFieldWontLeak() { - - __log("TEST: testAccessingStringFieldWontLeak"); - - var dummy = new com.tns.tests.DummyClass(); + Object.defineProperty(this, "class1", { + get: function() { + return _class1 + } + ,enumerable: false + }); + } + indref4helper.prototype.getMessageZZZ = function() { + return "```" + this.class1.getMessage(); + } + + function createObjects(name) { + var c1 = new indref4(); + + var cb1 = new com.tns.tests.Class1.Callback1(name, { + getMessage: function() { + var msg = c1.getMessage(); + return msg; + } + }); + + return com.tns.tests.Class1.Class2.printMessageWithDelay(cb1, 5 * 1000); + } + + expect(createObjects("Callback1178")).toBe(true); + expect(createObjects("Callback1179")).toBe(true); + gc(); + java.lang.System.gc(); + }); - for (var i=0; i<10000; i++) - { - var name = dummy.nameField; + it("testAccessingStringFieldWontLeak", function () { - Assert(name === "dummy", "FAILED testAccessingStringFieldWontLeak: Expected vaule='dummy', actual value=" + name); - } -} - + __log("TEST: testAccessingStringFieldWontLeak"); -test1() -test2() -test3() -test4() -//test5() -testAccessingStringFieldWontLeak(); \ No newline at end of file + var dummy = new com.tns.tests.DummyClass(); + + for (var i=0; i<10000; i++) + { + var name = dummy.nameField; + + expect(name).toBe("dummy"); + } + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testIfAbleToRunExternalFile.js b/test-app/assets/app/tests/testIfAbleToRunExternalFile.js index 730c120a9..d72218c36 100644 --- a/test-app/assets/app/tests/testIfAbleToRunExternalFile.js +++ b/test-app/assets/app/tests/testIfAbleToRunExternalFile.js @@ -1,34 +1,29 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var When_file_outside_the_project_folder_is_required_it_should_fail = function() { - - __log("When_file_outside_the_project_folder_is_required_it_should_throw_IllegalAccessException"); - - var illegalAccesExceptionCaught = false; - var fileSeparator = "/"; - var nonExistingFileName = "nonExistingFile"; - var nonExistingFileExtension = ".js"; +describe("Tests running external files", function () { - //create a file in external storage - var pathToExternalStorage = android.os.Environment.getExternalStorageDirectory().toString(); - var appDirectory = new java.io.File(pathToExternalStorage + fileSeparator + nonExistingFileName + nonExistingFileExtension); - appDirectory.mkdirs(); - - try - { - //try to require it with absolute path (requireing files with absolute path should not be possible) - require(pathToExternalStorage + fileSeparator + nonExistingFileName); - } - catch(e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "When_file_outside_the_project_folder_is_required_it_should_fail FAILED: Exception(illegal access) should be thrown"); -} + it("When_file_outside_the_project_folder_is_required_it_should_fail", function () { + + __log("When_file_outside_the_project_folder_is_required_it_should_throw_IllegalAccessException"); -When_file_outside_the_project_folder_is_required_it_should_fail(); + var illegalAccesExceptionCaught = false; + var fileSeparator = "/"; + var nonExistingFileName = "nonExistingFile"; + var nonExistingFileExtension = ".js"; + + //create a file in external storage + var pathToExternalStorage = android.os.Environment.getExternalStorageDirectory().toString(); + var appDirectory = new java.io.File(pathToExternalStorage + fileSeparator + nonExistingFileName + nonExistingFileExtension); + appDirectory.mkdirs(); + + try + { + //try to require it with absolute path (requireing files with absolute path should not be possible) + require(pathToExternalStorage + fileSeparator + nonExistingFileName); + } + catch(e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testWeakRef.js b/test-app/assets/app/tests/testWeakRef.js index 8ffc00ade..f8499d6a1 100644 --- a/test-app/assets/app/tests/testWeakRef.js +++ b/test-app/assets/app/tests/testWeakRef.js @@ -1,157 +1,149 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} +describe("Test WeakRef ", function () { + + it("Test if WeakRef gets cleared after gc", function () { + + __log("TEST: TestWeakRefGetsClearedAfterGC"); + + var wr = new WeakRef({ someProp: 12345 }); + + var val = wr.get().someProp; + expect(val).toBe(12345); + + gc(); + + var val = wr.get(); + expect(val).toBe(null); + }); + + it("Test if WeakRef gets cleared after clear", function () { + + __log("TEST: TestWeakRefGetsClearedAfterClear"); + + var wr = new WeakRef({ someProp: 54321 }); + + var val = wr.get().someProp; + expect(val).toBe(54321); + + wr.clear(); + + var val = wr.get(); + expect(val).toBe(null); + }); + + it("Test if WeakRef can create multiple instances", function () { + + __log("TEST: TestWeakRefCanCreateMultipleInstances"); + + var target = { someProp: 54321 }; + + var wr1 = new WeakRef(target); + var wr2 = new WeakRef(target); + + target = null; + + wr1.clear(); + + var val = wr1.get(); + expect(val).toBe(null); + + val = wr2.get().someProp; + expect(val).toBe(54321); + }); + + it("Test if WeakRef can create multiple instances 2", function () { -var TestWeakRefGetsClearedAfterGC = function() { + __log("TEST: TestWeakRefCanCreateMultipleInstances2"); + + var target = { someProp: 54321 }; + + var wr1 = new WeakRef(target); + var wr2 = new WeakRef(target); + + target = null; + gc(); + + var val1 = wr1.get(); + expect(val1).toBe(null); + + var val2 = wr2.get(); + expect(val2).toBe(null); + }); + + it("Test if WeakRef throws exception when constructed with wrong number of parameters", function () { + + __log("TEST: TestWeakRefThrowsExceptionWhenConstructedWithWrongNumberOfParameters"); + + var exceptionCaught = false; + try + { + new WeakRef(); + } + catch (e) + { + exceptionCaught = true; + } + expect(exceptionCaught).toBe(true); + + exceptionCaught = false; + try + { + new WeakRef(1, 2); + } + catch (e) + { + exceptionCaught = true; + } + expect(exceptionCaught).toBe(true); + + }); - __log("TEST: TestWeakRefGetsClearedAfterGC"); - - var wr = new WeakRef({ someProp: 12345 }); - - var val = wr.get().someProp; - Assert(val === 12345, "TestWeakRefGetsClearedAfterGC FAILED: Expected value '12345', actual value=" + val); - - gc(); - - var val = wr.get(); - Assert(val === null, "TestWeakRefGetsClearedAfterGC FAILED: Expected value 'null', actual value=" + val); -} - -var TestWeakRefGetsClearedAfterClear = function() { - - __log("TEST: TestWeakRefGetsClearedAfterClear"); - - var wr = new WeakRef({ someProp: 54321 }); - - var val = wr.get().someProp; - Assert(val === 54321, "TestWeakRefGetsClearedAfterClear FAILED: Expected value '54321', actual value=" + val); - - wr.clear(); - - var val = wr.get(); - Assert(val === null, "TestWeakRefGetsClearedAfterClear FAILED: Expected value 'null', actual value=" + val); -} - -var TestWeakRefCanCreateMultipleInstances = function() { - - __log("TEST: TestWeakRefCanCreateMultipleInstances"); - - var target = { someProp: 54321 }; - - var wr1 = new WeakRef(target); - var wr2 = new WeakRef(target); - - target = null; - - wr1.clear(); - - var val = wr1.get(); - Assert(val === null, "TestWeakRefCanCreateMultipleInstances FAILED: Expected value 'null', actual value=" + val); - - val = wr2.get().someProp; - Assert(val === 54321, "TestWeakRefCanCreateMultipleInstances FAILED: Expected value '54321', actual value=" + val); -} - -var TestWeakRefCanCreateMultipleInstances2 = function() { - - __log("TEST: TestWeakRefCanCreateMultipleInstances2"); - - var target = { someProp: 54321 }; - - var wr1 = new WeakRef(target); - var wr2 = new WeakRef(target); - - target = null; - gc(); - - var val1 = wr1.get(); - Assert(val1 === null, "TestWeakRefCanCreateMultipleInstances2 FAILED: Expected value (val1) 'null', actual value=" + val1); - - var val2 = wr2.get(); - Assert(val2 === null, "TestWeakRefCanCreateMultipleInstances2 FAILED: Expected value (val2) 'null', actual value=" + val2); -} - -var TestWeakRefThrowsExceptionWhenConstructedWithWrongNumberOfParameters = function() { - - __log("TEST: TestWeakRefThrowsExceptionWhenConstructedWithWrongNumberOfParameters"); - - var exceptionCaught = false; - try - { - new WeakRef(); - } - catch (e) - { - exceptionCaught = true; - } - Assert(exceptionCaught === true, "TestWeakRefThrowsExceptionWhenConstructedWithWrongNumberOfParameters FAILED: Expected value 'true'"); - - exceptionCaught = false; - try - { - new WeakRef(1, 2); - } - catch (e) - { - exceptionCaught = true; - } - Assert(exceptionCaught === true, "TestWeakRefThrowsExceptionWhenConstructedWithWrongNumberOfParameters FAILED: Expected value 'true'"); -} - -var TestWeakRefThrowsExceptionWhenConstructedWithNonObject = function() { - - __log("TEST: TestWeakRefThrowsExceptionWhenConstructedWithNonObject"); - - var exceptionCaught = false; - try - { - new WeakRef(1); - } - catch (e) - { - exceptionCaught = true; - } - Assert(exceptionCaught === true, "TestWeakRefThrowsExceptionWhenConstructedWithNonObject FAILED: Expected value 'true'"); - - exceptionCaught = false; - try - { - new WeakRef(false); - } - catch (e) - { - exceptionCaught = true; - } - Assert(exceptionCaught === true, "TestWeakRefThrowsExceptionWhenConstructedWithNonObject FAILED: Expected value 'true'"); + it("Test if WeakRef throws exception when constructed with non object", function () { + + __log("TEST: TestWeakRefThrowsExceptionWhenConstructedWithNonObject"); + + var exceptionCaught = false; + try + { + new WeakRef(1); + } + catch (e) + { + exceptionCaught = true; + } + expect(exceptionCaught).toBe(true); + + exceptionCaught = false; + try + { + new WeakRef(false); + } + catch (e) + { + exceptionCaught = true; + } + expect(exceptionCaught).toBe(true); - exceptionCaught = false; - try - { - new WeakRef(null); - } - catch (e) - { - exceptionCaught = true; - } - Assert(exceptionCaught === true, "TestWeakRefThrowsExceptionWhenConstructedWithNonObject FAILED: Expected value 'true'"); + exceptionCaught = false; + try + { + new WeakRef(null); + } + catch (e) + { + exceptionCaught = true; + } + expect(exceptionCaught).toBe(true); - exceptionCaught = false; - try - { - new WeakRef(undefined); - } - catch (e) - { - exceptionCaught = true; - } - Assert(exceptionCaught === true, "TestWeakRefThrowsExceptionWhenConstructedWithNonObject FAILED: Expected value 'true'"); -} + exceptionCaught = false; + try + { + new WeakRef(undefined); + } + catch (e) + { + exceptionCaught = true; + } + expect(exceptionCaught).toBe(true); + }); +}); -TestWeakRefGetsClearedAfterGC(); -TestWeakRefGetsClearedAfterClear(); -TestWeakRefCanCreateMultipleInstances(); -TestWeakRefCanCreateMultipleInstances2(); -TestWeakRefThrowsExceptionWhenConstructedWithWrongNumberOfParameters(); -TestWeakRefThrowsExceptionWhenConstructedWithNonObject(); diff --git a/test-app/assets/app/tests/tests.js b/test-app/assets/app/tests/tests.js index 1034c234c..b370f47aa 100644 --- a/test-app/assets/app/tests/tests.js +++ b/test-app/assets/app/tests/tests.js @@ -1,1868 +1,1801 @@ -///START: Extends tests -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var objectToString = function(o){ - var str=''; - - for(var p in o){ - if(typeof o[p] == 'string'){ - str+= p + ': ' + o[p]+';'; - }else{ - str+= p + ': { ' + objectToString(o[p]) + ' } '; - } - } - - return str; -}; - -var When_extending_a_class_two_times = function() { - - __log("TEST: When_extending_a_class_two_times"); - - __log("TEST: Creating MyButton"); - var MyButton = com.tns.tests.Button1.extend("MyButton", { - toString : function() { - return "button1"; - } - }); - - __log("TEST: Calling MyButton ctor"); - var button1 = new MyButton(); - __log("TEST: Calling button1 toString"); - var button1Label = button1.toString(); - button1.setLabel("first button"); - - __log("TEST: Creating MyButton2 class"); - var MyButton2 = new com.tns.tests.Button1.extend("MyButton", { - toString : function() { - return "button2"; - }}); - - var button2 = new MyButton2(); - button2.setLabel("second button"); - var button2Label = button2.toString(); - - __log("but1=" + button1Label + ", but2=" + button2Label); - - Assert(button1 != button2 && button1Label == "button1" && button2Label == "button2", "FAILED: When_extending_a_class_two_times"); - - var button1LabelAfterButton2Created = button1.toString(); - Assert(button1 != button2 && button1LabelAfterButton2Created == "button1" && button2Label == "button2", "FAILED: When_extending_a_class_two_times"); -} +describe("Tests ", function () { -var When_extending_a_class_two_times_with_no_extend_names = function() { + var objectToString = function(o){ + var str=''; + + for(var p in o){ + if(typeof o[p] == 'string'){ + str+= p + ': ' + o[p]+';'; + }else{ + str+= p + ': { ' + objectToString(o[p]) + ' } '; + } + } + + return str; + }; - __log("TEST: When_extending_a_class_two_times_with_no_extend_names"); + var myCustomEquality = function(first, second) { + return first == second; + }; - __log("TEST: Creating MyButton"); - var MyButton = com.tns.tests.Button1.extend({ - toString : function() { - return "button1"; - } + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); }); - __log("TEST: Calling MyButton ctor"); - var button1 = new MyButton(); - __log("TEST: Calling button1 toString"); - var button1Label = button1.toString(); - button1.setLabel("first button"); - - __log("TEST: Creating MyButton2 class"); - var MyButton2 = new com.tns.tests.Button1.extend({ - toString : function() { - return "button2"; - }}); - - var button2 = new MyButton2(); - button2.setLabel("second button"); - var button2Label = button2.toString(); - - __log("but1=" + button1Label + ", but2=" + button2Label); - - Assert(button1 != button2 && button1Label == "button1" && button2Label == "button2", "FAILED: When_extending_a_class_two_times_with_no_extend_names"); - - var button1LabelAfterButton2Created = button1.toString(); - Assert(button1 != button2 && button1LabelAfterButton2Created == "button1" && button2Label == "button2", "FAILED: When_extending_a_class_two_times_with_no_extend_names"); -} - -var When_implementing_an_interface_with_new_the_overrides_should_work = function() { - __log("TEST: When_implementing_an_interface_with_new__the_overrides_should_work"); - - var MyButton = new com.tns.tests.Button1.extend("MyButton60", { - toString : function() { - return "button1"; - } + it("When_extending_a_class_two_times", function () { + + __log("TEST: When_extending_a_class_two_times"); + + __log("TEST: Creating MyButton"); + var MyButton = com.tns.tests.Button1.extend("MyButton", { + toString : function() { + return "button1"; + } + }); + + __log("TEST: Calling MyButton ctor"); + var button1 = new MyButton(); + __log("TEST: Calling button1 toString"); + var button1Label = button1.toString(); + button1.setLabel("first button"); + + __log("TEST: Creating MyButton2 class"); + var MyButton2 = new com.tns.tests.Button1.extend("MyButton", { + toString : function() { + return "button2"; + }}); + + var button2 = new MyButton2(); + button2.setLabel("second button"); + var button2Label = button2.toString(); + + __log("but1=" + button1Label + ", but2=" + button2Label); + + var shouldBeTrue = (button1 != button2 && button1Label == "button1" && button2Label == "button2"); + + expect(shouldBeTrue).toBe(true); + + var button1LabelAfterButton2Created = button1.toString(); + shouldBeTrue = (button1 != button2 && button1LabelAfterButton2Created == "button1" && button2Label == "button2"); + + expect(shouldBeTrue).toBe(true); }); - var button1 = new MyButton(); - var buttonClicked = false; - button1.setOnClickListener(new android.view.View.OnClickListener("MyClickListener", { - onClick : function() { - buttonClicked = true; - } - })); - button1.click(null); - - Assert(buttonClicked == true, "FAILED: When_implementing_an_interface_with_new__the_overrides_should_work"); -} -var When_calling_instanceof_on_field_result_it_should_work = function() { - __log("TEST: When_calling_instanceof_on_field_result_it_should_work"); - - var MyButton = new com.tns.tests.Button1.extend("MyButton81", { - toString : function() { - return "button1"; - }, + it("When_extending_a_class_two_times_with_no_extend_names", function () { + + __log("TEST: When_extending_a_class_two_times_with_no_extend_names"); + + __log("TEST: Creating MyButton"); + var MyButton = com.tns.tests.Button1.extend({ + toString : function() { + return "button1"; + } + }); + + __log("TEST: Calling MyButton ctor"); + var button1 = new MyButton(); + __log("TEST: Calling button1 toString"); + var button1Label = button1.toString(); + button1.setLabel("first button"); + + __log("TEST: Creating MyButton2 class"); + var MyButton2 = new com.tns.tests.Button1.extend({ + toString : function() { + return "button2"; + }}); + + var button2 = new MyButton2(); + button2.setLabel("second button"); + var button2Label = button2.toString(); + + __log("but1=" + button1Label + ", but2=" + button2Label); + + var shouldBeTrue = (button1 != button2 && button1Label == "button1" && button2Label == "button2"); + + expect(shouldBeTrue).toBe(true); + + var button1LabelAfterButton2Created = button1.toString(); + shouldBeTrue = (button1 != button2 && button1LabelAfterButton2Created == "button1" && button2Label == "button2"); + + expect(shouldBeTrue).toBe(true); }); - var button1 = new MyButton(); - var dummyObject = button1.DummyClassAsObjectField; - - var isInstanceOf = dummyObject instanceof com.tns.tests.DummyClass; - Assert(isInstanceOf == true, "FAILED: When_calling_instanceof_on_field_result_it_should_work."); -} - -var When_calling_instanceof_on_method_result_it_should_work = function() { - __log("TEST: When_calling_instanceof_on_method_result_it_should_work"); - - var MyButton = new com.tns.tests.Button1.extend("MyButton98", { - toString : function() { - return "button1"; - }, + it("When_implementing_an_interface_with_new_the_overrides_should_work", function () { + + __log("TEST: When_implementing_an_interface_with_new__the_overrides_should_work"); + + var MyButton = new com.tns.tests.Button1.extend("MyButton60", { + toString : function() { + return "button1"; + } + }); + + var button1 = new MyButton(); + var buttonClicked = false; + button1.setOnClickListener(new android.view.View.OnClickListener("MyClickListener", { + onClick : function() { + buttonClicked = true; + } + })); + button1.click(null); + + expect(buttonClicked).toEqual(true); }); - var button1 = new MyButton(); - var dummy = button1.getDummy(); - - var isInstanceOf = dummy instanceof com.tns.tests.DummyClass; - Assert(isInstanceOf == true, "FAILED: When_calling_instanceof_on_method_result_it_should_work."); -} - -var When_calling_instanceof_on_method_argument_it_should_work = function() { - __log("TEST: When_calling_instanceof_on_method_argument_it_should_work"); - - var isInstanceOf; - - var MyButton = new com.tns.tests.Button1.extend("MyButton115", { - toString : function() { - return "button1"; - }, - - methodDummyClassAsObjectInArgs: function(object) { - isInstanceOf = object instanceof com.tns.tests.DummyClass; - } + it("When_calling_instanceof_on_field_result_it_should_work", function () { + + __log("TEST: When_calling_instanceof_on_field_result_it_should_work"); + + var MyButton = new com.tns.tests.Button1.extend("MyButton81", { + toString : function() { + return "button1"; + }, + }); + + var button1 = new MyButton(); + var dummyObject = button1.DummyClassAsObjectField; + + var isInstanceOf = dummyObject instanceof com.tns.tests.DummyClass; + + expect(isInstanceOf).toEqual(true); }); - var button1 = new MyButton(); - button1.callMethodDummyClassAsObjectInArgs(); - - Assert(isInstanceOf == true, "FAILED: When_calling_instanceof_on_method_argument_it_should_work."); -} - -var When_calling_instanceof_on_interface_it_should_work = function() { - - __log("NOT WORKING: When_calling_instanceof_on_interface_it_should_work"); - return; - - __log("TEST: When_calling_instanceof_on_interface_it_should_work"); - - var interfaceInstance = new android.view.View.OnClickListener("ClickListener", { - onClick : function() { - buttonClicked = true; - } + it("When_calling_instanceof_on_method_result_it_should_work", function () { + + __log("TEST: When_calling_instanceof_on_method_result_it_should_work"); + + var MyButton = new com.tns.tests.Button1.extend("MyButton98", { + toString : function() { + return "button1"; + }, + }); + + var button1 = new MyButton(); + var dummy = button1.getDummy(); + + var isInstanceOf = dummy instanceof com.tns.tests.DummyClass; + + expect(isInstanceOf).toEqual(true); }); - var secondInterfaceInstance = new android.view.View.OnClickListener("ClickListener", { - onClick : function() { - buttonClicked = true; - } + it("When_calling_instanceof_on_method_argument_it_should_work", function () { + + __log("TEST: When_calling_instanceof_on_method_argument_it_should_work"); + + var isInstanceOf; + + var MyButton = new com.tns.tests.Button1.extend("MyButton115", { + toString : function() { + return "button1"; + }, + + methodDummyClassAsObjectInArgs: function(object) { + isInstanceOf = object instanceof com.tns.tests.DummyClass; + } + }); + + var button1 = new MyButton(); + button1.callMethodDummyClassAsObjectInArgs(); + + expect(isInstanceOf).toEqual(true); }); - var thirdInterfaceInstance = new android.view.View.OnClickListener("ClickListener", { - onClick : function() { - buttonClicked = true; - } + //originally wasn't run + it("When_calling_instanceof_on_interface_it_should_work", function () { + + __log("TEST: When_calling_instanceof_on_interface_it_should_work"); + + var interfaceInstance = new android.view.View.OnClickListener("ClickListener", { + onClick : function() { + buttonClicked = true; + } + }); + + var secondInterfaceInstance = new android.view.View.OnClickListener("ClickListener", { + onClick : function() { + buttonClicked = true; + } + }); + + var thirdInterfaceInstance = new android.view.View.OnClickListener("ClickListener", { + onClick : function() { + buttonClicked = true; + } + }); + + //__log("Object get PrototypeOf" + Object.getPrototypeOf(interfaceInstance).toString()); + //__log("Object get PrototypeOf" + Object.getPrototypeOf(secondInterfaceInstance).toString()); + + var isInstanceOfOnClickListener = interfaceInstance instanceof android.view.View.OnClickListener; + var secondIsInstanceOfOnClickListener = secondInterfaceInstance instanceof android.view.View.OnClickListener; + var thirdIsInstanceOfOnClickListener = thirdInterfaceInstance instanceof android.view.View.OnClickListener; + + expect(isInstanceOfOnClickListener).toEqual(true); + expect(secondIsInstanceOfOnClickListener).toEqual(true); + expect(thirdIsInstanceOfOnClickListener).toEqual(true); }); - //__log("Object get PrototypeOf" + Object.getPrototypeOf(interfaceInstance).toString()); - //__log("Object get PrototypeOf" + Object.getPrototypeOf(secondInterfaceInstance).toString()); - - var isInstanceOfOnClickListener = interfaceInstance instanceof android.view.View.OnClickListener; - var secondIsInstanceOfOnClickListener = secondInterfaceInstance instanceof android.view.View.OnClickListener; - var thirdIsInstanceOfOnClickListener = thirdInterfaceInstance instanceof android.view.View.OnClickListener; - __log("isInstanceOfOnClickListener: " + isInstanceOfOnClickListener + " secondIsInstanceOfOnClickListener:" + secondIsInstanceOfOnClickListener + " thirdIsInstanceOfOnClickListener: " + thirdIsInstanceOfOnClickListener); - - Assert(isInstanceOfOnClickListener == true, "FAILED: When_calling_instanceof_on_interface_it_should_work. Actual isInstanceOfOnClickListener: " + isInstanceOfOnClickListener); - Assert(secondIsInstanceOfOnClickListener == true, "FAILED 11: When_calling_instanceof_on_interface_it_should_work. Actual secondIsInstanceOfOnClickListener: " + secondIsInstanceOfOnClickListener); -} + it("When_calling_instanceof_it_should_work", function () { + + __log("TEST: When_calling_instanceof_it_should_work"); + + var MyButton = com.tns.tests.Button1.extend("MyButton148", { + toString : function() { + return "button1"; + } + }); -var When_calling_instanceof_it_should_work = function() { - __log("TEST: When_calling_instanceof_it_should_work"); - - var MyButton = com.tns.tests.Button1.extend("MyButton148", { - toString : function() { - return "button1"; - } + var button1 = new MyButton(); + + var isInstanceOfMyButton = button1 instanceof MyButton; + var isInstanceOfButton1 = button1 instanceof com.tns.tests.Button1; + + expect(isInstanceOfMyButton).toEqual(true); + expect(isInstanceOfButton1).toBe(true); }); - - var button1 = new MyButton(); - - var isInstanceOfMyButton = button1 instanceof MyButton; - var isInstanceOfButton1 = button1 instanceof com.tns.tests.Button1; - Assert(isInstanceOfMyButton == true, "FAILED: When_calling_instanceof_it_should_work. The button should be instanceof MyButton"); - - Assert(isInstanceOfButton1 === true, "FAILED: When_calling_instanceof_it_should_work. The button should be instanceof Button1"); -} - - -var When_accessing_a_property_it_should_call_the_get_and_set_methods_respectivelly = function() { - __log("TEST: When_calling_instance_and_static_member_with_same_name_the_calls_should_succeed"); - var MyButton = com.tns.tests.Button1.extend("MyButton167", { - toString : function() { - return "button1"; + it("When_calling_instance_and_static_member_with_same_name_the_calls_should_succeed", function () { + + __log("TEST: When_calling_instance_and_static_member_with_same_name_the_calls_should_succeed"); + var MyButton = com.tns.tests.Button1.extend("MyButton213", { + toString : function() { + return "button1"; + } + }); + + var button1 = new MyButton(); + + var exceptionCaught = false; + try { + MyButton.someMethod(1, "hello"); + button1.someMethod(1, "hello"); + button1.someMethod(1, new java.lang.Object()); } + catch(e) { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(false); }); - - var button1 = new MyButton(); - - //call static method from instance - var prop = button1.IMAGE_ID_PROP; - - Assert(prop === "image id prop", "FAILED (1): When_accessing_a_property_it_should_call_the_get_and_set_methods_respectivelly"); - - button1.IMAGE_ID_PROP = "new value"; + it("When_calling_toString_on_an_java_object_it_should_call_the_java_method", function () { - prop = button1.IMAGE_ID_PROP; - - Assert(prop === "new value", "FAILED (2): When_accessing_a_property_it_should_call_the_get_and_set_methods_respectivelly"); -} - -var When_accessing_a_bool_property_it_should_call_the_is_and_set_methods_respectivelly = function() { - __log("TEST: When_accessing_a_bool_property_it_should_call_the_is_and_set_methods_respectivelly"); - var MyButton = com.tns.tests.Button1.extend("MyButton190", { - toString : function() { - return "button1"; - } + __log("TEST: When_calling_toString_on_an_java_object_it_should_call_the_java_method"); + var instance = new com.tns.tests.DummyClass(); + var s = instance.toString(); + + expect(s.indexOf("com.tns.tests.DummyClass")).not.toEqual(-1); }); - - var button1 = new MyButton(); - - //call static method from instance - var prop = button1.IMAGE_ID_BOOL_PROP; - - Assert(prop == false, "FAILED: When_accessing_a_bool_property_it_should_call_the_is_and_set_methods_respectivelly"); + it("When_calling_toString_on_an_java_object_that_has_overriden_toString_in_js_it_should_call_the_js_method", function () { + + __log("TEST: When_calling_toString_on_an_java_object_that_has_overriden_toString_in_js_it_should_call_the_js_method"); + var MyButton = com.tns.tests.Button1.extend("MyButton240", { + toString : function() { + return "button1"; + } + }); + + var instance = new MyButton(); + var s = instance.toString(); + + expect(s).toBe("button1"); + }); - button1.IMAGE_ID_BOOL_PROP = true; + it("When_extending_a_class_two_times_without_second_implementation_object", function () { + + __log("TEST: When_extending_a_class_two_times_without_second_implementation_object"); + + var MyButton = com.tns.tests.Button1.extend("MyButton257", { + toString : function() { + return "button1"; + } + }); + + var button1 = new MyButton(); + var button1Label = button1.toString(); - prop = button1.IMAGE_ID_BOOL_PROP; + var button2 = new com.tns.tests.Button1(); + var button2Label = button2.toString(); + + __log("button1Label=" + button1Label + ", button2Label=" + button2Label); + var shouldBeTrue = (button1 !== button2 && button1Label !== button2Label); + + expect(shouldBeTrue).toBe(true); + + var button1PostButton2CreationLabel = button1.toString(); + + expect(button1Label).toBe(button1PostButton2CreationLabel); + }); - Assert(prop == true, "FAILED: When_accessing_a_bool_property_it_should_call_the_is_and_set_methods_respectivelly"); -} + it("When__calling_super_method_using_the_prototype_property_of_a_function_it_should_call_the_super_method", function () { + + __log("TEST: When__calling_super_method_using_the_prototype_property_of_a_function_it_should_call_the_super_method"); -var When_calling_instance_and_static_member_with_same_name_the_calls_should_succeed = function() { - __log("TEST: When_calling_instance_and_static_member_with_same_name_the_calls_should_succeed"); - var MyButton = com.tns.tests.Button1.extend("MyButton213", { - toString : function() { - return "button1"; - } + var button1 = new com.tns.tests.Button1(); + var prop = com.tns.tests.Button1.prototype.getIMAGE_ID_PROP.call(button1); + + expect(prop).toBe("image id prop"); }); - - var button1 = new MyButton(); - - //call static method from extended object - MyButton.someMethod(1, "hello"); - //call static method from instance - button1.someMethod(1, "hello"); - - //call instance method - button1.someMethod(1, new java.lang.Object()); -} - - -var When_calling_toString_on_an_java_object_it_should_call_the_java_method = function() { - __log("TEST: When_calling_toString_on_an_java_object_it_should_call_the_java_method"); - var instance = new com.tns.tests.DummyClass(); - var s = instance.toString(); - Assert(s.indexOf("com.tns.tests.DummyClass") != -1, "FAILED: When_calling_toString_on_an_java_object_it_should_call_the_java_method. Actual value: " + instance.toString()); -} + it("When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method", function () { + + __log("TEST: When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method"); -var When_calling_toString_on_an_java_object_that_has_overriden_toString_in_js_it_should_call_the_js_method = function() { - __log("TEST: When_calling_toString_on_an_java_object_that_has_overriden_toString_in_js_it_should_call_the_js_method"); - var MyButton = com.tns.tests.Button1.extend("MyButton240", { - toString : function() { - return "button1"; - } + var MyButton = com.tns.tests.Button1.extend("MyButton289", {}); + var button1 = new MyButton(); + var prop = com.tns.tests.Button1.prototype.getIMAGE_ID_PROP.call(button1); + + expect(prop).toBe("image id prop"); }); - var instance = new MyButton(); - var s = instance.toString(); - Assert(s === "button1", "FAILED: When_calling_toString_on_an_java_object_that_has_overriden_toString_in_js_it_should_call_the_js_method. Actual value: " + instance.toString()); -} + it("When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method2", function () { + + __log("TEST: When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method2"); -var When_extending_a_class_two_times_without_second_implementation_object = function() { - __log("TEST: When_extending_a_class_two_times_without_second_implementation_object"); - - var MyButton = com.tns.tests.Button1.extend("MyButton257", { - toString : function() { - return "button1"; - } + var MyButton = com.tns.tests.Button1.extend("MyButton294", { + getIMAGE_ID_PROP: function() { return ""; } + }); + var button1 = new MyButton(); + var prop = com.tns.tests.Button1.prototype.getIMAGE_ID_PROP.call(button1); + + expect(prop).toBe("image id prop"); }); - var button1 = new MyButton(); - var button1Label = button1.toString(); - - var button2 = new com.tns.tests.Button1(); - var button2Label = button2.toString(); - - __log("button1Label=" + button1Label + ", button2Label=" + button2Label); - Assert(button1 !== button2 && button1Label !== button2Label, "FAILED: When_extending_a_class_two_times_without_second_implementation_object"); + it("When_extending_a_class_and_calling_super_toString", function () { + + //__log("//TODO: NOT WORKING: super method calls are not working correctly. Tests fails with FAILED: When_extending_a_class_and_calling_super_toString. Actual: com.tns.com.tns.tests.Button1-MyButton305@52854640 Expected: com.tns.tests.Button1@"); + //return; + + __log("TEST: When_extending_a_class_and_calling_super_toString"); + + var MyButton = com.tns.tests.Button1.extend("MyButton", { + toString : function() { + return this.super.toString() + this.super.echo("success"); + }, + + echo : function(s) { + return "fail"; + } + }); + + var button1 = new MyButton(); + var button1Label = button1.toString(); + + expect(button1Label.indexOf("com.tns.tests.Button1-")).not.toEqual(-1); + expect(button1Label.indexOf("MyButton")).not.toEqual(-1); + expect(button1Label.indexOf("success")).not.toEqual(-1); + + }); + it("When_extending_a_class_and_calling_super_method_it_should_work", function () { + + __log("TEST: When_extending_a_class_and_calling_super_method_it_should_work"); + var MyButton = com.tns.tests.Button1.extend("MyButton318", { + toString : function() { + return "toString overriden"; + }, + + getIMAGE_ID_PROP : function() { + return this.super.getIMAGE_ID_PROP() + "!"; + } + }); + var button1 = new MyButton(); + var button1SuperToString = button1.toString(); + + expect(button1SuperToString).toBe("toString overriden"); + + var IMAGE_ID_PROP_Result = button1.getIMAGE_ID_PROP(); + + expect(IMAGE_ID_PROP_Result).toBe("image id prop!"); + }); - var button1PostButton2CreationLabel = button1.toString(); - Assert(button1Label === button1PostButton2CreationLabel, "FAILED: When_extending_a_class_two_times_without_second_implementation_object"); -} - -var When__calling_super_method_using_the_prototype_property_of_a_function_it_should_call_the_super_method = function() { - __log("TEST: When__calling_super_method_using_the_prototype_property_of_a_function_it_should_call_the_super_method"); - - var button1 = new com.tns.tests.Button1(); - var prop = com.tns.tests.Button1.prototype.getIMAGE_ID_PROP.call(button1); + it("When_accessing_static_members_on_an_extended_class", function () { + + __log("TEST: When_accessing_static_members_on_an_extended_class"); + + var MyButton = com.tns.tests.Button1.extend("MyButton341", { + hashCode : function() { + return 5454; + } + }); + + var MyButton2 = com.tns.tests.Button1.extend("MyButton347", { + hashCode : function() { + return 1212; + } + }); + + var setValue = 4; + MyButton.setMyStaticIntField(setValue); + var readValue = MyButton2.getMyStaticIntField(); + + expect(readValue).toEqual(setValue); + + var readValue = com.tns.tests.Button1.getMyStaticIntField(); + + expect(readValue).toEqual(setValue); + }); - Assert(prop === "image id prop", "FAILED: When__calling_super_method_using_the_prototype_property_of_a_function_it_should_call_the_super_method"); -} - -var When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method = function() { - __log("TEST: When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method"); + it("When_implementing_an_interface_with_new__the_overrides_should_work", function () { + + __log("TEST: When_implementing_an_interface_with_new__the_overrides_should_work"); + + var MyButton = new com.tns.tests.Button1.extend({ + toString : function() { + return "button1"; + } + }); + + var button1 = new MyButton(); + var buttonClicked = false; - var MyButton = com.tns.tests.Button1.extend("MyButton289", {}); - var button1 = new MyButton(); - var prop = com.tns.tests.Button1.prototype.getIMAGE_ID_PROP.call(button1); - Assert(prop === "image id prop", "FAILED: When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method"); -} + button1.setOnClickListener(new android.view.View.OnClickListener({ + onClick : function() { + buttonClicked = true; + } + })); -var When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method2 = function() { - __log("TEST: When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method2"); + button1.click(null); - var MyButton = com.tns.tests.Button1.extend("MyButton294", { - getIMAGE_ID_PROP: function() { return ""; } + expect(buttonClicked).toEqual(true); }); - var button1 = new MyButton(); - var prop = com.tns.tests.Button1.prototype.getIMAGE_ID_PROP.call(button1); - Assert(prop === "image id prop", "FAILED: When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method2"); -} - -var When_extending_a_class_and_calling_super_toString = function() { - //__log("//TODO: NOT WORKING: super method calls are not working correctly. Tests fails with FAILED: When_extending_a_class_and_calling_super_toString. Actual: com.tns.com.tns.tests.Button1-MyButton305@52854640 Expected: com.tns.tests.Button1@"); - //return; - __log("TEST: When_extending_a_class_and_calling_super_toString"); - - var MyButton = com.tns.tests.Button1.extend("MyButton", { - toString : function() { - return this.super.toString() + this.super.echo("success"); - }, + it("When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance", function () { + + __log("TEST: When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance"); - echo : function(s) { - return "fail"; + var MyButton = new com.tns.tests.Button1.extend("MyButton381", { + toString : function() { + return "button1"; + } + }); + + var button1 = new MyButton(); + var dummy = button1.getDummy(); + + var exceptionCaught = false; + try { + var res = dummy.dummyMethod(123); //this will fail if button2 is not valid proxy object and properly exposed to js } - }); - - var button1 = new MyButton(); - var button1Label = button1.toString(); - Assert(button1Label.indexOf("com.tns.tests.Button1-") != -1, "FAILED: When_extending_a_class_and_calling_super_toString. Actual: " + button1Label + " Expected to contain: com.tns.tests.Button1-"); - Assert(button1Label.indexOf("MyButton") != -1, "FAILED: When_extending_a_class_and_calling_super_toString. Actual: " + button1Label + " Expected to contain: -MyButton"); - Assert(button1Label.indexOf("success") != -1, "FAILED: When_extending_a_class_and_calling_super_toString. Actual: " + button1Label + " Expected: com.tns.tests.Button1"); -} - -var When_extending_a_class_and_calling_super_method_it_should_work = function() { - __log("TEST: When_extending_a_class_and_calling_super_method_it_should_work"); - var MyButton = com.tns.tests.Button1.extend("MyButton318", { - toString : function() { - return "toString overriden"; - }, - - getIMAGE_ID_PROP : function() { - return this.super.getIMAGE_ID_PROP() + "!"; + catch (e) { + exceptionCaught = true; } + + expect(exceptionCaught).toBe(false); }); - var button1 = new MyButton(); - var button1SuperToString = button1.toString(); - - Assert(button1SuperToString === "toString overriden", "FAILED (1): When_extending_a_class_and_calling_super_method_it_should_work"); - - var IMAGE_ID_PROP_Result = button1.getIMAGE_ID_PROP(); - - Assert(IMAGE_ID_PROP_Result === "image id prop!", "FAILED (2): When_extending_a_class_and_calling_super_method_it_should_work"); -} + it("When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type", function () { -var When_accessing_static_members_on_an_extended_class = function() { - __log("TEST: When_accessing_static_members_on_an_extended_class"); - - var MyButton = com.tns.tests.Button1.extend("MyButton341", { - hashCode : function() { - return 5454; - } + __log("TEST: When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); + + var Button = new com.tns.tests.Button1.extend("MyButton397", { + toString : function() { + return "button1"; + } + }); + + var button = new Button(); + var object = button.getDummyClassAsObject(); + var name = object.getName(); + + expect(name).toEqual("dummy"); }); - var MyButton2 = com.tns.tests.Button1.extend("MyButton347", { - hashCode : function() { - return 1212; - } + it("When_a_java_field_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type", function () { + + __log("TEST: When_a_java_field_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); + + var Button = new com.tns.tests.Button1.extend("MyButton413", { + toString : function() { + return "button1"; + } + }); + + var button = new Button(); + var object = button.DummyClassAsObjectField; + var name = object.getName(); + + expect(name).toEqual("dummy"); }); - var setValue = 4; - MyButton.setMyStaticIntField(setValue); - var readValue = MyButton2.getMyStaticIntField(); - - Assert(readValue == setValue, "FAILED: When_accessing_static_members_on_an_extended_class"); - - var readValue = com.tns.tests.Button1.getMyStaticIntField(); - - Assert(readValue == setValue, "FAILED: When_accessing_static_members_on_an_extended_class"); -} - -var When_implementing_an_interface_with_new__the_overrides_should_work = function() { - __log("TEST: When_implementing_an_interface_with_new__the_overrides_should_work"); - - var MyButton = new com.tns.tests.Button1.extends({ - toString : function() { - return "button1"; - } + it("When_a_java_argument_is_passed_to_js_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type", function () { + + __log("TEST: When_a_java_argument_is_passed_to_js_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); + + var name = ""; + var Button = new com.tns.tests.Button1.extend("MyButton418", { + toString : function() { + return "button1"; + }, + + methodDummyClassAsObjectInArgs: function(object) { + name = object.getName(); + __log("The actual name is " + name); + } + }); + + var button = new Button(); + var object = button.callMethodDummyClassAsObjectInArgs(); + + expect(name).toEqual("dummy"); }); - var button1 = new MyButton(); - var buttonClicked = false; - button1.setOnClickListener(new android.view.View.OnClickListener({ - onClick : function() { - buttonClicked = true; - } - })); - button1.click(null); - - Assert(buttonClicked == true, "FAILED: When_implementing_an_interface_with_new__the_overrides_should_work"); -} - -var When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance = function() { - __log("TEST: When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance"); - - var MyButton = new com.tns.tests.Button1.extend("MyButton381", { - toString : function() { - return "button1"; - } + it("When_a_java_object_is_returned_from_indexer_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type", function () { + + __log("TEST: When_a_java_object_is_returned_from_indexer_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); + + var Button = new com.tns.tests.Button1.extend("MyButton450", { + toString : function() { + return "button1"; + } + }); + + var button = new Button(); + var arrayOfObjects = button.getDummyClassAsObjectArray(); + var name = arrayOfObjects[0].getName(); + + expect(name).toEqual("dummy"); }); - var button1 = new MyButton(); - var dummy = button1.getDummy(); - var res = dummy.dummyMethod(123); //this will fail if button2 is not valid proxy object and properly exposed to js - - Assert(true, "FAILED: When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance"); -} - -var When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type = function() { - __log("TEST: When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); - - var Button = new com.tns.tests.Button1.extend("MyButton397", { - toString : function() { - return "button1"; - } + it("When_accessing_a_static_field_on_a_javascript_instance_it_should_work", function () { + + __log("TEST: When_accessing_a_static_field_on_a_javascript_instance_it_should_work"); + + var MyButton = com.tns.tests.Button1.extend("MyButton455", { + hashCode : function() { + return 5454; + }, + + toString : function() { + return "button1"; + }, + + equals : function() { + return true; + } + }); + + var valueUsingChild = MyButton.STATIC_IMAGE_ID; + expect(valueUsingChild).toEqual("static image id"); + + var valueUsingParent = com.tns.tests.Button1.STATIC_IMAGE_ID; + + expect(valueUsingParent).toEqual("static image id"); }); - var button = new Button(); - var object = button.getDummyClassAsObject(); - var name = object.getName(); + it("TestRequireDirName", function () { + + __log("TEST: TestRequireDirName"); + + var dir = __dirname; + + var expectedDirname = "/data/data/com.tns.android_runtime_testapp/files/app/tests"; + + expect(dir).toBe(expectedDirname); + }); - Assert(name == "dummy", "FAILED: When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); -} + it("TestRequireFileName", function () { + + __log("TEST: TestRequireFileName"); + + var file = __filename; + + var expectedFilename = "/data/data/com.tns.android_runtime_testapp/files/app/tests/tests.js"; + + expect(file).toBe(expectedFilename); + + var file2 = module.filename; -var When_a_java_field_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type = function() { - __log("TEST: When_a_java_field_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); - - var Button = new com.tns.tests.Button1.extend("MyButton413", { - toString : function() { - return "button1"; - } + expect(file).toBe(file2); }); - var button = new Button(); - var object = button.DummyClassAsObjectField; - var name = object.getName(); + it("TestGarbageCollection", function (done) { + var normalTest = function () { + + __log("TEST: TestGarbageCollection"); + + var obj = new com.tns.tests.ClassX(); + + obj.dummy(); + + obj = null; + + gc(); + java.lang.System.gc(); + gc(); + java.lang.System.gc(); + gc(); + java.lang.System.gc(); + + new java.lang.Thread(new java.lang.Runnable("ThreadFunc", { + run: function() { + var isCollected = com.tns.tests.ClassX.IsCollected; + __log('----------> isCollected: ' + isCollected); + expect(isCollected).toBe(true); + done(); + } + })).start(); + }; + normalTest(); + }); - Assert(name == "dummy", "FAILED: When_a_java_field_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); -} + it("TestWorkingWithJavaArrayDoesNotMakeMemoryLeak", function () { + -var When_a_java_argument_is_passed_to_js_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type = function() { - __log("TEST: When_a_java_argument_is_passed_to_js_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); - - var name = ""; - var Button = new com.tns.tests.Button1.extend("MyButton418", { - toString : function() { - return "button1"; - }, + __log("TEST: TestWorkingWithJavaArrayDoesNotMakeMemoryLeak"); + + var size = 10 * 1024 * 1024; + + for (var i = 0; i < 100; i++) { + + var arr = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), size); + + var length = arr.length; + + expect(length).toEqual(size); + + arr[0] = 123; + + var el = arr[0]; + + expect(el).toEqual(123); - methodDummyClassAsObjectInArgs: function(object) { - name = object.getName(); - __log("The actual name is " + name); + gc(); + java.lang.System.gc(); } }); - var button = new Button(); - var object = button.callMethodDummyClassAsObjectInArgs(); - - Assert(name == "dummy", "FAILED: When_a_java_argument_is_passed_to_js_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); -} + it("TestConstructorOverride", function () { + -var When_a_java_object_is_returned_from_indexer_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type = function() { - __log("TEST: When_a_java_object_is_returned_from_indexer_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); - - var Button = new com.tns.tests.Button1.extend("MyButton450", { - toString : function() { - return "button1"; - } + __log("TEST: TestConstructorOverride"); + + var ctorCalled = false; + var isConstructor = false; + + var MyButton = new com.tns.tests.Button1.extend("MyButton574", { + init : function() { + ctorCalled = true; + isConstructor = arguments[arguments.length - 1]; + }, + + toString : function() { + return "button1"; + } + }); + + var btn = new MyButton(); + + expect(ctorCalled).toEqual(true); + expect(isConstructor).toEqual(true); }); - var button = new Button(); - var arrayOfObjects = button.getDummyClassAsObjectArray(); - var name = arrayOfObjects[0].getName(); - - Assert(name == "dummy", "FAILED: When_a_java_object_is_returned_from_indexer_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type"); -} + it("TestConstructorOverrideOnTypeWithInitMethod", function () { -var When_accessing_a_static_field_on_a_javascript_instance_it_should_work = function() { - - __log("TEST: When_accessing_a_static_field_on_a_javascript_instance_it_should_work"); + __log("TEST: TestConstructorOverrideOnTypeWithInitMethod"); + + var isCalled = false; + var isConstructor = false; + + var MyDummyClassWithInit = com.tns.tests.DummyClassWithInit.extend("MyButton591", { + init: function() { + isCalled = true; + isConstructor = arguments[arguments.length - 1]; + } + }); + + __log("TEST: TestConstructorOverrideOnTypeWithInitMethod: calling overriden ctor"); + var dummy = new MyDummyClassWithInit(); + + expect(isCalled).toEqual(true); + expect(isConstructor).toEqual(true); + + __log("TEST: TestConstructorOverrideOnTypeWithInitMethod: calling ctor as regular method"); + isCalled = undefined; + isConstructor = undefined; + dummy.callInit(); + + expect(isCalled).toEqual(true); + expect(isConstructor).toEqual(false); + + }); - var MyButton = com.tns.tests.Button1.extend("MyButton455", { - hashCode : function() { - return 5454; - }, + it("TestRequire", function () { - toString : function() { - return "button1"; - }, + __log("TEST: TestRequire"); - equals : function() { - return true; + var exceptionCaught = false; + try{ + var myModule = require("../simplemodule"); } + catch(e) { + exceptionCaught = true; + } + + myModule.myLog("Hello world from NativeScript!"); + + expect(exceptionCaught).toBe(false); }); - var valueUsingChild = MyButton.STATIC_IMAGE_ID; - Assert(valueUsingChild == "static image id", "FAILED: When_accessing_a_static_field_on_a_javascript_instance_it_should_work."); - - var valueUsingParent = com.tns.tests.Button1.STATIC_IMAGE_ID; - Assert(valueUsingParent == "static image id", "FAILED: When_accessing_a_static_field_on_a_javascript_instance_it_should_work."); -}; - - -var TestRequireDirName = function() { + it("TestArrays", function () { + + __log("TEST: TestArrays"); + + var MyButton = com.tns.tests.Button1.extend("MyButton639", { + toString : function() { + return "button1"; + } + }); + var tester = new MyButton(); + var instances = tester.getDummyInstances(); + + var instanceFound = false; - __log("TEST: TestRequireDirName"); - - var dir = __dirname; + for (var i = 0; i < instances.length; i++) + { + if (instances[i].getName() == "second"); + { + instanceFound = true; + } + } + + expect(instanceFound).toEqual(true); + + instances[0] = instances[1]; + + var instances0name = instances[0].getName(); + var instances1name = instances[1].getName(); + + expect(instances0name).toEqual(instances1name); + }); - var expectedDirname = "/data/data/com.tns.android_runtime_testapp/files/app/tests"; + it("TestArrayLengthPropertyIsNumber", function () { - Assert(dir === expectedDirname, "TestRequireDirName FAILED: Expected value '" + expectedDirname + "', actual value=" + dir); -} - -var TestRequireFileName = function() { + __log("TEST: TestArrayLengthPropertyIsNumber"); + + var expectedLength = 10; - __log("TEST: TestRequireFileName"); + function getLength(x) + { + var arr = x.getIntArray1(expectedLength); + + return arr ? arr.length : 123456; + } + + var MyButton = com.tns.tests.Button1.extend("MyButton680", { + toString : function() { + return "button1"; + } + }); + + var count = getLength(new MyButton()); + + expect(count).toBe(expectedLength); + + }); - var file = __filename; + it("TestCreationOfLocationListener", function () { + + __log("TEST: TestCreationOfLocationListener"); + + var onLocationChangedCalled = false; + var onProviderDisabledCalled = false; + var onProviderEnabledCalled = false; + + var listener = new android.location.LocationListener("LocationListener",{ + onLocationChanged: function(location) { + onLocationChangedCalled = true; + }, + onProviderDisabled: function(provider) { + onProviderDisabledCalled = true; + }, + onProviderEnabled: function(provider) { + onProviderEnabledCalled = true; + } + }); + + listener.onLocationChanged(null); + + expect(onLocationChangedCalled).toEqual(true); + + listener.onProviderDisabled(""); + + expect(onProviderDisabledCalled).toEqual(true); + + listener.onProviderEnabled(""); + + expect(onProviderEnabledCalled).toEqual(true); + }); - var expectedFilename = "/data/data/com.tns.android_runtime_testapp/files/app/tests/tests.js"; + it("TestInnerClassCreation", function () { - Assert(file === expectedFilename, "TestRequireFileName FAILED: Expected value '" + expectedFilename + "', actual value=" + file); + __log("TEST: TestInnerClassCreation"); + + var MyButton = com.tns.tests.Button1.extend("MyButton726", { + toString : function() { + return "button1" + }}); + + var button1 = new MyButton(); + + var innerButton = new button1.InnerButton(); + + var s = innerButton.getSomeString(); + + expect(s.length).toBeGreaterThan(0); + + var innerButton2 = new new button1.InnerButton().InnerClass2(123) + + var s1 = innerButton2.getSomeString2(); + + expect(s1.length).toBeGreaterThan(0); + }); - var file2 = module.filename; - - Assert(file === file2, "TestRequireFileName FAILED: Values 'file' and 'file2' should be strict equal"); -} - - -var TestGarbageCollection = function() { + it("TestNestedClassCreation", function () { + + __log("TEST: TestNestedClassCreation"); - __log("TEST: TestGarbageCollection"); - - var obj = new com.tns.tests.ClassX(); - - obj.dummy(); - - Assert(obj != null, "TestGarbageCollection FAILED: Instance should not be null"); + var i = 123; + + var nested = new com.tns.tests.Button1.InnerStaticClass(i); + + var actual_i = nested.getInt(); + + expect(actual_i).toEqual(i); + }); - obj = null; + it("TestCallMethodOnAnObjectReturnedAsObjectWithoutMetadata", function () { + + __log("TEST: TestCallMethodOnAnObjectReturnedAsObjectWithoutMetadata"); + + var dummy = new com.tns.tests.DummyClass(); + + var dummy2 = dummy.getDummyClassAsObject(); + + var name = dummy2.getName(); + + expect(name).toEqual("dummy"); + }); - gc(); - gc(); - gc(); - java.lang.System.gc(); - java.lang.System.gc(); - java.lang.System.gc(); + it("TestGetFieldOnAnObjectReturnedAsObjectWithoutMetadata", function () { + + __log("TEST: TestGetFieldOnAnObjectReturnedAsObjectWithoutMetadata"); + + var dummy = new com.tns.tests.DummyClass(); + + dummy.setDummyField(); + + var dummy2 = dummy.dummyField; + + var name = dummy2.getName(); + + expect(name).toEqual("dummy"); + }); - new java.lang.Thread(new java.lang.Runnable("ThreadFunc", { - run: function() { - var isCollected = com.tns.tests.ClassX.IsCollected; - Assert(isCollected === true, "TestGarbageCollection FAILED: Expected value is 'true', actual value=" + isCollected); - } - })).start(); -} - -var TestWorkingWithJavaArrayDoesNotMakeMemoryLeak = function() { + it("TestCallMethodOnAnObjectPassedAsParameterInOverriddenMethodAsAnObjectWithoutMetadata", function () { + + __log("TEST: TestCallMethodOnAnObjectPassedAsParameterInOverriddenMethodAsAnObjectWithoutMetadata"); + + var D = com.tns.tests.DummyClass.DummyDerivedClass.extend("D",{ + dummyMethod: function(dummy) { + return this.getName(); + } + }) + + var d = new D(); - __log("TEST: TestWorkingWithJavaArrayDoesNotMakeMemoryLeak"); - - var size = 10 * 1024 * 1024; - - for (var i = 0; i < 100; i++) { + var name = d.executeCallback(); + + expect(name).toEqual("dummy"); + }); - var arr = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), size); + it("TestAccessArrayElementAsObjectWithoutMetadata", function () { - var length = arr.length; + __log("TEST: TestAccessArrayElementAsObjectWithoutMetadata"); - Assert(length == size, "TestWorkingWithJavaArrayDoesNotMakeMemoryLeak FAILED: Expected value is " + size + ", actual value=" + length); + var d = new com.tns.tests.DummyClass(); - arr[0] = 123; + var arr = d.getDummyClassArrayAsObject(); - var el = arr[0]; + var arrLength = arr.length; - Assert(el == 123, "TestWorkingWithJavaArrayDoesNotMakeMemoryLeak FAILED: Expected value is 123, actual value=" + el); - - gc(); - java.lang.System.gc(); - } -} - -var TestConstructorOverride = function() { - - __log("TEST: TestConstructorOverride"); + expect(arrLength).toEqual(1); + + var dummy = arr[0]; + + var name = dummy.getName(); + + expect(name).toBe("dummy"); + }); - var ctorCalled = false; - var isConstructor = false; - - var MyButton = new com.tns.tests.Button1.extend("MyButton574", { - init : function() { - ctorCalled = true; - isConstructor = arguments[arguments.length - 1]; - }, + it("TestCallMethodThatReturnsNull", function () { + + __log("TEST: TestCallMethodThatReturnsNull"); - toString : function() { - return "button1"; - } + var dummy = new com.tns.tests.DummyClass(); + + var x = dummy.getNull(); + + expect(x).toEqual(null); }); - var btn = new MyButton(); - - Assert(ctorCalled == true, "TestConstructorOverride FAILED: constructor not called"); - Assert(isConstructor == true, "TestConstructorOverride FAILED: isConstructor should be 'true'"); -} + it("TestCallMethodThatReturnsNullString", function () { -var TestConstructorOverrideOnTypeWithInitMethod = function() { - - __log("TEST: TestConstructorOverrideOnTypeWithInitMethod"); - - var isCalled = false; - var isConstructor = false; + __log("TEST: TestCallMethodThatReturnsNullString"); - var MyDummyClassWithInit = com.tns.tests.DummyClassWithInit.extend("MyButton591", { - init: function() { - isCalled = true; - isConstructor = arguments[arguments.length - 1]; - } + var dummy = new com.tns.tests.DummyClass(); + + var x = dummy.getNullString(); + + expect(x).toEqual(null); }); - __log("TEST: TestConstructorOverrideOnTypeWithInitMethod: calling overriden ctor"); - var dummy = new MyDummyClassWithInit(); - - Assert(isCalled == true, "TestConstructorOverrideOnTypeWithInitMethod FAILED: constructor not called"); - Assert(isConstructor == true, "TestConstructorOverrideOnTypeWithInitMethod FAILED: isConstructor should be 'true'"); - - __log("TEST: TestConstructorOverrideOnTypeWithInitMethod: calling ctor as regular method"); - isCalled = undefined; - isConstructor = undefined; - dummy.callInit(); - - Assert(isCalled == true, "TestConstructorOverrideOnTypeWithInitMethod FAILED: constructor not called"); - Assert(isConstructor == false, "FAILED: isConstructor should be 'false' actual: " + isConstructor); -} + it("TestAccessNullField", function () { -var TestRequire = function() { - __log("TEST: TestRequire"); - - var myModule = require("../simplemodule"); - myModule.myLog("Hello world from NativeScript!"); -} + __log("TEST: TestAccessNullField"); -var TestArrays = function() { - __log("TEST: TestArrays"); - - var MyButton = com.tns.tests.Button1.extend("MyButton639", { - toString : function() { - return "button1"; - } + var dummy = new com.tns.tests.DummyClass(); + + var x = dummy.nullField + + expect(x).toEqual(null); }); - var tester = new MyButton(); - var instances = tester.getDummyInstances(); - - var instanceFound = false; - - for (var i = 0; i < instances.length; i++) - { - if (instances[i].getName() == "second"); - { - instanceFound = true; - } - } - - Assert(instanceFound, "TestArrays FAILED: TestArrays indexer not working"); - instances[0] = instances[1]; - - var instances0name = instances[0].getName(); - var instances1name = instances[1].getName(); - - Assert(instances0name == instances1name, "TestArrays FAILED: Cannot set element into the array"); -} + it("TestAccessNullArrayElement", function () { -var TestArrayLengthPropertyIsNumber = function() { + __log("TEST: TestAccessNullArrayElement"); - __log("TEST: TestArrayLengthPropertyIsNumber"); + var dummy = new com.tns.tests.DummyClass(); + + var arr = dummy.getArrayWithNullElement(); + + __log("arr=" + arr.length) + + var x = arr[0]; + + expect(x).toEqual(null); + }); - var expectedLength = 10; + it("TEMPLATE", function () { - function getLength(x) - { - var arr = x.getIntArray1(expectedLength); + __log("TEST: TestCallMethodWithIntVarArg"); - return arr ? arr.length : 123456; - } - - var MyButton = com.tns.tests.Button1.extend("MyButton680", { - toString : function() { - return "button1"; - } + var dummy = new com.tns.tests.DummyClass(); + + var s = dummy.concatIntArrayAsString([1, 2, 3, 4]); + + expect(s).toBe("1234"); }); - var count = getLength(new MyButton()); + it("TestCallMethodWithCharVarArg", function () { + + __log("TEST: TestCallMethodWithCharVarArg"); + + var dummy = new com.tns.tests.DummyClass(); + + var s = dummy.concatCharArrayAsString(['t', 'e', 's', 't']); + + expect(s).toBe("test"); + }); - Assert(count === expectedLength, "TestArrayLengthPropertyIsNumber FAILED: Array length property should be number"); -} + it("TestCallMethodWithObjectVarArg", function () { + + __log("TEST: TestCallMethodWithObjectVarArg"); + + var dummy = new com.tns.tests.DummyClass(); + + var s = dummy.concatObjectArrayAsString([1, "test", false]); -var TestCreationOfLocationListener = function() { - __log("TEST: TestCreationOfLocationListener"); - - var onLocationChangedCalled = false; - var onProviderDisabledCalled = false; - var onProviderEnabledCalled = false; - - var listener = new android.location.LocationListener("LocationListener",{ - onLocationChanged: function(location) { - onLocationChangedCalled = true; - }, - onProviderDisabled: function(provider) { - onProviderDisabledCalled = true; - }, - onProviderEnabled: function(provider) { - onProviderEnabledCalled = true; - } + expect(s).toBe("1, test, false"); }); - listener.onLocationChanged(null); - - Assert(onLocationChangedCalled, "TestCreationOfLocationListener FAILED: onLocationChanged is not called"); - - listener.onProviderDisabled(""); + it("TestCanInheritFromClassInAndroidSupportLibrary", function () { + + __log("TEST: TestCanInheritFromClassInAndroidSupportLibrary"); + + var MyParcelableCompat = android.support.v4.os.ParcelableCompat.extend("MyParcelableCompat", { + toString: function() { + return "MyParcelableCompat"; + } + }); + + var compat = new MyParcelableCompat(); + + var s = compat.toString(); + + expect(s).toBe("MyParcelableCompat"); + }); - Assert(onProviderDisabledCalled, "TestCreationOfLocationListener FAILED: onProviderDisabled is not called"); + it("TestCallMethodWithByteParameter", function () { + + __log("TEST: TestCallMethodWithByteParameter"); + + var b = java.lang.Byte.valueOf(byte(123)); + + var s = "" + b; + + expect(s).toBe("123"); + }); - listener.onProviderEnabled(""); + it("TestCallMethodWithFloatParameter", function () { + + __log("TEST: TestCallMethodWithFloatParameter"); + + var d = new com.tns.tests.DummyClass(); + + var s = d.methodWithoutOverloads(1.23); + + expect(s).toBe("float=1.23"); + }); - Assert(onProviderEnabledCalled, "TestCreationOfLocationListener FAILED: onProviderEnabled is not called"); -} + it("TestCanCallStaticMethodThroughBaseClass", function () { + + __log("TEST: TestCanCallStaticMethodThroughBaseClass"); + + var name = com.tns.tests.MyClassDerived.getName(); -var TestInnerClassCreation = function() { - __log("TEST: TestInnerClassCreation"); - - var MyButton = com.tns.tests.Button1.extend("MyButton726", { - toString : function() { - return "button1" - }}); - - var button1 = new MyButton(); - - var innerButton = new button1.InnerButton(); - - var s = innerButton.getSomeString(); - - Assert(s.length > 0, "TestInnerClassCreation FAILED: innerButton.getSomeString returned empty string"); + expect(name).toBe("com.tns.tests.MyClassBase"); + }); - var innerButton2 = new new button1.InnerButton().InnerClass2(123) + it("TestUseFieldThatIsArray", function () { + + __log("TEST: TestUseFieldThatIsArray"); + + var d = new com.tns.tests.DummyClass(); + + var arrInt = d.arrIntField; + + var arrIntLength = arrInt.length; + + expect(arrIntLength).toBe(5); + + var intElement = arrInt[2]; + + expect(intElement).toBe(33); + + var arrString = d.arrStringField; + + var arrStringLength = arrString.length; + + expect(arrIntLength).toBe(5); + + var stringElement = arrString[2]; + + expect(stringElement).toBe("cc"); + }); - var s1 = innerButton2.getSomeString2(); + it("TestCanAssignArrayToField", function () { + + __log("TEST: TestCanAssignArrayToField"); + + var d = new com.tns.tests.DummyClass(); + + var arr = d.arrIntField2; + + expect(arr).toBe(null); + + d.arrIntField2 = d.arrIntField; + + var arrLength = d.arrIntField2.length; + + expect(arrLength).toBe(5); + }); - Assert(s1.length > 0, "TestInnerClassCreation FAILED: innerButton2.getSomeString2 returned empty string"); -} + it("TestCallMethodThatReturnsLong", function () { + + __log("TEST: TestCallMethodThatReturnsLong"); + + var n = java.lang.Long.parseLong("9007199254740991"); // 9007199254740991 = 2^53-1 -var TestNestedClassCreation = function() { - __log("TEST: TestNestedClassCreation"); + expect(n.__proto__.valueOf()).toBe(0); + expect(n.value).toBe(undefined); + expect(typeof n).toBe("number"); + expect(n instanceof Number).toBe(false); - var i = 123; - - var nested = new com.tns.tests.Button1.InnerStaticClass(i); - - var actual_i = nested.getInt(); + var n = java.lang.Long.parseLong("9007199254740992"); // 9007199254740992 = 2^53 + + var ctorFuncName = n.__proto__.constructor.name; + expect(ctorFuncName).toBe("NativeScriptLongNumber"); + expect(isNaN(n.valueOf())).toBe(true); + + var javaValue = n.value; + expect(javaValue).toBe("9007199254740992"); + + var typeName = typeof n; + expect(typeName).toBe("object"); + }); - Assert(actual_i == i, "TestNestedClassCreation FAILED: InnerStaticClass.getInt returned wrong value " + actual_i + ", expected " + i); -} + it("TestCallMethodWithLongParameter", function () { -var TestCallMethodOnAnObjectReturnedAsObjectWithoutMetadata = function() { - __log("TEST: TestCallMethodOnAnObjectReturnedAsObjectWithoutMetadata"); - - var dummy = new com.tns.tests.DummyClass(); - - var dummy2 = dummy.getDummyClassAsObject(); - - var name = dummy2.getName(); + __log("TEST: TestCallMethodWithLongParameter"); + + var d = new com.tns.tests.DummyClass(); + + var n1 = java.lang.Long.parseLong("9007199254740991"); // 9007199254740991 = 2^53-1 + var s1 = d.getLongAsString(n1); + expect(s1).toBe("9007199254740991"); + + var n2 = java.lang.Long.parseLong("9007199254740992"); // 9007199254740992 = 2^53 + var s2 = d.getLongAsString(n2); + expect(s2).toBe("9007199254740992"); + + var n3 = java.lang.Long.parseLong("9007199254740993"); // 9007199254740992 = 2^53+1 + var s3 = d.getLongAsString(n3); + expect(s3).toBe("9007199254740993"); + }); - Assert(name == "dummy", "TestCallMethodOnAnObjectReturnedAsObjectWithoutMetadata FAILED: Expected value is 'dummy', returned value is '" + name + "'"); -} - + it("TestCallMethodWithLongCastArgument", function () { -var TestGetFieldOnAnObjectReturnedAsObjectWithoutMetadata = function() { - __log("TEST: TestGetFieldOnAnObjectReturnedAsObjectWithoutMetadata"); + __log("TEST: TestCallMethodWithLongCastArgument"); + + var d = new com.tns.tests.DummyClass(); + + var s1 = d.getLongAsString(long("9007199254740991")); // 9007199254740991 = 2^53-1 + expect(s1).toBe("9007199254740991"); + + var s2 = d.getLongAsString(long(9007199254740991)); // 9007199254740991 = 2^53-1 + expect(s2).toBe("9007199254740991"); + + var s3 = d.getLongAsString(long("9007199254740992")); // 9007199254740992 = 2^53 + expect(s3).toBe("9007199254740992"); + + var s4 = d.getLongAsString(long("9007199254740993")); // 9007199254740992 = 2^53+1 + expect(s4).toBe("9007199254740993"); + }); - var dummy = new com.tns.tests.DummyClass(); + it("TestCallToStringOfNativeScriptLongObject", function () { + + __log("TEST: TestCallToStringOfNativeScriptLongObject"); + + var n = java.lang.Long.parseLong("9007199254740992"); // 9007199254740992 = 2^53 + + var s = n.toString(); + + expect(s).toBe(n.value); + }); - dummy.setDummyField(); + it("TestCallMethodWithLongParameterWithNumberObject", function () { + + __log("TEST: TestCallMethodWithLongParameterWithNumberObject"); + + var d = new com.tns.tests.DummyClass(); + + var s = d.getLongAsString(new Number("9007199254740991")); // 9007199254740991 = 2^53-1 + expect(s).toBe("9007199254740991"); + }); - var dummy2 = dummy.dummyField; + it("TestCallMethodWithMinAndMaxLongValues", function () { + + __log("TEST: TestCallMethodWithMinAndMaxLongValues"); + + var d = new com.tns.tests.DummyClass(); + + var maxLong = d.getMaxLong(); + var sMax = d.getLongAsString(maxLong); + expect(sMax).toBe("9223372036854775807"); + + var minLong = d.getMinLong(); + var sMin = d.getLongAsString(minLong); + expect(sMin).toBe("-9223372036854775808"); + }); - var name = dummy2.getName(); + it("TestCallMethodWithByteParameter", function () { + + __log("TEST: TestCallMethodWithByteParameter"); + + var d = new com.tns.tests.DummyClass(); + + var s1 = d.method1(byte(123)); + expect(s1).toBe("byte=123"); + + var s2 = d.method1(byte(new Number(123))); + expect(s2).toBe("byte=123"); + + var s3 = d.method1(byte("123")); + expect(s3).toBe("byte=123"); + + var s4 = d.method1(byte(new String("123"))); + expect(s4).toBe("byte=123"); + }); - Assert(name == "dummy", "TestGetFieldOnAnObjectReturnedAsObjectWithoutMetadata FAILED: Expected value is 'dummy', returned value is '" + name + "'"); -} - - -var TestCallMethodOnAnObjectPassedAsParameterInOverriddenMethodAsAnObjectWithoutMetadata = function() { - __log("TEST: TestCallMethodOnAnObjectPassedAsParameterInOverriddenMethodAsAnObjectWithoutMetadata"); + it("TestCallMethodWithShortParameter", function () { + + __log("TEST: TestCallMethodWithShortParameter"); + + var d = new com.tns.tests.DummyClass(); + + var s1 = d.method1(short(12345)); + expect(s1).toBe("short=12345"); + + var s2 = d.method1(short(new Number(12345))); + expect(s2).toBe("short=12345"); + + var s3 = d.method1(short("12345")); + expect(s3).toBe("short=12345"); + + var s4 = d.method1(short(new String("12345"))); + expect(s4).toBe("short=12345"); + }); - var D = com.tns.tests.DummyClass.DummyDerivedClass.extend("D",{ - dummyMethod: function(dummy) { - return this.getName(); - } - }) + it("TestCallMethodWithBooleanParameter", function () { + + __log("TEST: TestCallMethodWithBooleanParameter"); + + var d = new com.tns.tests.DummyClass(); + + var s1 = d.method1(true); + expect(s1).toBe("boolean=true"); + + var s2 = d.method1(false); + expect(s2).toBe("boolean=false"); + + var s3 = d.method1(new Boolean(true)); + expect(s3).toBe("boolean=true"); + + var s4 = d.method1(new Boolean(false)); + expect(s4).toBe("boolean=false"); + }); - var d = new D(); - - var name = d.executeCallback(); + it("TestThrowJavaScriptExceptionWhenCannotResolveJavaMethod", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenCannotResolveJavaMethod"); + + var exceptionCaught = false; + + var d = new com.tns.tests.DummyClass(); + + try + { + var s = d.method1(new java.lang.Object()); + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); - Assert(name == "dummy", "TestCallMethodOnAnObjectPassedAsParameterInOverriddenMethodAsAnObjectWithoutMetadata FAILED: Expected value is 'dummy', returned value is '" + name + "'"); -} - -var TestAccessArrayElementAsObjectWithoutMetadata = function() { - - __log("TEST: TestAccessArrayElementAsObjectWithoutMetadata"); + it("TestThrowJavaScriptExceptionWhenCannotResolveJavaConstructor", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenCannotResolveJavaConstructor"); + + var exceptionCaught = false; + + try + { + var d = new com.tns.tests.DummyClass(new java.lang.Object()); + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); - var d = new com.tns.tests.DummyClass(); - - var arr = d.getDummyClassArrayAsObject(); - - var arrLength = arr.length; - - Assert(arrLength == 1, "TestAccessArrayElementAsObjectWithoutMetadata FAILED: Expected array length is 1, actual length=" + arrLength); - - var dummy = arr[0]; - - var name = dummy.getName(); - - Assert(name === "dummy", "TestAccessArrayElementAsObjectWithoutMetadata FAILED: Expected value is 'dummy', returned value is '" + name + "'"); -} - -var TestCallMethodThatReturnsNull = function() { - - __log("TEST: TestCallMethodThatReturnsNull"); - - var dummy = new com.tns.tests.DummyClass(); - - var x = dummy.getNull(); - - Assert(x == null, "TestCallMethodThatReturnsNull FAILED: Expected value is null, but actual value is not null"); -} - -var TestCallMethodThatReturnsNullString = function() { - - __log("TEST: TestCallMethodThatReturnsNullString"); - - var dummy = new com.tns.tests.DummyClass(); - - var x = dummy.getNullString(); - - Assert(x == null, "TestCallMethodThatReturnsNullString FAILED: Expected value is null, but actual value is not null"); -} - -var TestAccessNullField = function() { - - __log("TEST: TestAccessNullField"); - - var dummy = new com.tns.tests.DummyClass(); - - var x = dummy.nullField - - Assert(x == null, "TestAccessNullField FAILED: Expected value is null, but actual value is not null"); -} - -var TestAccessNullArrayElement = function() { - - __log("TEST: TestAccessNullArrayElement"); - - var dummy = new com.tns.tests.DummyClass(); - - var arr = dummy.getArrayWithNullElement(); - - __log("arr=" + arr.length) - - var x = arr[0]; - - Assert(x == null, "TestAccessNullArrayElement FAILED: Expected value is null, but actual value is not null"); -} - -var TestCallMethodWithIntVarArg = function() { - - __log("TEST: TestCallMethodWithIntVarArg"); - - var dummy = new com.tns.tests.DummyClass(); - - var s = dummy.concatIntArrayAsString([1, 2, 3, 4]); - - Assert(s === "1234", "TestCallMethodWithIntVarArg FAILED: Expected value is '1234', but actual value is=" + s); -} - -var TestCallMethodWithCharVarArg = function() { - - __log("TEST: TestCallMethodWithCharVarArg"); - - var dummy = new com.tns.tests.DummyClass(); - - var s = dummy.concatCharArrayAsString(['t', 'e', 's', 't']); - - Assert(s === "test", "TestCallMethodWithCharVarArg FAILED: Expected value is 'test', but actual value is=" + s); -} - -var TestCallMethodWithObjectVarArg = function() { - - __log("TEST: TestCallMethodWithObjectVarArg"); - - var dummy = new com.tns.tests.DummyClass(); - - var s = dummy.concatObjectArrayAsString([1, "test", false]); - - Assert(s === "1, test, false", "TestCallMethodWithObjectVarArg FAILED: Expected value is '1, test, false', but actual value is=" + s); -} - -var TestCanInheritFromClassInAndroidSupportLibrary = function() { - - __log("TEST: TestCanInheritFromClassInAndroidSupportLibrary"); - - var MyParcelableCompat = android.support.v4.os.ParcelableCompat.extend("MyParcelableCompat", { - toString: function() { - return "MyParcelableCompat"; + it("TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject"); + + var arr = java.lang.reflect.Array.newInstance(java.lang.Object.class, 10); + + var o = new java.lang.Object(); + arr[0] = o; + + var exceptionCaught = false; + + try + { + arr[0] = {}; } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + + var isOldElement = o.equals(arr[0]); + + expect(isOldElement).toBe(true); }); - var compat = new MyParcelableCompat(); - - var s = compat.toString(); - - Assert(s === "MyParcelableCompat", "TestCanInheritFromClassInAndroidSupportLibrary FAILED: Expected value is 'MyParcelableCompat', but actual value is=" + s); -} - -var TestCallMethodWithByteParameter = function() { - - __log("TEST: TestCallMethodWithByteParameter"); - - var b = java.lang.Byte.valueOf(byte(123)); - - var s = "" + b; - - Assert(s === "123", "TestCallMethodWithByteParameter FAILED: Expected value is '123', but actual value is=" + s); -} - -var TestCallMethodWithFloatParameter = function() { - - __log("TEST: TestCallMethodWithFloatParameter"); - - var d = new com.tns.tests.DummyClass(); - - var s = d.methodWithoutOverloads(1.23); - - Assert(s === "float=1.23", "TestCallMethodWithFloatParameter FAILED: Expected value is 'float=1.23', but actual value is=" + s); -} - -var TestCanCallStaticMethodThroughBaseClass = function() { - - __log("TEST: TestCanCallStaticMethodThroughBaseClass"); - - var name = com.tns.tests.MyClassDerived.getName(); - - Assert(name === "com.tns.tests.MyClassBase", "TestCanCallStaticMethodThroughBaseClass FAILED: TestCanCallStaticMethodThroughBaseClass: Expected value is 'com.tns.tests.MyClassBase', but actual value is=" + name); -} - -var TestUseFieldThatIsArray = function() { - - __log("TEST: TestUseFieldThatIsArray"); - - var d = new com.tns.tests.DummyClass(); - - var arrInt = d.arrIntField; - - var arrIntLength = arrInt.length; - - Assert(arrIntLength === 5, "TestUseFieldThatIsArray FAILED: Expected array length is 5, but actual length is=" + arrIntLength); - - var intElement = arrInt[2]; - - Assert(intElement === 33, "TestUseFieldThatIsArray FAILED: Expected array element value is 33, but actual element value is=" + intElement); - - var arrString = d.arrStringField; - - var arrStringLength = arrString.length; - - Assert(arrIntLength === 5, "TestUseFieldThatIsArray FAILED: Expected array length is 5, but actual length is=" + arrStringLength); - - var stringElement = arrString[2]; - - Assert(stringElement === "cc", "TestUseFieldThatIsArray FAILED: Expected array element value is 'cc', but actual element value is=" + stringElement); -} - -var TestCanAssignArrayToField = function() { - - __log("TEST: TestCanAssignArrayToField"); - - var d = new com.tns.tests.DummyClass(); - - var arr = d.arrIntField2; - - Assert(arr === null, "TestCanAssignArrayToField FAILED: Expected value is null, but actual value is=" + arr); - - d.arrIntField2 = d.arrIntField; - - var arrLength = d.arrIntField2.length; - - Assert(arrLength === 5, "TestCanAssignArrayToField FAILED: Expected array length is 5, but actual length is=" + arrLength); -} - -var TestCallMethodThatReturnsLong = function() { - - __log("TEST: TestCallMethodThatReturnsLong"); - - var n = java.lang.Long.parseLong("9007199254740991"); // 9007199254740991 = 2^53-1 - - Assert(n.__proto__.valueOf() === 0, "TestCallMethodThatReturnsLong FAILED: n.__proto__.valueOf() === 0"); - Assert(n.value === undefined, "TestCallMethodThatReturnsLong FAILED: n.value === undefined"); - Assert(typeof n === "number", "TestCallMethodThatReturnsLong FAILED: typeof n === 'number'"); - Assert(n instanceof Number === false, "TestCallMethodThatReturnsLong FAILED: n instanceof Number === false"); - - var n = java.lang.Long.parseLong("9007199254740992"); // 9007199254740992 = 2^53 - - var ctorFuncName = n.__proto__.constructor.name; - Assert(ctorFuncName === "NativeScriptLongNumber", "TestCallMethodThatReturnsLong FAILED: Expected constructor function name is 'NativeScriptLongNumber', actual name=" + ctorFuncName); - Assert(isNaN(n.valueOf()) === true, "TestCallMethodThatReturnsLong FAILED: Expected JavaScript value is NaN"); - var javaValue = n.value; - Assert(javaValue === "9007199254740992", "TestCallMethodThatReturnsLong FAILED: Expected Java value is '9007199254740992', actual value=" + javaValue); - var typeName = typeof n; - Assert(typeName === "object", "TestCallMethodThatReturnsLong FAILED: Expected type is 'object', actual type=" + typeName); -} - -var TestCallMethodWithLongParameter = function() { - - __log("TEST: TestCallMethodWithLongParameter"); - - var d = new com.tns.tests.DummyClass(); - - var n1 = java.lang.Long.parseLong("9007199254740991"); // 9007199254740991 = 2^53-1 - var s1 = d.getLongAsString(n1); - Assert(s1 === "9007199254740991", "TestCallMethodWithLongParameter FAILED: Expected value is '9007199254740991', actual value=" + s1); - - var n2 = java.lang.Long.parseLong("9007199254740992"); // 9007199254740992 = 2^53 - var s2 = d.getLongAsString(n2); - Assert(s2 === "9007199254740992", "TestCallMethodWithLongParameter FAILED: Expected value is '9007199254740992', actual value=" + s2); - - var n3 = java.lang.Long.parseLong("9007199254740993"); // 9007199254740992 = 2^53+1 - var s3 = d.getLongAsString(n3); - Assert(s3 === "9007199254740993", "TestCallMethodWithLongParameter FAILED: Expected value is '9007199254740993', actual value=" + s3); -} - -var TestCallMethodWithLongCastArgument = function() { - - __log("TEST: TestCallMethodWithLongCastArgument"); - - var d = new com.tns.tests.DummyClass(); - - var s1 = d.getLongAsString(long("9007199254740991")); // 9007199254740991 = 2^53-1 - Assert(s1 === "9007199254740991", "TestCallMethodWithLongCastArgument FAILED: Expected value is '9007199254740991', actual value=" + s1); - - var s2 = d.getLongAsString(long(9007199254740991)); // 9007199254740991 = 2^53-1 - Assert(s2 === "9007199254740991", "TestCallMethodWithLongCastArgument FAILED: Expected value is '9007199254740991', actual value=" + s2); - - var s3 = d.getLongAsString(long("9007199254740992")); // 9007199254740992 = 2^53 - Assert(s3 === "9007199254740992", "TestCallMethodWithLongCastArgument FAILED: Expected value is '9007199254740992', actual value=" + s3); - - var s4 = d.getLongAsString(long("9007199254740993")); // 9007199254740992 = 2^53+1 - Assert(s4 === "9007199254740993", "TestCallMethodWithLongCastArgument FAILED: Expected value is '9007199254740993', actual value=" + s4); -} - -var TestCallToStringOfNativeScriptLongObject = function() { - - __log("TEST: TestCallToStringOfNativeScriptLongObject"); - - var n = java.lang.Long.parseLong("9007199254740992"); // 9007199254740992 = 2^53 - - var s = n.toString(); - - Assert(s === n.value, "TestCallToStringOfNativeScriptLongObject FAILED: Expected value is '9007199254740992', actual value=" + s); -} - -var TestCallMethodWithLongParameterWithNumberObject = function() { - - __log("TEST: TestCallMethodWithLongParameterWithNumberObject"); - - var d = new com.tns.tests.DummyClass(); - - var s = d.getLongAsString(new Number("9007199254740991")); // 9007199254740991 = 2^53-1 - Assert(s === "9007199254740991", "TestCallMethodWithLongParameterWithNumberObject FAILED: Expected value is '9007199254740991', actual value=" + s); -} - -var TestCallMethodWithMinAndMaxLongValues = function() { - - __log("TEST: TestCallMethodWithMinAndMaxLongValues"); - - var d = new com.tns.tests.DummyClass(); - - var maxLong = d.getMaxLong(); - var sMax = d.getLongAsString(maxLong); - Assert(sMax === "9223372036854775807", "TestCallMethodWithMinAndMaxLongValues FAILED: Expected value is '9223372036854775807', actual value=" + sMax); - - var minLong = d.getMinLong(); - var sMin = d.getLongAsString(minLong); - Assert(sMin === "-9223372036854775808", "TestCallMethodWithMinAndMaxLongValues FAILED: Expected value is '-9223372036854775808', actual value=" + sMin); -} - -var TestCallMethodWithByteParameter = function() { - - __log("TEST: TestCallMethodWithByteParameter"); - - var d = new com.tns.tests.DummyClass(); - - var s1 = d.method1(byte(123)); - Assert(s1 === "byte=123", "TestCallMethodWithByteParameter FAILED: Expected value is 'byte=123', actual value=" + s1); - - var s2 = d.method1(byte(new Number(123))); - Assert(s2 === "byte=123", "TestCallMethodWithByteParameter FAILED: Expected value is 'byte=123', actual value=" + s2); - - var s3 = d.method1(byte("123")); - Assert(s3 === "byte=123", "TestCallMethodWithByteParameter FAILED: Expected value is 'byte=123', actual value=" + s3); - - var s4 = d.method1(byte(new String("123"))); - Assert(s4 === "byte=123", "TestCallMethodWithByteParameter FAILED: Expected value is 'byte=123', actual value=" + s4); -} - -var TestCallMethodWithShortParameter = function() { - - __log("TEST: TestCallMethodWithShortParameter"); - - var d = new com.tns.tests.DummyClass(); - - var s1 = d.method1(short(12345)); - Assert(s1 === "short=12345", "TestCallMethodWithShortParameter FAILED: Expected value is 'short=12345', actual value=" + s1); - - var s2 = d.method1(short(new Number(12345))); - Assert(s2 === "short=12345", "TestCallMethodWithShortParameter FAILED: Expected value is 'short=12345', actual value=" + s2); - - var s3 = d.method1(short("12345")); - Assert(s3 === "short=12345", "TestCallMethodWithShortParameter FAILED: Expected value is 'short=12345', actual value=" + s3); - - var s4 = d.method1(short(new String("12345"))); - Assert(s4 === "short=12345", "TestCallMethodWithShortParameter FAILED: Expected value is 'short=12345', actual value=" + s4); -} - -var TestCallMethodWithBooleanParameter = function() { - - __log("TEST: TestCallMethodWithBooleanParameter"); - - var d = new com.tns.tests.DummyClass(); - - var s1 = d.method1(true); - Assert(s1 === "boolean=true", "TestCallMethodWithBooleanParameter FAILED: Expected value is 'boolean=true', actual value=" + s1); - - var s2 = d.method1(false); - Assert(s2 === "boolean=false", "TestCallMethodWithBooleanParameter FAILED: Expected value is 'boolean=false', actual value=" + s1); - - var s3 = d.method1(new Boolean(true)); - Assert(s3 === "boolean=true", "TestCallMethodWithBooleanParameter FAILED: Expected value is 'boolean=true', actual value=" + s3); - - var s4 = d.method1(new Boolean(false)); - Assert(s4 === "boolean=false", "TestCallMethodWithBooleanParameter FAILED: Expected value is 'boolean=false', actual value=" + s4); -} - -var TestThrowJavaScriptExceptionWhenCannotResolveJavaMethod = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenCannotResolveJavaMethod"); - - var exceptionCaught = false; - - var d = new com.tns.tests.DummyClass(); - - try - { - var s = d.method1(new java.lang.Object()); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenCannotResolveJavaMethod FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenCannotResolveJavaConstructor = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenCannotResolveJavaConstructor"); - - var exceptionCaught = false; - - try - { - var d = new com.tns.tests.DummyClass(new java.lang.Object()); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenCannotResolveJavaConstructor FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject"); - - var arr = java.lang.reflect.Array.newInstance(java.lang.Object.class, 10); - - var o = new java.lang.Object(); - arr[0] = o; - - var exceptionCaught = false; - - try - { - arr[0] = {}; - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject FAILED: No exception is thrown"); - - var isOldElement = o.equals(arr[0]); - - Assert(isOldElement === true, "TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject FAILED: Old and new element should be the same"); -} - -var TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive"); - - var arr = java.lang.reflect.Array.newInstance(java.lang.Object.class, 10); - - var o = new java.lang.Object(); - arr[0] = o; - - var exceptionCaught = false; - - try - { - arr[0] = 123; - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive FAILED: No exception is thrown"); - - var isOldElement = o.equals(arr[0]); - - Assert(isOldElement === true, "TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive FAILED: Old and new element should be the same"); -} - -var TestThrowJavaScriptExceptionWhenCreateJavaObjectWithNakedJavaScriptObject = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenCreateJavaObjectWithNakedJavaScriptObject"); - - var exceptionCaught = false; - - try - { - var d = new com.tns.tests.DummyClass({}); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenCreateJavaObjectWithNakedJavaScriptObject FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenCallJavaMethodWithNakedJavaScriptObject = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenCallJavaMethodWithNakedJavaScriptObject"); - - var exceptionCaught = false; + it("TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive"); + + var arr = java.lang.reflect.Array.newInstance(java.lang.Object.class, 10); + + var o = new java.lang.Object(); + arr[0] = o; + + var exceptionCaught = false; + + try + { + arr[0] = 123; + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + + var isOldElement = o.equals(arr[0]); + + expect(isOldElement).toBe(true); + }); - var d = new com.tns.tests.DummyClass(); - - try - { - var s = d.method2({}); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenCallJavaMethodWithNakedJavaScriptObject FAILED: No exception is thrown"); -} + it("TestThrowJavaScriptExceptionWhenCreateJavaObjectWithNakedJavaScriptObject", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenCreateJavaObjectWithNakedJavaScriptObject"); + + var exceptionCaught = false; -var TestThrowJavaScriptExceptionWhenCallJavaMethodWithJavaScriptPrimitiveWhenJavaRefIsExpected = function() { + try + { + var d = new com.tns.tests.DummyClass({}); + } + catch (e) + { + exceptionCaught = true; + } - __log("TEST: TestThrowJavaScriptExceptionWhenCallJavaMethodWithJavaScriptPrimitiveWhenJavaRefIsExpected"); - - var exceptionCaught = false; + expect(exceptionCaught).toBe(true); + }); - var d = new com.tns.tests.DummyClass(); - - try - { - var s = d.method2(123); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenCallJavaMethodWithJavaScriptPrimitiveWhenJavaRefIsExpected FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted = function() { + it("TestThrowJavaScriptExceptionWhenCallJavaMethodWithNakedJavaScriptObject", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenCallJavaMethodWithNakedJavaScriptObject"); + + var exceptionCaught = false; + + var d = new com.tns.tests.DummyClass(); - __log("TEST: TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted"); - - var exceptionCaught = false; - - var impl = { - echo : function(s) { - return "!!!" + s; + try + { + var s = d.method2({}); + } + catch (e) + { + exceptionCaught = true; } - }; - - var MyButton = com.tns.tests.Button1.extend("btn1303", impl); - var btn = new MyButton(); - - var echo = com.tns.tests.Button1.prototype.echo; - delete com.tns.tests.Button1.prototype.echo; - delete impl.echo; - try - { - __log("btn=" + btn.triggerEcho("12345")); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted FAILED (1): No exception is thrown"); + expect(exceptionCaught).toBe(true); + }); - exceptionCaught = false; + it("TestThrowJavaScriptExceptionWhenCallJavaMethodWithJavaScriptPrimitiveWhenJavaRefIsExpected", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenCallJavaMethodWithJavaScriptPrimitiveWhenJavaRefIsExpected"); + + var exceptionCaught = false; + + var d = new com.tns.tests.DummyClass(); - try - { - __log("btn=" + btn.triggerEchoAsObject("123")); - } - catch (e) - { - exceptionCaught = true; - } + try + { + var s = d.method2(123); + } + catch (e) + { + exceptionCaught = true; + } - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted FAILED (2): No exception is thrown"); + expect(exceptionCaught).toBe(true); + }); - com.tns.tests.Button1.prototype.echo = echo; -} - + it("TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted"); + + var exceptionCaught = false; + + var impl = { + echo : function(s) { + return "!!!" + s; + } + }; + + var MyButton = com.tns.tests.Button1.extend("btn1303", impl); + var btn = new MyButton(); + + var echo = com.tns.tests.Button1.prototype.echo; + delete com.tns.tests.Button1.prototype.echo; + delete impl.echo; + + try + { + __log("btn=" + btn.triggerEcho("12345")); + } + catch (e) + { + exceptionCaught = true; + } -var TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten = function() { + expect(exceptionCaught).toBe(true); + + exceptionCaught = false; - __log("TEST: TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten"); - - var exceptionCaught = false; - - var impl = { - echo : function(s) { - return "!!!" + s; + try + { + __log("btn=" + btn.triggerEchoAsObject("123")); } - }; - - var MyButton = com.tns.tests.Button1.extend("btn1344", impl); - var btn = new MyButton(); - - impl.echo = "" - - try - { - __log("btn=" + btn.triggerEcho("123")); - } - catch (e) - { - exceptionCaught = true; - } + catch (e) + { + exceptionCaught = true; + } - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten FAILED (1): No exception is thrown"); + expect(exceptionCaught).toBe(true); + + com.tns.tests.Button1.prototype.echo = echo; + }); - exceptionCaught = false; - - try - { - __log("btn=" + btn.triggerEchoAsObject("123")); - } - catch (e) - { - exceptionCaught = true; - } + it("TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten"); + + var exceptionCaught = false; + + var impl = { + echo : function(s) { + return "!!!" + s; + } + }; + + var MyButton = com.tns.tests.Button1.extend("btn1344", impl); + var btn = new MyButton(); + + impl.echo = "" + + try + { + __log("btn=" + btn.triggerEcho("123")); + } + catch (e) + { + exceptionCaught = true; + } - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten FAILED (2): No exception is thrown"); -} + expect(exceptionCaught).toBe(true); + + exceptionCaught = false; -var TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed = function() { + try + { + __log("btn=" + btn.triggerEchoAsObject("123")); + } + catch (e) + { + exceptionCaught = true; + } - __log("TEST: TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed"); - - var methodCalled = false; - var exceptionCaught = false; - - var d = new com.tns.tests.DummyClass(); - - var impl1 = new com.tns.tests.DummyClass.MyInterface("impl1_1393", { - echoInt: function(i) { methodCalled = true; return i; } + expect(exceptionCaught).toBe(true); }); - var i = d.triggerEchoInt(impl1, 123); - - Assert(methodCalled === true, "TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed FAILED: Method override is not called"); - - Assert(i === 123, "TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed FAILED: Expected value is 123, actual value=" + i); - - try - { - d.triggerDoSomething(impl1); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed FAILED: No exception is thrown"); - - methodCalled = false; - exceptionCaught = false; - - var impl2 = new com.tns.tests.DummyClass.MyInterface("impl2_1417",{ - doSomething: function() { methodCalled = true; } + it("TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed"); + + var methodCalled = false; + var exceptionCaught = false; + + var d = new com.tns.tests.DummyClass(); + + var impl1 = new com.tns.tests.DummyClass.MyInterface("impl1_1393", { + echoInt: function(i) { methodCalled = true; return i; } + }); + + var i = d.triggerEchoInt(impl1, 123); + + expect(methodCalled).toBe(true); + + expect(i).toBe(123); + + try + { + d.triggerDoSomething(impl1); + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + + methodCalled = false; + exceptionCaught = false; + + var impl2 = new com.tns.tests.DummyClass.MyInterface("impl2_1417",{ + doSomething: function() { methodCalled = true; } + }); + + d.triggerDoSomething(impl2); + + expect(methodCalled).toBe(true); + + try + { + d.triggerEchoInt(impl2, 123); + } + catch (e) + { + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); }); - d.triggerDoSomething(impl2); - - Assert(methodCalled === true, "TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed FAILED: Method override is not called"); - - try - { - d.triggerEchoInt(impl2, 123); - } - catch (e) - { - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass"); - - var implObj = {} - - var exceptionCaught = false; - - var Button1 = new com.tns.tests.Button1.extend("Button1", implObj); - - try - { - var D = com.tns.tests.DummyClass.DummyDerivedClass.extend("D1440", implObj); - } - catch (e) - { - __log("TEST: TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass exception:" + e); - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected"); - - var d = new com.tns.tests.DummyClass(); - - var exceptionCaught = false; - - try - { - d.setName(false); - } - catch (e) - { - __log("e=" + e); - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected FAILED: No exception is thrown"); - - exceptionCaught = false; - - try - { - d.setName(true); - } - catch (e) - { - __log("e=" + e); - exceptionCaught = true; - } - - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected FAILED: No exception is thrown"); -} - -var TestThrowJavaScriptExceptionWhenPassNumberArgumentWhereNotExpected = function() { - - __log("TEST: TestThrowJavaScriptExceptionWhenPassNumberArgumentWhereNotExpected"); - - var d = new com.tns.tests.DummyClass(); - - var exceptionCaught = false; - - try - { - d.setName(1); - } - catch (e) - { - __log("e=" + e); - exceptionCaught = true; - } + it("TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass"); + + var implObj = {} + + var exceptionCaught = false; + + var Button1 = new com.tns.tests.Button1.extend("Button1", implObj); + + try + { + var D = com.tns.tests.DummyClass.DummyDerivedClass.extend("D1440", implObj); + } + catch (e) + { + __log("TEST: TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass exception:" + e); + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); - Assert(exceptionCaught === true, "TestThrowJavaScriptExceptionWhenPassNumberArgumentWhereNotExpected FAILED: No exception is thrown"); -} - -var TestCallProctedMethodDefinedAsAbstractAndThenOverwritten = function() { - - __log("TEST: TestCallProctedMethodDefinedAsAbstractAndThenOverwritten"); + it("TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected", function () { + + __log("TEST: TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected"); + + var d = new com.tns.tests.DummyClass(); + + var exceptionCaught = false; + + try + { + d.setName(false); + } + catch (e) + { + __log("e=" + e); + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + + exceptionCaught = false; - var C = com.tns.tests.AbsClassImpl.extend("C1520", { - echoString: function(s) { - var echo = this.super.echoString(s); - return echo + "!"; + try + { + d.setName(true); + } + catch (e) + { + __log("e=" + e); + exceptionCaught = true; } + + expect(exceptionCaught).toBe(true); }); - var c = new C(); - - var s = c.echo("test"); - Assert(s === "test!", "TestCallProctedMethodDefinedAsAbstractAndThenOverwritten FAILED: Expected value 'test!', actual value=" + s); -} - -var TestCharSequenceReturnValueIsTreatedAsStringWhenItIsString = function() { + it("TestThrowJavaScriptExceptionWhenPassNumberArgumentWhereNotExpected", function () { - __log("TEST: TestCharSequenceReturnValueIsTreatedAsStringWhenItIsString"); - - var d = new com.tns.tests.DummyClass(); - - var s = d.getNameAsCharSequence(); + __log("TEST: TestThrowJavaScriptExceptionWhenPassNumberArgumentWhereNotExpected"); + + var d = new com.tns.tests.DummyClass(); + + var exceptionCaught = false; + + try + { + d.setName(1); + } + catch (e) + { + __log("e=" + e); + exceptionCaught = true; + } + + expect(exceptionCaught).toBe(true); + }); - Assert(s === "dummy", "TestCharSequenceReturnValueIsTreatedAsStringWhenItIsString FAILED: Expected value 'dummy', actual value=" + s); -} - - -var TestObjectReturnValueIsTreatedAsStringWhenItIsString = function() { + it("TestCallProctedMethodDefinedAsAbstractAndThenOverwritten", function () { + + __log("TEST: TestCallProctedMethodDefinedAsAbstractAndThenOverwritten"); + + var C = com.tns.tests.AbsClassImpl.extend("C1520", { + echoString: function(s) { + var echo = this.super.echoString(s); + return echo + "!"; + } + }); + var c = new C(); + + var s = c.echo("test"); + + expect(s).toBe("test!"); + }); - __log("TEST: TestObjectReturnValueIsTreatedAsStringWhenItIsString"); + it("TestCharSequenceReturnValueIsTreatedAsStringWhenItIsString", function () { + + __log("TEST: TestCharSequenceReturnValueIsTreatedAsStringWhenItIsString"); - var d = new com.tns.tests.DummyClass(); - - var s = d.getNameAsCharSequence(); + var d = new com.tns.tests.DummyClass(); + + var s = d.getNameAsCharSequence(); + + expect(s).toBe("dummy"); + }); - Assert(s === "dummy", "TestObjectReturnValueIsTreatedAsStringWhenItIsString FAILED: Expected value 'dummy', actual value=" + s); -} - -var TestCanFindImplementationObjectWhenCreateExtendedObjectFromJava = function() { - - __log("TEST: TestCanFindImplementationObjectWhenCreateExtendedObjectFromJava"); + it("TestObjectReturnValueIsTreatedAsStringWhenItIsString", function () { + + __log("TEST: TestObjectReturnValueIsTreatedAsStringWhenItIsString"); - var O = java.lang.Object.extend("O1560", {}); - - var ctor = (new O()).getClass().getConstructors()[0]; + var d = new com.tns.tests.DummyClass(); + + var s = d.getNameAsCharSequence(); + + expect(s).toBe("dummy"); + expect(true).toEqual(true); + }); - var o = ctor.newInstance(null); - - Assert(o !== null, "TestCanFindImplementationObjectWhenCreateExtendedObjectFromJava FAILED: Cannot find implementation object for given extended class"); -} + it("TestCanFindImplementationObjectWhenCreateExtendedObjectFromJava", function () { -var TestCanCallMethodThatReturnsArrayOfInterfaces = function() { + __log("TEST: TestCanFindImplementationObjectWhenCreateExtendedObjectFromJava"); - __log("TEST: TestCanCallMethodThatReturnsArrayOfInterfaces"); + var O = java.lang.Object.extend("O1560", {}); + + var ctor = (new O()).getClass().getConstructors()[0]; + + var o = ctor.newInstance(null); - var arr = java.lang.reflect.Array.newInstance(android.view.View.OnClickListener.class, 1); - - Assert(arr !== null, "TestCanCallMethodThatReturnsArrayOfInterfaces FAILED: Cannot create an array of interfaces"); - - var listener = new android.view.View.OnClickListener("listener1580", {}); + expect(o).not.toBe(null); + }); - arr[0] = listener; - - Assert(arr[0] !== null, "TestCanCallMethodThatReturnsArrayOfInterfaces FAILED: Cannot set an interface implementation to an array of interfaces"); -} - -var TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes = function() { - - __log("TEST: TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes"); + it("TestCanCallMethodThatReturnsArrayOfInterfaces", function () { - var formats = java.lang.reflect.Array.newInstance(java.text.NumberFormat.class, 2); - formats[0] = java.text.NumberFormat.getInstance(); - formats[1] = java.text.NumberFormat.getIntegerInstance(); - var mf = new java.text.MessageFormat("{0}, {1}") - mf.setFormats(formats); - var arr = mf.parse("123, 4567"); - var len = arr.length; + __log("TEST: TestCanCallMethodThatReturnsArrayOfInterfaces"); - Assert(len === 2, "TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes FAILED: Expected length is 2, actual=" + len); -} - -var TestCanCallToStringOnClassProxy = function() { - __log("TEST: TestCanCallToStringOnClassProxy"); + var arr = java.lang.reflect.Array.newInstance(android.view.View.OnClickListener.class, 1); + + expect(arr).not.toBe(null); + + var listener = new android.view.View.OnClickListener("listener1580", {}); + + arr[0] = listener; - var view = android.view.View; - var s = view.toString(); + expect(arr[0]).not.toBe(null); + }); - Assert(s.length > 0, "TestCanCallToStringOnClassProxy FAILED: Cannot call toString on class proxy"); -} + it("TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes", function () { + + __log("TEST: TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes"); -var When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class = function() { - __log("TEST: When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class"); - - var MyButton = com.tns.tests.Button1.extend("MyButton1615", { - toString : function() { - return "button1" - }}); + var formats = java.lang.reflect.Array.newInstance(java.text.NumberFormat.class, 2); + formats[0] = java.text.NumberFormat.getInstance(); + formats[1] = java.text.NumberFormat.getIntegerInstance(); + var mf = new java.text.MessageFormat("{0}, {1}") + mf.setFormats(formats); + var arr = mf.parse("123, 4567"); + var len = arr.length; + expect(len).toBe(2); + }); - var button = new MyButton(); - var clazz1 = button.getClass(); - var name1 = clazz1.getName(); - Assert(name1.indexOf("MyButton1615") != -1, "FAILED: When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class"); - - var clazz2 = MyButton.class; - var name2 = clazz2.getName(); - Assert(name2.indexOf("MyButton1615") != -1, "FAILED: When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class"); -} + it("TestCanCallToStringOnClassProxy", function () { + + __log("TEST: TestCanCallToStringOnClassProxy"); -var When_using_global_in_a_module_global_should_be_defined = function() { - __log("TEST: When_using_global_in_a_module_global_should_be_defined"); + var view = android.view.View; + var s = view.toString(); + + expect(s.length).toBeGreaterThan(0); + }); - var module = require("../modules/module"); - module.accessGlobalObject(); -} + it("When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class", function () { + + __log("TEST: When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class"); + + var MyButton = com.tns.tests.Button1.extend("MyButton1615", { + toString : function() { + return "button1" + }}); + -var When_using_package_json_should_load_module = function() { - __log("TEST: When_using_package_json_should_load_module"); + var button = new MyButton(); + var clazz1 = button.getClass(); + var name1 = clazz1.getName(); + expect(name1.indexOf("MyButton1615")).not.toEqual(-1); + + var clazz2 = MyButton.class; + var name2 = clazz2.getName(); + expect(name2.indexOf("MyButton1615")).not.toEqual(-1); + }); - var module2 = require("../module2"); - var value456 = module2.value456; + it("When_using_global_in_a_module_global_should_be_defined", function () { + + __log("TEST: When_using_global_in_a_module_global_should_be_defined"); + + var module = require("../modules/module"); + var canAccessGlobalObject = module.accessGlobalObject(); + expect(canAccessGlobalObject).toBe(true); + }); - Assert(value456 === 456, "FAILED: When_using_package_json_should_load_module"); -} - -var When_require_bcl_module_it_should_be_loaded = function() { - __log("TEST: When_require_bcl_module_it_should_be_loaded"); + it("When_using_package_json_should_load_module", function () { + + __log("TEST: When_using_package_json_should_load_module"); + + var module2 = require("../module2"); + var value456 = module2.value456; + + expect(value456).toBe(456); + }); - var module = require("bclmodule"); - module.getModuleName(); -} - -var When_require_a_module_it_should_be_loaded = function() { - __log("TEST: When_require_a_module_it_should_be_loaded"); + it("When_require_bcl_module_it_should_be_loaded", function () { + + __log("TEST: When_require_bcl_module_it_should_be_loaded"); + + var module = require("bclmodule"); + var moduleName = module.getModuleName(); + var expectedModuleName = "bclModule"; + expect(moduleName).toBe(expectedModuleName); + }); - var module = require("./testModules/testmodule"); - var moduleName = module.getModuleName(); + it("When_require_a_module_it_should_be_loaded", function () { + + __log("TEST: When_require_a_module_it_should_be_loaded"); + + var module = require("./testModules/testmodule"); + var moduleName = module.getModuleName(); + + expect(moduleName).toEqual("testModule"); + }); - Assert(moduleName == "testModule", "FAILED: When_require_a_module_it_should_be_loaded"); -} - - -var When_require_a_bcl_module_in_a_dir_it_should_be_loaded = function() { - __log("TEST: When_require_a_bcl_module_in_a_dir_it_should_be_loaded"); + it("When_require_a_bcl_module_in_a_dir_it_should_be_loaded", function () { + + __log("TEST: When_require_a_bcl_module_in_a_dir_it_should_be_loaded"); + + var module = require("tests/testModules/testBclModule"); + var moduleName = module.getModuleName(); + + expect(moduleName).toEqual("testBclModule"); + }); - var module = require("tests/testModules/testBclModule"); - var moduleName = module.getModuleName(); + it("When_require_a_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it", function () { + + __log("TEST: When_require_a_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it"); + + var module = require("./testModules/someDirModule"); + var moduleName = module.getModuleName(); + + expect(moduleName).toEqual("index.js"); + }); - Assert(moduleName == "testBclModule", "FAILED: When_require_a_bcl_module_in_a_dir_it_should_be_loaded"); -} - -var When_require_a_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it = function() { - __log("TEST: When_require_a_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it"); + it("When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it", function () { + + __log("TEST: When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it"); + + var module = require("tests/testModules/someBclDirModule"); + var moduleName = module.getModuleName(); + + expect(moduleName).toEqual("bclindex.js"); + }); - var module = require("./testModules/someDirModule"); - var moduleName = module.getModuleName(); - - Assert(moduleName == "index.js", "FAILED: When_require_a_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it"); -} - -var When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it = function() { - __log("TEST: When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it"); - - var module = require("tests/testModules/someBclDirModule"); - var moduleName = module.getModuleName(); - - Assert(moduleName == "bclindex.js", "FAILED: When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it"); -} - -var When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_package_json_inside_it = function() { - __log("TEST: When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_package_json_inside_it"); - - var module = require("tests/testModules/someModule"); - var value123 = module.value123; - - Assert(value123 === 123, "FAILED: When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_package_json_inside_it"); -} - -When_extending_a_class_two_times(); -When_extending_a_class_two_times_with_no_extend_names(); -When_implementing_an_interface_with_new_the_overrides_should_work(); - -//LOG("ALL PASSED"); -//fail(); - -When_extending_a_class_two_times_without_second_implementation_object(); -When_extending_a_class_and_calling_super_toString(); -When_accessing_a_static_field_on_a_javascript_instance_it_should_work(); -When_accessing_static_members_on_an_extended_class(); - -When__calling_super_method_using_the_prototype_property_of_a_function_it_should_call_the_super_method(); -When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method(); -When__calling_super_method_using_the_prototype_property_of_a_extended_function_it_should_call_the_super_method2() - - - -When_extending_a_class_and_calling_super_method_it_should_work(); - -//@@@ -//When_accessing_a_property_it_should_call_the_get_and_set_methods_respectivelly(); -//When_accessing_a_bool_property_it_should_call_the_is_and_set_methods_respectivelly(); - -//When_calling_instance_and_static_member_with_same_name_the_calls_should_succeed(); //TODO: Enable when supporting isStatic in MethodResolver -When_calling_toString_on_an_java_object_that_has_overriden_toString_in_js_it_should_call_the_js_method(); -When_calling_toString_on_an_java_object_it_should_call_the_java_method(); -When_a_java_method_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type(); -When_a_java_field_returns_object_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type(); -When_a_java_argument_is_passed_to_js_that_needs_js_instance__it_should_create_the_instance_according_to_the_actual_return_type(); -When_calling_instanceof_it_should_work(); -When_calling_instanceof_on_method_argument_it_should_work(); -When_calling_instanceof_on_method_result_it_should_work(); -When_calling_instanceof_on_field_result_it_should_work(); -When_accessing_class_property_on_a_extended_class_it_should_return_the_extended_class(); -When_using_global_in_a_module_global_should_be_defined(); -When_using_package_json_should_load_module(); -When_require_bcl_module_it_should_be_loaded(); -When_require_a_module_it_should_be_loaded(); -When_require_a_bcl_module_in_a_dir_it_should_be_loaded(); -When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it(); -When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_package_json_inside_it(); -When_require_a_module_that_is_a_directory_name_it_should_load_the_index_js_inside_it(); -When_calling_instanceof_on_interface_it_should_work(); - -TestRequireDirName(); -TestRequireFileName(); -TestGarbageCollection(); -TestWorkingWithJavaArrayDoesNotMakeMemoryLeak(); -TestConstructorOverride(); -TestConstructorOverrideOnTypeWithInitMethod(); -TestRequire(); -TestArrays(); -TestArrayLengthPropertyIsNumber(); -TestCreationOfLocationListener(); -TestInnerClassCreation(); -TestNestedClassCreation(); -TestCallMethodOnAnObjectReturnedAsObjectWithoutMetadata(); -TestGetFieldOnAnObjectReturnedAsObjectWithoutMetadata(); -TestCallMethodOnAnObjectPassedAsParameterInOverriddenMethodAsAnObjectWithoutMetadata(); -TestAccessArrayElementAsObjectWithoutMetadata(); -TestCallMethodThatReturnsNull(); -TestCallMethodThatReturnsNullString(); -TestAccessNullField(); -TestAccessNullArrayElement(); -TestCallMethodWithIntVarArg(); -TestCallMethodWithCharVarArg(); -TestCallMethodWithObjectVarArg(); -TestCanInheritFromClassInAndroidSupportLibrary(); -TestCallMethodWithByteParameter(); -TestCanCallStaticMethodThroughBaseClass(); -TestUseFieldThatIsArray(); -TestCanAssignArrayToField(); -TestCallMethodThatReturnsLong(); -TestCallMethodWithLongParameter(); -TestCallMethodWithLongCastArgument(); -TestCallToStringOfNativeScriptLongObject(); -TestCallMethodWithMinAndMaxLongValues(); -TestCallMethodWithLongParameterWithNumberObject(); -TestCallMethodWithByteParameter(); -TestCallMethodWithFloatParameter(); -TestCallMethodWithShortParameter(); -TestCallMethodWithBooleanParameter(); -TestThrowJavaScriptExceptionWhenCannotResolveJavaMethod(); -TestThrowJavaScriptExceptionWhenCannotResolveJavaConstructor(); -TestThrowJavaScriptExceptionWhenSetArrayRefElementWithNakedJavaScriptObject(); -TestThrowJavaScriptExceptionWhenSetArrayRefElementWithJavaScriptPrimitive(); -TestThrowJavaScriptExceptionWhenCreateJavaObjectWithNakedJavaScriptObject(); -TestThrowJavaScriptExceptionWhenCallJavaMethodWithNakedJavaScriptObject(); -TestThrowJavaScriptExceptionWhenCallJavaMethodWithJavaScriptPrimitiveWhenJavaRefIsExpected(); -TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsDeleted(); -TestThrowJavaScriptExceptionWhenOverideMethodImplementationIsOverwritten(); -// ART does not allow partiallly implemented interfaces (as expected) -//TestThrowJavaScriptExceptionWhenPartiallyImplementedInterfaceIsUsed(); -TestThrowJavaScriptExceptionWhenImplementationObjectIsUsedToExtendMoreThanOneClass(); -TestThrowJavaScriptExceptionWhenPassBooleanArgumentWhereNotExpected(); -TestThrowJavaScriptExceptionWhenPassNumberArgumentWhereNotExpected(); -TestCallProctedMethodDefinedAsAbstractAndThenOverwritten(); -TestCharSequenceReturnValueIsTreatedAsStringWhenItIsString(); -TestObjectReturnValueIsTreatedAsStringWhenItIsString(); -TestCanFindImplementationObjectWhenCreateExtendedObjectFromJava(); -TestCanCallMethodThatReturnsArrayOfInterfaces(); -TestCanParseSignatureWithTypesThatContainsCapitalLettersForPrimitiveTypes(); -TestCanCallToStringOnClassProxy(); \ No newline at end of file + it("When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_package_json_inside_it", function () { + + __log("TEST: When_require_a_bcl_module_that_is_a_directory_name_it_should_load_the_package_json_inside_it"); + + var module = require("tests/testModules/someModule"); + var value123 = module.value123; + + expect(value123).toBe(123); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testsForRuntimeBindingGenerator.js b/test-app/assets/app/tests/testsForRuntimeBindingGenerator.js index c9cb4a7ef..c8a4dcb15 100644 --- a/test-app/assets/app/tests/testsForRuntimeBindingGenerator.js +++ b/test-app/assets/app/tests/testsForRuntimeBindingGenerator.js @@ -1,50 +1,51 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var When_generating_a_proxy_of_nested_interface_at_runtime = function() { - __log("TEST: When_generating_a_proxy_of_nested_interface_at_runtime"); - - var MyButton = new com.tns.tests.Button1.extend("MyButton10", { - toString : function() { - return "button1"; - }, - }); +describe("Tests for runtime binding generator", function () { - var button = new MyButton(); + var myCustomEquality = function(first, second) { + return first == second; + }; - var called = false; - button.setOnClickListener(new android.view.View.OnClickListener("ClickListener19", { - onClick: function() { - called = true; - } - })); - - - - button.click(null); + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); - Assert(called === true, "FAILED: When_generating_a_proxy_of_nested_interface_at_runtime."); -} + it("When_generating_a_proxy_of_nested_interface_at_runtime", function () { - -var When_generating_a_proxy_of_android_class_at_runtime = function() { - __log("TEST: When_generating_a_proxy_of_android_class_at_runtime"); - - var MyButton = new com.tns.tests.Button1.extend("MyButton36", { - toString : function() { - return "button1"; - }, + __log("TEST: When_generating_a_proxy_of_nested_interface_at_runtime"); + + var MyButton = new com.tns.tests.Button1.extend("MyButton10", { + toString : function() { + return "button1"; + }, + }); + + var button = new MyButton(); + + var called = false; + button.setOnClickListener(new android.view.View.OnClickListener("ClickListener19", { + onClick: function() { + called = true; + } + })); + + button.click(null); + + expect(called).toBe(true); }); - var button1 = new MyButton(); - var dummyObject = button1.DummyClassAsObjectField; - - var isInstanceOf = dummyObject instanceof com.tns.tests.DummyClass; - Assert(isInstanceOf == true, "FAILED: When_generating_a_proxy_of_android_class_at_runtime."); -} - -When_generating_a_proxy_of_nested_interface_at_runtime(); -When_generating_a_proxy_of_android_class_at_runtime(); \ No newline at end of file + it("When_generating_a_proxy_of_android_class_at_runtime", function () { + + __log("TEST: When_generating_a_proxy_of_android_class_at_runtime"); + + var MyButton = new com.tns.tests.Button1.extend("MyButton36", { + toString : function() { + return "button1"; + }, + }); + + var button1 = new MyButton(); + var dummyObject = button1.DummyClassAsObjectField; + + var isInstanceOf = dummyObject instanceof com.tns.tests.DummyClass; + expect(isInstanceOf).toEqual(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testsForTypescript.js b/test-app/assets/app/tests/testsForTypescript.js index 9ce1fd1c1..11aa80957 100644 --- a/test-app/assets/app/tests/testsForTypescript.js +++ b/test-app/assets/app/tests/testsForTypescript.js @@ -1,543 +1,538 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -}; - - -(function When_creating_a_typescript_instance_with_constructor_property_it_should_support_this() { - - __log("TEST: When_creating_a_typescript_instance_with_constructor_property_it_should_support_this"); - var NativeViewGroup = (function (_super) { - __extends(NativeViewGroup, _super); - function NativeViewGroup(view) { - this._view = view; - return __native(this); - } - - NativeViewGroup.prototype.Then = function () { - this._view.Do(); - }; - - return NativeViewGroup; - })(android.view.ViewGroup); +describe("Tests typescript", function () { - var doCalled = false; - - var myView = new NativeViewGroup({ Do: function() { doCalled = true; }}); - myView.Then(); - Assert(doCalled == true, "FAILED: When_creating_a_typescript_instance_with_constructor_property_it_should_support_this. Method 'Do' not called"); - - var MyButton = (function (_super) { - __extends(MyButton, _super); - function MyButton() { - _super.call(this); - this.myName = "MyName"; - return __native(this); - } - - MyButton.prototype.echo = function (s) { - return "echo: " + this.myName; - }; - - MyButton.prototype.toString = function (s) { - return "toString: " + this.myName; - }; - - return MyButton; - })(com.tns.tests.Button1); - - var b = new MyButton(); - var exo = b.triggerEcho("exo"); - Assert(exo === "echo: MyName", "FAILED: When_creating_a_typescript_instance_with_constructor_property_it_should_support_this. Exo not wroking"); - - var toStringResult = b.toString(); - Assert(toStringResult === "toString: MyName", "FAILED: When_creating_a_typescript_instance_with_constructor_property_it_should_support_this. toString not wroking"); -})(); - - -(function When_creating_a_typescript_instance_it_should_support_overriden_members() { + var myCustomEquality = function(first, second) { + return first == second; + }; - __log("TEST: When_creating_a_typescript_instance_it_should_support_overriden_members"); + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); - var initCalled = false; - var MyButton1 = (function (_super) { - __extends(MyButton1, _super); - function MyButton1() { - _super.call(this); - return __native(this); - } - - MyButton1.prototype.init = function () { - initCalled = true; - }; - - MyButton1.prototype.toString = function (s) { - return "toString called" - }; - - return MyButton1; - })(com.tns.tests.Button1); + it("When_creating_a_typescript_instance_with_constructor_property_it_should_support_this", function () { - var button = new MyButton1(); - Assert(initCalled == true, "FAILED: When_creating_a_typescript_instance_it_should_support_overriden_members. Init not called"); - - var value = button.toString(); - Assert(value == "toString called", "FAILED: When_creating_a_typescript_instance_it_should_support_overriden_members. toString not called. Actual: " + value); -})(); - + __log("TEST: When_creating_a_typescript_instance_with_constructor_property_it_should_support_this"); + var NativeViewGroup = (function (_super) { + __extends(NativeViewGroup, _super); + function NativeViewGroup(view) { + this._view = view; + return __native(this); + } + + NativeViewGroup.prototype.Then = function () { + this._view.Do(); + }; + + return NativeViewGroup; + })(android.view.ViewGroup); + + var doCalled = false; -(function When_creating_a_typescript_instance_it_should_support_calling_super_members_from_overriden_members() { - - __log("TEST: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_overriden_members"); - - - var MyButton2 = (function (_super) { - __extends(MyButton2, _super); - function MyButton2() { + var myView = new NativeViewGroup({ Do: function() { doCalled = true; }}); + myView.Then(); + expect(doCalled).toEqual(true); + + var MyButton = (function (_super) { + __extends(MyButton, _super); + function MyButton() { _super.call(this); + this.myName = "MyName"; return __native(this); } - MyButton2.prototype.superToString = function () { - return _super.prototype.toString.call(this); + MyButton.prototype.echo = function (s) { + return "echo: " + this.myName; }; - MyButton2.prototype.toString = function (s) { - return this.super.toString(); - }; - - return MyButton2; - })(com.tns.tests.Button1); - - var button = new MyButton2(); - var button1Label = button.superToString(); - Assert(button1Label.indexOf("com.tns.tests.Button1-") != -1, "FAILED: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_overriden_members. Actual: " + button1Label); - Assert(button1Label.indexOf("-MyButton2") != -1, "FAILED: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_overriden_members. Expected to contain MyButton2. Actual: " + button1Label); -})(); - - -(function When_creating_a_pure_typescript_inheritance_chain_it_should_work() { - - __log("TEST: When_creating_a_pure_typescript_inheritance_chain_it_should_work"); - - var Animal = (function () { - function Animal(name) { - this.name = name; - } - Animal.prototype.move = function (meters) { - __log(this.name + " moved " + meters + "m."); - }; - return Animal; - })(); - - var Snake = (function (_super) { - __extends(Snake, _super); - function Snake(name) { - _super.call(this, name); - } - Snake.prototype.move = function () { - __log("Slithering..."); - _super.prototype.move.call(this, 5); - }; - return Snake; - })(Animal); - - var Horse = (function (_super) { - __extends(Horse, _super); - function Horse(name) { - _super.call(this, name); - } - Horse.prototype.move = function () { - __log("Galloping..."); - _super.prototype.move.call(this, 45); - }; - return Horse; - })(Animal); - - var horse = new Horse(); - var isInstanceOf = horse instanceof Horse; - Assert(isInstanceOf == true, "FAILED: When_creating_a_pure_typescript_inheritance_chain_it_should_work."); - - isInstanceOf = horse instanceof Animal; - Assert(isInstanceOf == true, "FAILED: When_creating_a_pure_typescript_inheritance_chain_it_should_work."); - - var snake = new Snake(); - isInstanceOf = snake instanceof Snake; - Assert(isInstanceOf == true, "FAILED: When_creating_a_pure_typescript_inheritance_chain_it_should_work."); - - isInstanceOf = snake instanceof Animal; - Assert(isInstanceOf == true, "FAILED: When_creating_a_pure_typescript_inheritance_chain_it_should_work."); - - var animal = new Animal(); - isInstanceOf = animal instanceof Animal; - Assert(isInstanceOf == true, "FAILED: When_creating_a_pure_typescript_inheritance_chain_it_should_work."); - -})(); - -(function When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance() { - - __log("TEST: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance"); - - var MyButton3 = (function (_super) { - __extends(MyButton3, _super); - function MyButton3() { - _super.call(this); - return __native(this); - } - - MyButton3.prototype.toString = function (s) { - return this.super.toString(); + MyButton.prototype.toString = function (s) { + return "toString: " + this.myName; }; - return MyButton3; + return MyButton; })(com.tns.tests.Button1); - - var button = new MyButton3(); - - var isInstanceOf = button instanceof MyButton3; - Assert(isInstanceOf == true, "FAILED: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance. Should be instance of MyButton3"); - - isInstanceOf = button instanceof com.tns.tests.Button1; - Assert(isInstanceOf == true, "FAILED: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance.Should be instance of com.tns.tests.Button1"); -})(); -(function When_creating_a_typescript_instance_with_arguments_it_should_be_a_valid_nativescript_instance() { - - __log("TEST: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance"); - - var MyButtonWithArgs = (function (_super) { - __extends(MyButtonWithArgs, _super); - function MyButtonWithArgs(value) { - _super.call(this, value); - return __native(this); - } - - MyButtonWithArgs.prototype.init = function () { - }; - - MyButtonWithArgs.prototype.onClick = function () { - __log("MyButton onClick called"); - }; + var b = new MyButton(); + var exo = b.triggerEcho("exo"); + expect(exo).toBe("echo: MyName"); - MyButtonWithArgs.prototype.superToString = function () { - return _super.prototype.toString.call(this); - }; - - return MyButtonWithArgs; - })(com.tns.tests.Button1); + var toStringResult = b.toString(); + expect(toStringResult).toBe("toString: MyName"); + }); - var button = new MyButtonWithArgs(5); - - var isInstanceOf = button instanceof MyButtonWithArgs; - Assert(isInstanceOf == true, "FAILED: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance. Should be instance of MyButtonWithArgs"); - - isInstanceOf = button instanceof com.tns.tests.Button1; - Assert(isInstanceOf == true, "FAILED: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance.Should be instance of com.tns.tests.Button1"); -})(); - - -(function When_creating_a_typescript_instance_it_should_support_member_access() { - - __log("TEST: When_creating_a_typescript_instance_it_should_support_member_access"); - - var MyButton4 = (function (_super) { - __extends(MyButton4, _super); - function MyButton4() { + it("When_creating_a_typescript_instance_it_should_support_overriden_members", function () { + + __log("TEST: When_creating_a_typescript_instance_it_should_support_overriden_members"); + + var initCalled = false; + var MyButton1 = (function (_super) { + __extends(MyButton1, _super); + function MyButton1() { _super.call(this); - this.my1 = "MyName"; return __native(this); } - MyButton4.prototype.init = function () { + MyButton1.prototype.init = function () { + initCalled = true; }; - MyButton4.prototype.echo = function (s) { - return "echo: " + this.my1; + MyButton1.prototype.toString = function (s) { + return "toString called" }; - return MyButton4; + return MyButton1; })(com.tns.tests.Button1); + + var button = new MyButton1(); + expect(initCalled).toEqual(true); + + var value = button.toString(); + expect(value).toEqual("toString called"); + }); - var button = new MyButton4(); - var prop = button.getIMAGE_ID_PROP(); - Assert(prop == "image id prop", "FAILED: When_creating_a_typescript_instance_it_should_support_member_access."); + it("When_creating_a_typescript_instance_it_should_support_calling_super_members_from_overriden_members", function () { + + __log("TEST: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_overriden_members"); + + var MyButton2 = (function (_super) { + __extends(MyButton2, _super); + function MyButton2() { + _super.call(this); + return __native(this); + } + + MyButton2.prototype.superToString = function () { + return _super.prototype.toString.call(this); + }; + + MyButton2.prototype.toString = function (s) { + return this.super.toString(); + }; + + return MyButton2; + })(com.tns.tests.Button1); + + var button = new MyButton2(); + var button1Label = button.superToString(); + expect(button1Label.indexOf("com.tns.tests.Button1-")).not.toEqual(-1); + expect(button1Label.indexOf("-MyButton2")).not.toEqual(-1); + }); - var button1 = new MyButton4(); - var prop1 = button1.getIMAGE_ID_PROP(); - Assert(prop1 == "image id prop", "FAILED: When_creating_a_typescript_instance_it_should_support_member_access."); -})(); - - - -(function When_creating_a_typescript_instance_it_should_support_calling_super_members_from_super_prototype() { + it("When_creating_a_pure_typescript_inheritance_chain_it_should_work", function () { + + __log("TEST: When_creating_a_pure_typescript_inheritance_chain_it_should_work"); + + var Animal = (function () { + function Animal(name) { + this.name = name; + } + Animal.prototype.move = function (meters) { + __log(this.name + " moved " + meters + "m."); + }; + return Animal; + })(); + + var Snake = (function (_super) { + __extends(Snake, _super); + function Snake(name) { + _super.call(this, name); + } + Snake.prototype.move = function () { + __log("Slithering..."); + _super.prototype.move.call(this, 5); + }; + return Snake; + })(Animal); + + var Horse = (function (_super) { + __extends(Horse, _super); + function Horse(name) { + _super.call(this, name); + } + Horse.prototype.move = function () { + __log("Galloping..."); + _super.prototype.move.call(this, 45); + }; + return Horse; + })(Animal); + + var horse = new Horse(); + var isInstanceOf = horse instanceof Horse; + expect(isInstanceOf).toEqual(true); + + isInstanceOf = horse instanceof Animal; + expect(isInstanceOf).toEqual(true); + + var snake = new Snake(); + isInstanceOf = snake instanceof Snake; + expect(isInstanceOf).toEqual(true); + + isInstanceOf = snake instanceof Animal; + expect(isInstanceOf).toEqual(true); + + var animal = new Animal(); + isInstanceOf = animal instanceof Animal; + expect(isInstanceOf).toEqual(true); + }); - __log("TEST: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_super_prototype"); + it("When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance", function () { + + __log("TEST: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance"); + + var MyButton3 = (function (_super) { + __extends(MyButton3, _super); + function MyButton3() { + _super.call(this); + return __native(this); + } + + MyButton3.prototype.toString = function (s) { + return this.super.toString(); + }; + + return MyButton3; + })(com.tns.tests.Button1); + + var button = new MyButton3(); + + var isInstanceOf = button instanceof MyButton3; + expect(isInstanceOf).toEqual(true); + + isInstanceOf = button instanceof com.tns.tests.Button1; + expect(isInstanceOf).toEqual(true); + }); - var MyButton5 = (function (_super) { - __extends(MyButton5, _super); - function MyButton5() { - _super.call(this); - this.my1 = "MyName"; - return __native(this); - } - - MyButton5.prototype.init = function () { - }; - - MyButton5.prototype.toString = function (s) { - return this.super.toString(); - }; - - return MyButton5; - })(com.tns.tests.Button1); - - var button = new MyButton5(); - var button1Label = button.toString(); - Assert(button1Label.indexOf("com.tns.tests.Button1-") != -1, "FAILED: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_super_prototype"); - Assert(button1Label.indexOf("-MyButton5") != -1, "FAILED: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_super_prototype. Expected to conatin MyButton5"); -})(); + it("When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance", function () { + + __log("TEST: When_creating_a_typescript_instance_it_should_be_a_valid_nativescript_instance"); + + var MyButtonWithArgs = (function (_super) { + __extends(MyButtonWithArgs, _super); + function MyButtonWithArgs(value) { + _super.call(this, value); + return __native(this); + } + + MyButtonWithArgs.prototype.init = function () { + }; -(function When_extending_an_already_extended_object_it_should_throw_an_error() { - - __log("TEST: When_extending_an_already_extended_object_it_should_throw_an_error"); + MyButtonWithArgs.prototype.onClick = function () { + __log("MyButton onClick called"); + }; + + MyButtonWithArgs.prototype.superToString = function () { + return _super.prototype.toString.call(this); + }; + + return MyButtonWithArgs; + })(com.tns.tests.Button1); + + var button = new MyButtonWithArgs(5); + + var isInstanceOf = button instanceof MyButtonWithArgs; + expect(isInstanceOf).toEqual(true); + + isInstanceOf = button instanceof com.tns.tests.Button1; + expect(isInstanceOf).toEqual(true); + }); - var errorThrown = false; - try { + it("When_creating_a_typescript_instance_it_should_support_member_access", function () { + + __log("TEST: When_creating_a_typescript_instance_it_should_support_member_access"); - var MyButton6 = (function (_super) { - __extends(MyButton6, _super); - function MyButton6() { + var MyButton4 = (function (_super) { + __extends(MyButton4, _super); + function MyButton4() { _super.call(this); this.my1 = "MyName"; return __native(this); } - MyButton6.prototype.init = function () { + MyButton4.prototype.init = function () { }; - MyButton6.prototype.toString = function (s) { - return this.super.toString(); + MyButton4.prototype.echo = function (s) { + return "echo: " + this.my1; }; - return MyButton6; + return MyButton4; })(com.tns.tests.Button1); - - var SecondButton = (function (_super) { - __extends(SecondButton, _super); - - function SecondButton() { - _super.apply(this, arguments); - } - - return SecondButton; - })(MyButton6); - } catch (err) { - errorThrown = true; - } + + var button = new MyButton4(); + var prop = button.getIMAGE_ID_PROP(); + expect(prop).toEqual("image id prop"); + + var button1 = new MyButton4(); + var prop1 = button1.getIMAGE_ID_PROP(); + expect(prop1).toEqual("image id prop"); + }); - Assert(errorThrown == true, "FAILED: When_extending_an_already_extended_object_it_should_throw_an_error."); -})(); - + it("When_creating_a_typescript_instance_it_should_support_calling_super_members_from_super_prototype", function () { + + __log("TEST: When_creating_a_typescript_instance_it_should_support_calling_super_members_from_super_prototype"); + + var MyButton5 = (function (_super) { + __extends(MyButton5, _super); + function MyButton5() { + _super.call(this); + this.my1 = "MyName"; + return __native(this); + } + + MyButton5.prototype.init = function () { + }; -(function When_accessing_a_static_field_on_a_typescript_instance_it_should_work() { + MyButton5.prototype.toString = function (s) { + return this.super.toString(); + }; + + return MyButton5; + })(com.tns.tests.Button1); + + var button = new MyButton5(); + var button1Label = button.toString(); + expect(button1Label.indexOf("com.tns.tests.Button1-")).not.toEqual(-1); + expect(button1Label.indexOf("-MyButton5")).not.toEqual(-1); + }); - __log("TEST: When_accessing_a_static_field_on_a_typescript_instance_it_should_work"); + it("When_extending_an_already_extended_object_it_should_throw_an_error", function () { + + __log("TEST: When_extending_an_already_extended_object_it_should_throw_an_error"); + + var errorThrown = false; + try { + + var MyButton6 = (function (_super) { + __extends(MyButton6, _super); + function MyButton6() { + _super.call(this); + this.my1 = "MyName"; + return __native(this); + } + + MyButton6.prototype.init = function () { + }; + + MyButton6.prototype.toString = function (s) { + return this.super.toString(); + }; + + return MyButton6; + })(com.tns.tests.Button1); + + var SecondButton = (function (_super) { + __extends(SecondButton, _super); + + function SecondButton() { + _super.apply(this, arguments); + } + + return SecondButton; + })(MyButton6); + } catch (err) { + errorThrown = true; + } + + expect(errorThrown).toEqual(true); + }); - var MyButton7 = (function (_super) { - __extends(MyButton7, _super); - function MyButton7() { - _super.call(this); - this.my1 = "MyName"; - } - - MyButton7.prototype.init = function () { - }; + it("When_accessing_a_static_field_on_a_typescript_instance_it_should_work", function () { + + __log("TEST: When_accessing_a_static_field_on_a_typescript_instance_it_should_work"); + + var MyButton7 = (function (_super) { + __extends(MyButton7, _super); + function MyButton7() { + _super.call(this); + this.my1 = "MyName"; + } + + MyButton7.prototype.init = function () { + }; - MyButton7.prototype.toString = function (s) { - return "my"; - }; - - return MyButton7; - })(com.tns.tests.Button1); - - var valueUsingChild = MyButton7.STATIC_IMAGE_ID; - Assert(valueUsingChild == "static image id", "FAILED: When_accessing_a_static_field_on_a_typescript_instance_it_should_work. MyButton7.STATIC_IMAGE_ID should be 5"); - - MyButton7.STATIC_IMAGE_ID = "test"; - valueUsingChild = MyButton7.STATIC_IMAGE_ID; - Assert(valueUsingChild == "test", "FAILED: When_accessing_a_static_field_on_a_typescript_instance_it_should_work. MyButton7.STATIC_IMAGE_ID should be 5"); + MyButton7.prototype.toString = function (s) { + return "my"; + }; + + return MyButton7; + })(com.tns.tests.Button1); + + var valueUsingChild = MyButton7.STATIC_IMAGE_ID; + expect(valueUsingChild).toEqual("static image id"); + + MyButton7.STATIC_IMAGE_ID = "test"; + valueUsingChild = MyButton7.STATIC_IMAGE_ID; + expect(valueUsingChild).toEqual("test"); + + var valueUsingParent = com.tns.tests.Button1.STATIC_IMAGE_ID; + expect(valueUsingParent).toEqual("static image id"); + }); - var valueUsingParent = com.tns.tests.Button1.STATIC_IMAGE_ID; - Assert(valueUsingParent == "static image id", "FAILED: When_accessing_a_static_field_on_a_typescript_instance_it_should_work. com.tns.tests.Button1.STATIC_IMAGE_ID should be 5"); -})(); + it("When_calling_a_static_method_on_a_typescript_instance_it_should_work", function () { + + __log("TEST: When_calling_a_static_method_on_a_typescript_instance_it_should_work"); -(function When_calling_a_static_method_on_a_typescript_instance_it_should_work() { - - __log("TEST: When_calling_a_static_method_on_a_typescript_instance_it_should_work"); + + var MyButton8 = (function (_super) { + __extends(MyButton8, _super); + function MyButton8() { + _super.call(this); + this.my1 = "MyName"; + } + + MyButton8.prototype.init = function () { + }; + MyButton8.prototype.onClick = function () { + __log("MyButton onClick called"); + }; + + MyButton8.prototype.superToString = function () { + return _super.prototype.toString.call(this); + }; + + MyButton8.prototype.echo = function (s) { + return "echo: " + this.my1; + }; + + return MyButton8; + })(com.tns.tests.Button1); + + MyButton8.setMyStaticIntField(5); + var valueUsingChild = MyButton8.getMyStaticIntField(); + expect(valueUsingChild).toEqual(5); + + var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); + expect(valueUsingParent).toEqual(5); + + com.tns.tests.Button1.setMyStaticIntField(6); + var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); + expect(valueUsingParent).toEqual(6); + + valueUsingChild = MyButton8.getMyStaticIntField(); + expect(valueUsingChild).toEqual(6); + }); + + it("When_inherit_from_android_base_class_it_should_create_an_instance", function () { + + /* + // From issue #137 https://github.com/telerik/Kimera/issues/137 + class ListViewAdapter extends android.widget.BaseAdapter { + private _items: Array; + + constructor(items: Array) { + super(); + + this._items = items; + } + + get items(): Array { + return this._items; + } + set items(value: Array) { + this._items = value; + } + + public getCount() { + return this._items ? this._items.length : 0; + } + + public getItem(i) { + return this._items && i < this._items.length ? this._items[i] : null; + } + + public getItemId(i) { + return long(0); + } + + public getView(i, view, viewGroup) { + return null; + } + + public refresh() { + this.notifyDataSetChanged(); + } + } + */ + var ListViewAdapter = (function (_super) { + __extends(ListViewAdapter, _super); + function ListViewAdapter(items) { + _super.call(this); + + this._items = items; + return __native(this); + } + Object.defineProperty(ListViewAdapter.prototype, "items", { + get: function () { + return this._items; + }, + set: function (value) { + this._items = value; + }, + enumerable: true, + configurable: true + }); + + ListViewAdapter.prototype.getCount = function () { + return this._items ? this._items.length : 0; + }; + + ListViewAdapter.prototype.getItem = function (i) { + return this._items && i < this._items.length ? this._items[i] : null; + }; + + ListViewAdapter.prototype.getItemId = function (i) { + return long(0); + }; + + ListViewAdapter.prototype.getView = function (i, view, viewGroup) { + return null; + }; + + ListViewAdapter.prototype.refresh = function () { + this.notifyDataSetChanged(); + }; + return ListViewAdapter; + })(android.widget.BaseAdapter); + + var adapter = new ListViewAdapter(); + + expect(adapter).not.toEqual(null); + }); - var MyButton8 = (function (_super) { - __extends(MyButton8, _super); - function MyButton8() { + it("When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work", function () { + + __log("TEST: When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work"); + + var MyButton9 = (function (_super) { + __extends(MyButton9, _super); + + function MyButton9() { _super.call(this); - this.my1 = "MyName"; + + var that = __native(this); + + that.setOnClickListener(new android.view.View.OnClickListener({ + onClick : function() { + that.buttonClicked = true; + } + })); + + return that; } - - MyButton8.prototype.init = function () { - }; - MyButton8.prototype.onClick = function () { - __log("MyButton onClick called"); - }; - - MyButton8.prototype.superToString = function () { - return _super.prototype.toString.call(this); - }; - - MyButton8.prototype.echo = function (s) { - return "echo: " + this.my1; - }; - - return MyButton8; + return MyButton9; })(com.tns.tests.Button1); - - MyButton8.setMyStaticIntField(5); - var valueUsingChild = MyButton8.getMyStaticIntField(); - Assert(valueUsingChild == 5, "FAILED: When_calling_a_static_method_on_a_typescript_instance_it_should_work."); - - var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); - Assert(valueUsingParent == 5, "FAILED: When_calling_a_static_method_on_a_typescript_instance_it_should_work."); - - com.tns.tests.Button1.setMyStaticIntField(6); - var valueUsingParent = com.tns.tests.Button1.getMyStaticIntField(); - Assert(valueUsingParent == 6, "FAILED: When_calling_a_static_method_on_a_typescript_instance_it_should_work."); - valueUsingChild = MyButton8.getMyStaticIntField(); - Assert(valueUsingChild == 6, "FAILED: When_calling_a_static_method_on_a_typescript_instance_it_should_work."); -})(); - -(function When_inherit_from_android_base_class_it_should_create_an_instance() { - /* - // From issue #137 https://github.com/telerik/Kimera/issues/137 - class ListViewAdapter extends android.widget.BaseAdapter { - private _items: Array; - - constructor(items: Array) { - super(); - - this._items = items; - } - - get items(): Array { - return this._items; - } - set items(value: Array) { - this._items = value; - } - - public getCount() { - return this._items ? this._items.length : 0; - } - - public getItem(i) { - return this._items && i < this._items.length ? this._items[i] : null; - } - - public getItemId(i) { - return long(0); - } - - public getView(i, view, viewGroup) { - return null; - } - - public refresh() { - this.notifyDataSetChanged(); - } - } - */ - var ListViewAdapter = (function (_super) { - __extends(ListViewAdapter, _super); - function ListViewAdapter(items) { - _super.call(this); - - this._items = items; - return __native(this); - } - Object.defineProperty(ListViewAdapter.prototype, "items", { - get: function () { - return this._items; - }, - set: function (value) { - this._items = value; - }, - enumerable: true, - configurable: true - }); - - ListViewAdapter.prototype.getCount = function () { - return this._items ? this._items.length : 0; - }; - - ListViewAdapter.prototype.getItem = function (i) { - return this._items && i < this._items.length ? this._items[i] : null; - }; - - ListViewAdapter.prototype.getItemId = function (i) { - return long(0); - }; - - ListViewAdapter.prototype.getView = function (i, view, viewGroup) { - return null; - }; - - ListViewAdapter.prototype.refresh = function () { - this.notifyDataSetChanged(); - }; - return ListViewAdapter; - })(android.widget.BaseAdapter); - - var adapter = new ListViewAdapter(); - - Assert(adapter != null, "FAILED: When_inherit_from_android_base_class_it_should_create_an_instance."); - -})(); - -(function When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work() { - - __log("TEST: When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work"); - - var MyButton9 = (function (_super) { - __extends(MyButton9, _super); - - function MyButton9() { - _super.call(this); - - var that = __native(this); - - that.setOnClickListener(new android.view.View.OnClickListener({ - onClick : function() { - that.buttonClicked = true; - } - })); - - return that; - } - - return MyButton9; - })(com.tns.tests.Button1); - - var button = new MyButton9(); - var button1 = new MyButton9(); - button.click(null); - - Assert(button.buttonClicked === true, "FAILED: When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work."); - Assert(button1.buttonClicked === undefined, "FAILED: When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work."); - - button.buttonClicked = false; - button1.click(null); - - Assert(button.buttonClicked === false, "FAILED: When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work."); - Assert(button1.buttonClicked === true, "FAILED: When_creating_a_typescript_instance_and_anonymous_interfaces_in_its_ctor_it_should_work."); -})(); \ No newline at end of file + var button = new MyButton9(); + var button1 = new MyButton9(); + button.click(null); + + expect(button.buttonClicked).toBe(true); + expect(button1.buttonClicked).toBe(undefined); + + button.buttonClicked = false; + button1.click(null); + + expect(button.buttonClicked).toBe(false); + expect(button1.buttonClicked).toBe(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testsMemoryManagement.js b/test-app/assets/app/tests/testsMemoryManagement.js index 14959c45e..e4fcbdcb4 100644 --- a/test-app/assets/app/tests/testsMemoryManagement.js +++ b/test-app/assets/app/tests/testsMemoryManagement.js @@ -1,23 +1,41 @@ -function TestSecondaryCallbackInvokationWithObjectParamsShouldWork() -{ - var u = new com.tns.tests.UseCallbackTest(123); +describe("Tests for memmory managment", function () { - u.setDataCallback(new com.tns.tests.UseCallbackTest.DataCallback("DataCallback_5", { - onData: function(data, delay) { - android.util.Log.i("TNS.TESTS", "data=" + data.getData()); - } - })); + var myCustomEquality = function(first, second) { + return first == second; + }; - u.setCleanCallback(new com.tns.tests.UseCallbackTest.CleanCallback("CleanCallback11", { - onClean: function(delay) { - gc(); - java.lang.System.gc(); - } - })); - - u.enqueDataCallback(0); - u.enqueDataCallback(10 * 1000); - u.enqueCleanCallback(0); -} + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); + + it("TestSecondaryCallbackInvokationWithObjectParamsShouldWork", function () { + + var u = new com.tns.tests.UseCallbackTest(123); + + u.setDataCallback(new com.tns.tests.UseCallbackTest.DataCallback("DataCallback_5", { + onData: function(data, delay) { + if("inner spec: ", function () { + android.util.Log.i("TNS.TESTS", "data=" + data.getData()); + expect(data).not.toEqual(undefined); + expect(delay).not.toEqual(undefined); + }); + } + })); + + u.setCleanCallback(new com.tns.tests.UseCallbackTest.CleanCallback("CleanCallback11", { + onClean: function(delay) { + if("inner spec: ", function () { + expect(delay).not.toEqual(undefined); + gc(); + java.lang.System.gc(); + }); + } + })); -TestSecondaryCallbackInvokationWithObjectParamsShouldWork(); + u.enqueDataCallback(0); + u.enqueDataCallback(10 * 1000); + u.enqueCleanCallback(0); + expect(true).toBe(true); + expect(true).toEqual(true); + }); +}); \ No newline at end of file diff --git a/test-app/assets/app/tests/testsWithContext.js b/test-app/assets/app/tests/testsWithContext.js index b55c4f196..78d581e40 100644 --- a/test-app/assets/app/tests/testsWithContext.js +++ b/test-app/assets/app/tests/testsWithContext.js @@ -1,113 +1,111 @@ -var Assert = function(condition, failMessage) { - if (condition == false) { - fail(failMessage); - } -} - -var TestConstructorOverrideForBuiltinType = function(context) { - - __log("TEST: TestConstructorOverrideForBuiltinType"); - - var ctorCalled = false; - var isConstructor = false; - - var MyButton = new android.widget.Button.extend({ - init : function() { - ctorCalled = true; - isConstructor = arguments[arguments.length - 1]; - } - }); - - var btn = new MyButton(context); - - Assert(ctorCalled == true, "TestConstructorOverrideForBuiltinType FAILED: constructor not called"); - Assert(isConstructor == true, "TestConstructorOverrideForBuiltinType FAILED: isConstructor should be 'true'"); -} +exports.run = function(cntxt) +{ + describe("Tests with context ", function () { + + var context = cntxt; + var myCustomEquality = function(first, second) { + return first == second; + }; + + beforeEach(function() { + jasmine.addCustomEqualityTester(myCustomEquality); + }); + + it("TestConstructorOverrideForBuiltinType", function () { + + __log("TEST: TestConstructorOverrideForBuiltinType"); + + var ctorCalled = false; + var isConstructor = false; -var TestConstructorOverrideForBuiltinTypeWithInitMethod = function(context) { + var MyButton = new android.widget.Button.extend({ + init : function() { + ctorCalled = true; + isConstructor = arguments[arguments.length - 1]; + } + }); + + var btn = new MyButton(context); + + expect(ctorCalled).toEqual(true); + expect(isConstructor).toEqual(true); + }); + + it("TestConstructorOverrideForBuiltinTypeWithInitMethod", function () { + + __log("TEST: TestConstructorOverrideForBuiltinTypeWithInitMethod"); + + var initInvocationCount = 0; - __log("TEST: TestConstructorOverrideForBuiltinTypeWithInitMethod"); - - var initInvocationCount = 0; + var MyDatePicker = android.widget.DatePicker.extend({ + init: function() { + ++initInvocationCount; + } + }); + + var datePicker = new MyDatePicker(context); + + __log("datePicker=" + datePicker); + + var count1 = initInvocationCount; + + expect(count1).toBeGreaterThan(0); + + datePicker.init(2014, 3, 25, null); + + var count2 = initInvocationCount; + + expect(count2).toBeGreaterThan(count1); + }); + + it("TestBuiltinNestedClassCreation", function () { + + __log("TEST: TestBuiltinNestedClassCreation"); + + var loader = new android.content.Loader(context); + + var observer = new loader.ForceLoadContentObserver(); + + expect(observer).not.toEqual(null); + }); + + it("TestPublicWindowManagerImplWithoutMetadata", function () { + + __log("TEST: TestPublicWindowManagerImplWithoutMetadata"); + + var windowManagerImpl = context.getSystemService(android.content.Context.WINDOW_SERVICE); + + var display = windowManagerImpl.getDefaultDisplay(); + + //__log("display.isValid=" + display.isValid()); + + var displayInfo = display.toString(); + + expect(displayInfo.length).toBeGreaterThan(0); + }); + + it("TestUsingClassFromAndroidSupportLibrary", function () { + + __log("TEST: TestUsingClassFromAndroidSupportLibrary"); - var MyDatePicker = android.widget.DatePicker.extend({ - init: function() { - ++initInvocationCount; - } + var layout = new android.support.v4.widget.DrawerLayout(context); + + expect(layout).not.toEqual(null); + }); + + it("TestCanPassCharSequenceArray", function () { + + __log("TEST: TestCanPassCharSequenceArray"); + + var alert = new android.app.AlertDialog.Builder(context); + + var builder = alert.setItems(["One", "Two" ], new android.content.DialogInterface.OnClickListener({ + onClick: function (dialog, which) { + // + } + })); + + expect(builder).not.toEqual(null); + }); }); - - var datePicker = new MyDatePicker(context); - - __log("datePicker=" + datePicker); - - var count1 = initInvocationCount; - - Assert(count1 > 0, "TestConstructorOverrideForBuiltinTypeWithInitMethod FAILED: initInvocationCount should be > 0"); - - datePicker.init(2014, 3, 25, null); - - var count2 = initInvocationCount; - - Assert(count2 > count1, "TestConstructorOverrideForBuiltinTypeWithInitMethod FAILED: initInvocationCount should be increased"); -} - -var TestBuiltinNestedClassCreation = function(context) { - - __log("TEST: TestBuiltinNestedClassCreation"); - - var loader = new android.content.Loader(context); - - var observer = new loader.ForceLoadContentObserver(); - - Assert(observer != null, "TestBuiltinNestedClassCreation FAILED: Cannot instantiate android.content.Loader.ForceLoadContentObserver class"); -} - - -var TestPublicWindowManagerImplWithoutMetadata = function(context) { - - __log("TEST: TestPublicWindowManagerImplWithoutMetadata"); - - var windowManagerImpl = context.getSystemService(android.content.Context.WINDOW_SERVICE); - - var display = windowManagerImpl.getDefaultDisplay(); - - //__log("display.isValid=" + display.isValid()); - - var displayInfo = display.toString(); - - Assert(displayInfo.length > 0, "TestPublicWindowManagerImplWithoutMetadata FAILED: Cannot obtain display info string from WindowManagerImpl instance"); -} - -var TestUsingClassFromAndroidSupportLibrary = function(context) { - - __log("TEST: TestUsingClassFromAndroidSupportLibrary"); - - var layout = new android.support.v4.widget.DrawerLayout(context); - - Assert(layout != null, "TestUsingClassFromAndroidSupportLibrary FAILED: Cannot create an instance of class from Android Support Library"); -} - -var TestCanPassCharSequenceArray = function(context) { - - __log("TEST: TestCanPassCharSequenceArray"); - - var alert = new android.app.AlertDialog.Builder(context); - - var builder = alert.setItems(["One", "Two" ], new android.content.DialogInterface.OnClickListener({ - onClick: function (dialog, which) { - // - } - })); - - Assert(builder != null, "TestCanPassCharSequenceArray: builder should be != null"); -} - -exports.run = function(context) -{ - TestConstructorOverrideForBuiltinType(context); - TestConstructorOverrideForBuiltinTypeWithInitMethod(context); - TestBuiltinNestedClassCreation(context); - TestPublicWindowManagerImplWithoutMetadata(context); - TestUsingClassFromAndroidSupportLibrary(context); - TestCanPassCharSequenceArray(context); -} \ No newline at end of file +}; \ No newline at end of file From da489fbfd9c40441352de82327d8d7f889c7695f Mon Sep 17 00:00:00 2001 From: plamen5kov Date: Mon, 4 May 2015 14:47:12 +0300 Subject: [PATCH 2/4] added grunt automatization added needed node module --- gruntfile.js | 22 ++++++++- test-app/ant.properties | 4 ++ test-app/custom_sign.keystore | Bin 0 -> 2245 bytes test-app/gruntfile.js | 82 ++++++++++++++++++++++++++++++++++ test-app/package.json | 16 +++++++ 5 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 test-app/ant.properties create mode 100644 test-app/custom_sign.keystore create mode 100644 test-app/gruntfile.js create mode 100644 test-app/package.json diff --git a/gruntfile.js b/gruntfile.js index 20896e8b6..5be46baf8 100644 --- a/gruntfile.js +++ b/gruntfile.js @@ -195,7 +195,19 @@ module.exports = function(grunt) { }, runMetadataGenerator: { cmd: "./node_modules/.bin/generate-metadata " + localCfg.libsDir + " ./dist/framework/assets/metadata" - } + }, + runTests: { + cmd: "npm install && grunt --verbose", + cwd: "./test-app" + }, + antCleanBindingGenerator: { + cmd: "ant clean", + cwd: "./binding-generator/Generator/" + }, + antCleanRunTime: { + cmd: "ant clean", + cwd: "./src/" + }, } }); @@ -206,7 +218,7 @@ module.exports = function(grunt) { grunt.loadNpmTasks("grunt-replace"); grunt.registerTask("generateRuntime", [ - "exec:generateRuntime" + "exec:generateRuntime" ]); grunt.registerTask("generateMetadata", [ @@ -230,6 +242,12 @@ module.exports = function(grunt) { return []; } })()); + + grunt.registerTask("test", [ + "exec:antCleanBindingGenerator", + "exec:antCleanRunTime", + "exec:runTests" + ]); grunt.registerTask("default", [ "clean:build", diff --git a/test-app/ant.properties b/test-app/ant.properties new file mode 100644 index 000000000..e009510c5 --- /dev/null +++ b/test-app/ant.properties @@ -0,0 +1,4 @@ +key.store.password=aaaaaa +key.alias.password=aaaaaa +key.store=./custom_sign.keystore +key.alias=aaaa-alias \ No newline at end of file diff --git a/test-app/custom_sign.keystore b/test-app/custom_sign.keystore new file mode 100644 index 0000000000000000000000000000000000000000..30c13d52676217890c18c35b40da3298bf36eeb6 GIT binary patch literal 2245 zcmchYc{J1w7sux}hOx}p%M#J*kuVrEc(R0$ANk&VxW8@SX#IyP(IO zsd^B6JOcNSb!FDL7zo4*ASjR>gfO3=3LgLgPJqP#fENUzKz$boG9Y0B5wdWklXNZ8brt(({^0tacrhV1KN(1C9t8orY6r)5)2rZFoha-)RB zb7%d+-*-~;#Z&nbm_;x$O>^`tpc@P07O^>=iBZLq6^Z zy3FfQeAKO>jo~eGYfB2%sF@Dyu~TvSc1HuJ9}l~tgp8Lbty^I@TGZ+T_Gt{fR@bQoX0_4aKbZ4~yQazVCLo)`MlPi> zzRnbywis-h{3>w;|gMGo< zk>D29vy!9FA-{E4+!uM&o~mv9^m8Oe;9Oy7&5)(?)iKUWP+V*B0zwOr ze;E5fO&zwgsxoA`fMdiF1N78QGB5*IAl@~W7xf(fa%YY5x!{7MxwlgKNs5_O!tkNu z_DR4i@t)IGYwb2<HkP*dhos+YBVWv_|h`OTh4iSslFC+$iy52}v=wAZ~p+J=7#plCNNI&5rgJyaZ7>{5n}M4`|6 zt;dbGm*c$els~uAJqA}VeYJTy+OLGx&as26@iqjccaYt{d0=z=V4H*9oHt)DWTwdd$@AdKTVQKtw{M@FU7FWg= z&H2F5mI~Lqbdy{wjw0truFblMKC;>597E4Aw$u>3vcm zT2?$=54sU6OUFXd5n%6g;rs6oCV8o&6+ZourCYGo<8wwpW?4+I!$nlmUsG&10r+7Y z@3SLcZIzU)(pXj_t|#wNoLPfSZCFaeUW($^GV`!tQ;V5YM#|#(+30+Sse6&C!RO9? zZmoISGJmm0Pbo;Yex>=W>_d#ZRH`Mes&cg??c#-f$9Y+tk%UDtj#s~L=d>`x3Ei3b z-Jh0_NxM7$P6G!NPFf-RC#c`IiE8hH0=FNi-;g?Q2OVlJf&YiHSPSHlpZfJD~?HlSvz4P6j1z zuDY#CtT}b8t!nE6Y?;yzn}}-86k8wm@8W@$WK4jn!{oMdKGVhB!rT3Pn}d&=Zz%?h zfsT!Ylm>U5bq_?FJ@D*7a59D`Qc(d-Q`4@u8$I0Gg18mj4)gVf!1BM3Bku(@Z3GGg z;t57jcy1ynV7F`@FaQQaT&bLo2sod>iCBx+bvOVB@q!R|4bi=e$%BFLNkB0~Jkc+R z_&>t`3xWPZ1b-ny|0g1Q#r87uNbva+Jg$2Z5eKE<8rle?22w*CiPF%)O2Ltuh*MgK z|Azl=GZf(PKgHO46+9F`1caaff?x^&fF75XSwxid8j*4235b0R^cA z#_Ly~X;XpHBH(2rj5gplDi(AtG3P{2G^V(aDU~wN?Sr7t_mxaPja2&5?uQbE;NbM zA-^|8d11(Yh@^;~!C}?{RYx)EYJF3l z=HSsO!PI|>xVKSzA_5@U1^nbF`57+e-Vvxhe0VX}OjUpDvV{9|C_o!)`x+pqOcN!( zvs1L{6+FTl%dHyP&74cIg;w+$e#Gg(`%OoScI<_ZHoNdW+Qp$}PHWLN&q|ATe}6er zC0Ev~zZD6bR;3EaC*BZ|7G{y#N!LX;1OhC=lcS*sZRFU7hQ+Mo?(AjK!L^_~P{^H# zsYP-crs6l__KYP~i$bLH3%-#NnP|SA_DnysHs|(jwKQ_DDL?=G%bG0c%!br82BgzD zsibQtn0xt{ Date: Thu, 7 May 2015 10:41:21 +0300 Subject: [PATCH 3/4] added timeout to adb install command --- test-app/gruntfile.js | 14 +++++++------- test-app/tasks/deploy-apk.js | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 7 deletions(-) create mode 100644 test-app/tasks/deploy-apk.js diff --git a/test-app/gruntfile.js b/test-app/gruntfile.js index 0e32373e2..3053af3e3 100644 --- a/test-app/gruntfile.js +++ b/test-app/gruntfile.js @@ -21,7 +21,7 @@ module.exports = function(grunt) { grunt.initConfig({ wait: { - forDelay: { + timeToRunTests: { options: { delay: 20000 } @@ -40,15 +40,15 @@ module.exports = function(grunt) { } }, exec: { - createTestAppBuildFile: { + createBuildXml: { cmd: "android update project --path ." }, runAntCleanRelease: { cmd: "ant release" }, installApkOnDevice: { - cmd: "adb install -r NativeScriptActivity-release.apk", - cwd: "./bin" + cmd: "node ./tasks/deploy-apk.js ./bin/NativeScriptActivity-release.apk", + cwd: "." }, startInstalledApk: { cmd: "adb shell am start -n com.tns.android_runtime_testapp/com.tns.NativeScriptActivity -a android.intent.action.MAIN -c android.intent.category.LAUNCHER", @@ -71,11 +71,11 @@ module.exports = function(grunt) { grunt.registerTask("default", [ "clean:build", "mkdir:build", - "exec:createTestAppBuildFile", - "exec:runAntCleanRelease", + "exec:createBuildXml", + "exec:runAntCleanRelease", "exec:installApkOnDevice", "exec:startInstalledApk", - "wait:forDelay", + "wait:timeToRunTests", "exec:copyResultToDist" ]); diff --git a/test-app/tasks/deploy-apk.js b/test-app/tasks/deploy-apk.js new file mode 100644 index 000000000..776cd8646 --- /dev/null +++ b/test-app/tasks/deploy-apk.js @@ -0,0 +1,31 @@ +// This node app deploys apk file on device +// Parameters: +// - Path to APK to deploy + +if (process.argv.length < 2) { + console.error('Expect path to apk file to install'); + process.exit(1); +} + +var apk = process.argv[2]; + +var proc = require('child_process'); + +var deployTimeout = 180000; // 3 minutes to deploy and launch. + +var cmd = 'adb install -r ' + apk; + +function timeoutFunction(msg) { + console.error(msg); + testrun.kill(); + process.exit(1); +}; + +var timeout = setTimeout(function() { timeoutFunction("ERROR: Deploy timeout!"); }, deployTimeout); + +console.log("Executing adb install: " + cmd); +var testrun = proc.exec(cmd, function(error, stdout, stderr) { + // If the process exits prematurely kill the timer anyway... + clearTimeout(timeout); +}); +testrun.stderr.pipe(process.stderr, { end: false }); \ No newline at end of file From 39941adabf57a73fe82dde0232d3245193c1022f Mon Sep 17 00:00:00 2001 From: plamen5kov Date: Thu, 7 May 2015 16:29:07 +0300 Subject: [PATCH 4/4] fix gruntfile to work with references runtime and binding generator changed manifest so it runs on newer devices --- test-app/AndroidManifest.xml | 2 +- test-app/custom_rules.xml | 87 ++++++++++++++++++++++++++++++++++++ test-app/gruntfile.js | 41 ++++++++++------- 3 files changed, 114 insertions(+), 16 deletions(-) create mode 100644 test-app/custom_rules.xml diff --git a/test-app/AndroidManifest.xml b/test-app/AndroidManifest.xml index 6f8a1f6be..714a14ed6 100644 --- a/test-app/AndroidManifest.xml +++ b/test-app/AndroidManifest.xml @@ -5,7 +5,7 @@ + android:targetSdkVersion="22" /> diff --git a/test-app/custom_rules.xml b/test-app/custom_rules.xml new file mode 100644 index 000000000..47477411c --- /dev/null +++ b/test-app/custom_rules.xml @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/test-app/gruntfile.js b/test-app/gruntfile.js index 3053af3e3..09807eb45 100644 --- a/test-app/gruntfile.js +++ b/test-app/gruntfile.js @@ -4,33 +4,26 @@ module.exports = function(grunt) { var pathModule = require("path"); - var args = { - buildVersion: grunt.option("build-version") || "0.0.1", - commitVersion: grunt.option("commit-version") || process.env.GIT_COMMIT || "" - }; - var localCfg = { rootDir: ".", outDir: "./dist", - commitVersion: args.commitVersion, }; - localCfg.jniDir = pathModule.join(localCfg.rootDir, "/jni"), - localCfg.runtimeVersionHFile = pathModule.join(localCfg.rootDir, "/jni/Version.h"), - localCfg.applicationMkFile = pathModule.join(localCfg.rootDir, "/jni/Application.mk"), - grunt.initConfig({ wait: { timeToRunTests: { options: { - delay: 20000 + delay: 180000 } } }, clean: { build: { src: [localCfg.outDir] - } + }, + metadata: { + src: "./assets/metadata/*" + } }, mkdir: { build: { @@ -43,7 +36,7 @@ module.exports = function(grunt) { createBuildXml: { cmd: "android update project --path ." }, - runAntCleanRelease: { + runAntRelease: { cmd: "ant release" }, installApkOnDevice: { @@ -58,7 +51,20 @@ module.exports = function(grunt) { cmd: "adb pull /sdcard/android_unit_test_results.xml", cwd: localCfg.outDir } - } + }, + copy: { + //these .so files need to be in the src/libs folder because the test-app refers them + //later if we want to separate the tests from the build, these files can be taken from k:distributions ... stable/android-runtime/ ... + generatedLibraries: { + expand: true, + cwd: "../src/dist/libs/", + src: [ + "**/armeabi-v7a/*", + "**/x86/*" + ], + dest: "../src/libs/" + } + } }); grunt.loadNpmTasks("grunt-contrib-clean"); @@ -71,8 +77,13 @@ module.exports = function(grunt) { grunt.registerTask("default", [ "clean:build", "mkdir:build", + "copy:generatedLibraries", "exec:createBuildXml", - "exec:runAntCleanRelease", + + //currently runAntRelease step includes an ant custom build step which generates latest greatest metadata + //currently we generate metadata using the target sdk declared in the AndroidManifest file and if the sdk is missing the build will fail + "exec:runAntRelease", + "exec:installApkOnDevice", "exec:startInstalledApk", "wait:timeToRunTests",