Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion test-app/app/src/main/assets/app/mainpage.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ require("./tests/testGC");
require("./tests/testsMemoryManagement");
require("./tests/testFieldGetSet");
require("./tests/extendedClassesTests");
//require("./tests/extendClassNameTests"); // as tests now run with SBG, this test fails the whole build process
require("./tests/extendClassNameTests");
require("./tests/testJniReferenceLeak");
require("./tests/testNativeModules");
require("./tests/requireExceptionTests");
Expand Down Expand Up @@ -125,6 +125,7 @@ require('./tests/testWorkerEsmEntry');
require('./tests/testWorkerLifetime');
// Java->JS calls route to the runtime that created the object
require('./tests/testRuntimeBoundDispatch');
require('./tests/testConcurrentProxyGeneration');
// Fetches from the in-app loopback fixture server, so it goes last
require('./tests/testEsmHttpLoader');
// Node-API addon surface
Expand Down
131 changes: 90 additions & 41 deletions test-app/app/src/main/assets/app/tests/extendClassNameTests.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,92 @@
// extend() is called through a computed member so the static binding generator skips
// these call sites: it would try, and fail, to compile a class for each name.
describe("Tests extend class name ", function () {

var myCustomEquality = function(first, second) {
return first == second;
};

beforeEach(function() {
jasmine.addCustomEqualityTester(myCustomEquality);
});

//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);
// });
//
// 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;
// }
//
// expect(exceptionCaught).toBe(true);
// });
});
function extendObject(name, implementation) {
return java.lang.Object["extend"](name, implementation);
}

function expectRejected(name) {
var message = null;
try {
extendObject(name, {});
} catch (e) {
message = e.message;
}
expect(message).not.toBeNull();
expect(message).toContain(name);
}

// the class name valid symbols are [a-z , A-Z , 0-9, _]
it("When_naming_extension_class_user_should_give_valid_name", function () {
expect(function () {
extendObject("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789", {});
}).not.toThrow();
});

it("When_naming_extension_contains_invalid_symbols_should_throw_exception", function () {
expect(function () {
extendObject("1235!", {});
}).toThrowError(/invalid symbols/);
});

it("rejects a dotted name with an empty part", function () {
expectRejected("com.tns.tests.extendname..Empty");
expectRejected(".com.tns.tests.extendname.Leading");
expectRejected("com.tns.tests.extendname/.Slash");
expectRejected("com.tns.tests.extendname.Trailing.");
});

it("rejects a dotted name with a character no class name can contain", function () {
expectRejected("com.tns.tests.extendname.Has Space");
expectRejected("com.tns.tests.extendname.Has;Semicolon");
expectRejected("com.tns.tests.extendname.Has[Bracket");
expectRejected("com.tns.tests.extendname.Has<Angle>");
expectRejected("com.tns.tests.extendname.No\u00A0Break");
expectRejected("com.tns.tests.extendname.Zero\u200BWidth");
});

function expectWorkingClass(name, className) {
className = className || name;
var Extended = extendObject(name, {
toString: function () {
return "from " + name;
}
});
var instance = new Extended();

expect(instance.getClass().getName()).toBe(className);
// Objects.toString calls toString() from Java, through the generated class.
expect(java.util.Objects.toString(instance)).toBe("from " + name);
}

it("generates a class for a dotted name whose part starts with a digit", function () {
expectWorkingClass("com.tns.tests.extendname.1LeadingDigit");
});

it("generates a class for a dotted name whose part contains a dash", function () {
expectWorkingClass("com.tns.tests.extend-name.Dashed");
});

it("generates a class for a dotted name whose part is a Java reserved word", function () {
expectWorkingClass("com.tns.tests.extendname.int");
});

it("generates a class for a dotted name with a non-ASCII letter", function () {
expectWorkingClass("com.tns.tests.extendname.Caf\u00E9");
});

it("does not reject a dotted name with a supplementary-plane letter", function () {
var message = null;
try {
extendObject("com.tns.tests.extendname.Script\uD835\uDC9C", {});
} catch (e) {
message = e.message;
}
expect(message === null ? "" : message).not.toContain("Invalid extend() name");
});

it("reads a '/' in a dotted name as a package separator", function () {
expectWorkingClass("com.tns.tests.extendname/Slashed", "com.tns.tests.extendname.Slashed");
});
});
104 changes: 104 additions & 0 deletions test-app/app/src/main/assets/app/tests/proxyGenerationJob.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
// Generates a set of named proxies unique to `tag` and has Java call every overridden
// method through each generated class. Returns a description of every check that failed.
//
// extend() is called through a computed member so the static binding generator does not
// precompile these classes: they must be generated at runtime by the calling runtime.
module.exports = function generateAndCallProxies(tag) {
var failures = [];
var prefix = "com.tns.tests.proxygen." + tag + ".";

function check(what, actual, expected) {
if (actual !== expected) {
failures.push(tag + " " + what + ": expected " + expected + ", got " + actual);
}
}

function attempt(what, body) {
try {
body();
} catch (e) {
failures.push(tag + " " + what + " threw: " + e);
}
}

attempt("Comparator", function () {
var ByLength = java.util.Comparator["extend"](prefix + "ByLength", {
compare: function (a, b) {
return a.length - b.length;
}
});
var list = java.util.Arrays.asList(["aa", "a", "aaaa", "aaa"]);
check("Collections.max(compare)", java.util.Collections.max(list, new ByLength()), "aaaa");
});

attempt("Callable", function () {
var Answer = java.util.concurrent.Callable["extend"](prefix + "Answer", {
call: function () {
return "called " + tag;
}
});
var task = new java.util.concurrent.FutureTask(new Answer());
task.run();
check("FutureTask.get(call)", task.get(), "called " + tag);
});

attempt("Runnable", function () {
var ran = false;
var Task = java.lang.Runnable["extend"](prefix + "Task", {
run: function () {
ran = true;
}
});
new java.lang.Thread(new Task()).run();
check("Thread.run(run)", ran, true);
});

attempt("InputStream", function () {
var Stream = java.io.InputStream["extend"](prefix + "Stream", {
read: function () {
return 42;
},
skip: function (n) {
return n * 2;
},
available: function () {
return 5;
}
});
var stream = new java.io.PushbackInputStream(new Stream());
check("read()", stream.read(), 42);
check("skip(long)", stream.skip(21), 42);
check("available()", stream.available(), 5);
});

attempt("OutputStream", function () {
var written = [];
var Sink = java.io.OutputStream["extend"](prefix + "Sink", {
write: function (b) {
written.push(b);
}
});
new java.io.DataOutputStream(new Sink()).writeShort(0x0102);
check("DataOutputStream.writeShort(write)", written.join(","), "1,2");
});

attempt("Object", function () {
var Value = java.lang.Object["extend"](prefix + "Value", {
toString: function () {
return "value " + tag;
},
hashCode: function () {
return 1234;
},
equals: function (other) {
return other === "same";
}
});
var value = new Value();
check("Objects.toString(toString)", java.util.Objects.toString(value), "value " + tag);
check("Objects.hashCode(hashCode)", java.util.Objects.hashCode(value), 1234);
check("Objects.equals(equals)", java.util.Objects.equals(value, "same"), true);
});

return failures;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Entry for testConcurrentProxyGeneration: waits for "go", then generates and calls
// this worker's proxies.
var generateAndCallProxies = require("./proxyGenerationJob");

onmessage = function (msg) {
postMessage(generateAndCallProxies(msg.data));
};

postMessage("ready");
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Every runtime generates proxies with its own generator, on its own thread. Several
// workers and this runtime generate different classes at once; each class must come
// out intact, which Java proves by calling every overridden method through it.
describe("Concurrent runtime proxy generation", function () {
var generateAndCallProxies = require("./proxyGenerationJob");
var WORKERS = 3;
var DEADLINE_MS = 60000;

it("generates intact classes in several runtimes at once", function (done) {
var workers = [];
var ready = 0;
var pending = WORKERS;
var failures = [];
var finished = false;

function finish() {
if (finished) {
return;
}
finished = true;
clearTimeout(timer);
workers.forEach(function (worker) {
worker.terminate();
});
expect(failures).toEqual([]);
done();
}

var timer = setTimeout(function () {
failures.push(pending + " worker(s) did not report within " + DEADLINE_MS + "ms");
finish();
}, DEADLINE_MS);

function start() {
workers.forEach(function (worker, index) {
worker.postMessage("w" + index);
});
failures = failures.concat(generateAndCallProxies("main"));
}

for (var i = 0; i < WORKERS; i++) {
var worker = new Worker("./proxyGenerationWorker.js");
worker.onmessage = function (msg) {
if (msg.data === "ready") {
if (++ready === WORKERS) {
start();
}
return;
}
failures = failures.concat(msg.data);
if (--pending === 0) {
finish();
}
};
worker.onerror = function (e) {
failures.push("worker error: " + (e && e.message));
if (--pending === 0) {
finish();
}
};
workers.push(worker);
}
}, 90000);
});
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,6 @@ public class Dump {
static final String RUNTIME_TAG_FIELD_NAME = "runtimeTag__ns";
static final String OBJECT_ID_FIELD_NAME = "objectId__ns";

static final StringBuffer methodDescriptorBuilder = new StringBuffer();


/**
* Returns the dex descriptor corresponding to the given method.
*
Expand All @@ -38,7 +35,7 @@ public class Dump {
*/
public String getDexMethodDescriptor(final MethodDescriptor method) {
ClassDescriptor[] parameters = method.getParameterTypes();
methodDescriptorBuilder.setLength(0);
StringBuffer methodDescriptorBuilder = new StringBuffer();
getDexDescriptor(methodDescriptorBuilder, method.getReturnType());
for (int i = 0; i < parameters.length; ++i) {
getDexDescriptor(methodDescriptorBuilder, parameters[i]);
Expand All @@ -55,7 +52,7 @@ public String getDexMethodDescriptor(final MethodDescriptor method) {
*/
public String getMethodOverloadDescriptor(final MethodDescriptor method) {
ClassDescriptor[] parameters = method.getParameterTypes();
methodDescriptorBuilder.setLength(0);
StringBuffer methodDescriptorBuilder = new StringBuffer();
for (int i = 0; i < parameters.length; ++i) {
getDexDescriptor(methodDescriptorBuilder, parameters[i]);
}
Expand All @@ -71,7 +68,7 @@ public String getMethodOverloadDescriptor(final MethodDescriptor method) {
*/
public String getDexConstructorDescriptor(final MethodDescriptor constructor) {
ClassDescriptor[] parameters = constructor.getParameterTypes();
methodDescriptorBuilder.setLength(0);
StringBuffer methodDescriptorBuilder = new StringBuffer();
getDexDescriptor(methodDescriptorBuilder, ClassDescriptor.VOID);
for (int i = 0; i < parameters.length; ++i) {
getDexDescriptor(methodDescriptorBuilder, parameters[i]);
Expand Down Expand Up @@ -841,7 +838,6 @@ private void generateFields(ClassVisitor cv) {
}

static final String[] classImplentedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "Lcom/tns/NativeScriptRuntimeBound;" };
static final String[] interfaceImplementedInterfaces = new String[] { "Lcom/tns/NativeScriptHashCodeProvider;", "Lcom/tns/NativeScriptRuntimeBound;", "" };

private ClassVisitor generateClass(ApplicationWriter aw, ClassDescriptor classTo, String classSignature, String tnsClassSignature, HashSet<ClassDescriptor> implementedInterfaces, AnnotationDescriptor[] annotations) {
ClassVisitor cv;
Expand All @@ -851,11 +847,8 @@ private ClassVisitor generateClass(ApplicationWriter aw, ClassDescriptor classTo
ArrayList<String> interfacesToImplement = new ArrayList(Arrays.asList(classImplentedInterfaces));

if (classTo.isInterface()) {
interfaceImplementedInterfaces[interfaceImplementedInterfaces.length - 1] = classSignature;
for (String interfaceToImpl : interfaceImplementedInterfaces) {
if (!interfacesToImplement.contains(interfaceToImpl)) {
interfacesToImplement.add(interfaceToImpl);
}
if (!interfacesToImplement.contains(classSignature)) {
interfacesToImplement.add(classSignature);
}

classSignature = objectClass;
Expand Down
Loading
Loading