/interpreter/tags/at2-build190607/test/edu/vub/at/objects/symbiosis/SymbiosisTest.java

http://ambienttalk.googlecode.com/ · Java · 821 lines · 479 code · 76 blank · 266 comment · 4 complexity · 07a400535709a683be30865708a2bb97 MD5 · raw file

  1. /**
  2. * AmbientTalk/2 Project
  3. * SymbiosisTest.java created on 13-nov-2006 at 15:10:58
  4. * (c) Programming Technology Lab, 2006 - 2007
  5. * Authors: Tom Van Cutsem & Stijn Mostinckx
  6. *
  7. * Permission is hereby granted, free of charge, to any person
  8. * obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without
  10. * restriction, including without limitation the rights to use,
  11. * copy, modify, merge, publish, distribute, sublicense, and/or
  12. * sell copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following
  14. * conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be
  17. * included in all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  26. * OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. package edu.vub.at.objects.symbiosis;
  29. import edu.vub.at.AmbientTalkTest;
  30. import edu.vub.at.eval.Evaluator;
  31. import edu.vub.at.exceptions.InterpreterException;
  32. import edu.vub.at.exceptions.XArityMismatch;
  33. import edu.vub.at.exceptions.XClassNotFound;
  34. import edu.vub.at.exceptions.XDuplicateSlot;
  35. import edu.vub.at.exceptions.XIllegalOperation;
  36. import edu.vub.at.exceptions.XNotInstantiatable;
  37. import edu.vub.at.exceptions.XSelectorNotFound;
  38. import edu.vub.at.exceptions.XSymbiosisFailure;
  39. import edu.vub.at.exceptions.XTypeMismatch;
  40. import edu.vub.at.exceptions.XUnassignableField;
  41. import edu.vub.at.objects.ATClosure;
  42. import edu.vub.at.objects.ATField;
  43. import edu.vub.at.objects.ATMethod;
  44. import edu.vub.at.objects.ATObject;
  45. import edu.vub.at.objects.ATTypeTag;
  46. import edu.vub.at.objects.natives.NATContext;
  47. import edu.vub.at.objects.natives.NATException;
  48. import edu.vub.at.objects.natives.NATFraction;
  49. import edu.vub.at.objects.natives.NATNil;
  50. import edu.vub.at.objects.natives.NATNumber;
  51. import edu.vub.at.objects.natives.NATObject;
  52. import edu.vub.at.objects.natives.NATTable;
  53. import edu.vub.at.objects.natives.NATText;
  54. import edu.vub.at.objects.natives.grammar.AGSymbol;
  55. import edu.vub.at.objects.natives.grammar.TestEval;
  56. import java.io.Serializable;
  57. import java.util.Collection;
  58. import java.util.List;
  59. import java.util.Set;
  60. import java.util.Vector;
  61. /**
  62. * Tests the symbiosis with Java. This is primarily done by wrapping
  63. * the SymbiosisTest class and instances itself and invoking some of
  64. * their non-test prefixed methods.
  65. *
  66. * @author tvcutsem
  67. */
  68. public class SymbiosisTest extends AmbientTalkTest {
  69. public static void main(String[] args) {
  70. junit.swingui.TestRunner.run(TestEval.class);
  71. /*Test test= new SymbiosisTest() {
  72. public void runTest() throws Exception {
  73. testBugfixOverloadedConstructor();
  74. }
  75. };
  76. junit.textui.TestRunner.run(test);*/
  77. }
  78. // test fixture
  79. private Class jTestClass;
  80. private JavaClass atTestClass;
  81. private SymbiosisTest jTestObject;
  82. private JavaObject atTestObject;
  83. private JavaPackage jLobby_;
  84. // these fields and methods will be reflectively invoked from within AmbientTalk
  85. public int xtest;
  86. public static String ytest = "AmbientTalk";
  87. public SymbiosisTest(int xval) {
  88. xtest = xval;
  89. }
  90. public SymbiosisTest() {
  91. xtest = 0;
  92. }
  93. public SymbiosisTest(SymbiosisTest t) {
  94. xtest = -1;
  95. }
  96. public SymbiosisTest(AmbientTalkTest t) {
  97. xtest = -1;
  98. }
  99. private static class ExceptionTest extends Exception {
  100. private static final long serialVersionUID = 1L;
  101. }
  102. public SymbiosisTest(JavaClass c) throws ExceptionTest {
  103. throw new ExceptionTest();
  104. }
  105. public static final int TEST_OBJECT_INIT = 42;
  106. public int gettertest() { return xtest; }
  107. public void settertest(int xval) { xtest = xval; }
  108. public static String prefix(String msg) { return msg + ytest; }
  109. public boolean identitytest(Object obj) { return obj == this; }
  110. public String overloadedtest() { return "()"; }
  111. public String overloadedtest(int x) { return "(int)"; }
  112. public String overloadedtest(Object[] vals) { return "(Object[])"; }
  113. public String overloadedtest(double x) { return "(double)"; }
  114. public String overloadedtest(SymbiosisTest x) { return "(SymbiosisTest)"; }
  115. public Object overloadedvararg(ATObject[] varargs) { return null; }
  116. public int overloadedvararg(int x) { return x; }
  117. public String overloadedmatch2(Object x) { return "(Object)"; }
  118. public String overloadedmatch2(SymbiosisTest x) { return "(SymbiosisTest)"; }
  119. public void setUp() {
  120. jTestClass = SymbiosisTest.class;
  121. atTestClass = JavaClass.wrapperFor(SymbiosisTest.class);
  122. jTestObject = new SymbiosisTest(TEST_OBJECT_INIT);
  123. atTestObject = JavaObject.wrapperFor(jTestObject);
  124. jLobby_ = new JavaPackage("");
  125. }
  126. /**
  127. * Test the conversion function Symbiosis.ambientTalkToJava for various kinds of input.
  128. */
  129. public void testAT2JavaConversion() {
  130. try {
  131. // -- WRAPPED JAVA OBJECTS --
  132. assertEquals(jTestObject, Symbiosis.ambientTalkToJava(atTestObject, SymbiosisTest.class));
  133. // -- PRIMITIVE TYPES --
  134. assertEquals(new Integer(5), Symbiosis.ambientTalkToJava(NATNumber.atValue(5), int.class));
  135. // -- STRINGS --
  136. assertEquals(ytest, Symbiosis.ambientTalkToJava(NATText.atValue(ytest), String.class));
  137. // -- ARRAYS --
  138. assertEquals(0.5, ((double[]) Symbiosis.ambientTalkToJava(NATTable.atValue(new ATObject[] { NATFraction.atValue(0.5) }), double[].class))[0], 0.0);
  139. // -- EXCEPTIONS --
  140. assertEquals(XIllegalOperation.class, Symbiosis.ambientTalkToJava(new XIllegalOperation("AT2JavaTest").getAmbientTalkRepresentation(), Exception.class).getClass());
  141. // -- CLASS OBJECTS --
  142. assertEquals(jTestClass, Symbiosis.ambientTalkToJava(atTestClass, Class.class));
  143. // -- nil => NULL if converting to Java --
  144. assertEquals(null, Symbiosis.ambientTalkToJava(NATNil._INSTANCE_, Runnable.class));
  145. // -- nil => nil if remaining within AT --
  146. assertEquals(NATNil._INSTANCE_, Symbiosis.ambientTalkToJava(NATNil._INSTANCE_, ATObject.class));
  147. // beware with types such as java.lang.Object that match both Java and AT types!
  148. // if the ATObject can be assigned to the Java type, the ATObject will be kept
  149. assertEquals(NATNil._INSTANCE_, Symbiosis.ambientTalkToJava(NATNil._INSTANCE_, Object.class));
  150. // -- INTERFACE TYPES AND NAT CLASSES --
  151. assertTrue(Symbiosis.ambientTalkToJava(new NATObject(), Runnable.class) instanceof Runnable);
  152. try {
  153. Symbiosis.ambientTalkToJava(new NATObject(), Symbiosis.class);
  154. fail();
  155. } catch (XTypeMismatch e) {
  156. // expected: coercion does not work for non-interface class types
  157. }
  158. } catch (InterpreterException e) {
  159. fail(e.getMessage());
  160. }
  161. }
  162. /**
  163. * Test the conversion function Symbiosis.javaToAmbientTalk for various kinds of input.
  164. */
  165. public void testJava2ATConversion() {
  166. try {
  167. // -- WRAPPED JAVA OBJECTS --
  168. assertEquals(atTestObject, Symbiosis.javaToAmbientTalk(jTestObject));
  169. // -- PRIMITIVE TYPES --
  170. assertEquals(NATNumber.atValue(5), Symbiosis.javaToAmbientTalk(new Integer(5)));
  171. // -- STRINGS --
  172. assertEquals(NATText.atValue(ytest), Symbiosis.javaToAmbientTalk(ytest));
  173. // -- ARRAYS --
  174. assertEquals(NATFraction.atValue(0.5), Symbiosis.javaToAmbientTalk(new double[] { 0.5 }).asNativeTable().elements_[0]);
  175. // -- EXCEPTIONS --
  176. assertEquals(XIllegalOperation.class, ((NATException)Symbiosis.javaToAmbientTalk(new XIllegalOperation("Java2ATTest"))).getWrappedException().getClass());
  177. // -- CLASS OBJECTS --
  178. assertEquals(atTestClass, Symbiosis.javaToAmbientTalk(jTestClass));
  179. // -- nil => NULL --
  180. assertEquals(NATNil._INSTANCE_, Symbiosis.javaToAmbientTalk(null));
  181. // -- INTERFACE TYPES AND NAT CLASSES --
  182. ATObject orig = new NATObject();
  183. Object proxy = Symbiosis.ambientTalkToJava(orig, Runnable.class);
  184. assertEquals(orig, Symbiosis.javaToAmbientTalk(proxy));
  185. } catch (InterpreterException e) {
  186. fail(e.getMessage());
  187. }
  188. }
  189. /**
  190. * Invokes the two instance methods gettertest and settertest on atTestObject.
  191. * Also performs a selection of the field 'xtest'
  192. *
  193. * Also invokes the method 'identitytest' to see whether AT->Java conversion does proper unwrapping
  194. */
  195. public void testWorkingInstanceInvocation() {
  196. try {
  197. // def result := atTestObject.gettertest(); assert(42 == result)
  198. ATObject result = atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("gettertest"), NATTable.EMPTY);
  199. assertEquals(TEST_OBJECT_INIT, result.asNativeNumber().javaValue);
  200. // result := atTestObject.settertest(1); assert(result == nil); assert(atTestObject.xtest == 1)
  201. result = atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("settertest"), NATTable.atValue(new ATObject[] { NATNumber.ONE }));
  202. assertEquals(NATNil._INSTANCE_, result);
  203. assertEquals(1, jTestObject.xtest);
  204. // result := atTestObject.xtest
  205. result = atTestObject.meta_select(atTestObject, AGSymbol.jAlloc("xtest"));
  206. assertEquals(NATNumber.ONE, result);
  207. // atTestObject.identitytest(atTestObject) == atTestObject
  208. assertTrue(atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("identitytest"),
  209. NATTable.atValue(new ATObject[] { atTestObject })).asNativeBoolean().javaValue);
  210. } catch (InterpreterException e) {
  211. fail(e.getMessage());
  212. }
  213. }
  214. /**
  215. * Invokes the class method 'prefix' and performs a selection and assignment of the static 'ytest' field
  216. */
  217. public void testWorkingClassInvocation() {
  218. try {
  219. // def result := atTestClass.prefix("Hello, "); assert("Hello, " + ytest == result)
  220. String txt = "Hello, ";
  221. NATText prefix = NATText.atValue(txt);
  222. ATObject result = atTestClass.meta_invoke(atTestClass, AGSymbol.jAlloc("prefix"), NATTable.atValue(new ATObject[] { prefix }));
  223. assertEquals(txt + ytest, result.asNativeText().javaValue);
  224. // result := atTestClass.ytest; assert(result == ytest);
  225. result = atTestClass.meta_select(atTestClass, AGSymbol.jAlloc("ytest"));
  226. assertEquals(ytest, result.asNativeText().javaValue);
  227. // atTestClass.ytest := "Hello, "; assert(ytest == "Hello, ")
  228. result = atTestClass.meta_assignField(atTestClass, AGSymbol.jAlloc("ytest"), prefix);
  229. assertEquals(NATNil._INSTANCE_, result);
  230. assertEquals(txt, ytest);
  231. } catch (InterpreterException e) {
  232. fail(e.getMessage());
  233. }
  234. }
  235. /**
  236. * Invokes the method 'gettertest' with one argument instead of zero.
  237. */
  238. public void testFaultyArity() {
  239. try {
  240. atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("gettertest"), NATTable.atValue(new ATObject[] { NATNil._INSTANCE_ }));
  241. fail("Expected an arity mismatch exception");
  242. } catch(XArityMismatch e) {
  243. // expected exception: success
  244. } catch(InterpreterException e) {
  245. fail(e.getMessage());
  246. }
  247. }
  248. /**
  249. * Invokes the method 'settertest' with a double (fraction) instead of an int (number)
  250. */
  251. public void testIllegalArgs() {
  252. try {
  253. atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("settertest"), NATTable.atValue(new ATObject[] { NATFraction.atValue(0.1) }));
  254. fail("Expected an illegal argument exception");
  255. } catch(XTypeMismatch e) {
  256. // Java expects an int, so AT expects a native number, but is given a native fraction
  257. if (e.getExpectedType() == NATNumber.class) {
  258. // expected exception: success
  259. } else {
  260. fail(e.getMessage());
  261. }
  262. } catch(InterpreterException e) {
  263. fail(e.getMessage());
  264. }
  265. }
  266. /**
  267. * Tries to assign to a final public field
  268. */
  269. public void testIllegalAssignment() {
  270. try {
  271. atTestClass.meta_assignField(atTestClass, AGSymbol.jAlloc("TEST_OBJECT_INIT"), NATNumber.atValue(0));
  272. fail("Expected an illegal assignment exception");
  273. } catch(XUnassignableField e) {
  274. // expected exception: success
  275. } catch(InterpreterException e) {
  276. fail(e.getMessage());
  277. }
  278. }
  279. /**
  280. * Test whether variable arguments work
  281. */
  282. public void testVarArgInvocation() {
  283. try {
  284. ATObject result = atTestObject.meta_invoke(atTestObject,
  285. AGSymbol.jAlloc("overloadedvararg"),
  286. NATTable.atValue(new ATObject[] { NATNumber.ZERO, NATNumber.ONE }));
  287. assertEquals(NATNil._INSTANCE_, result);
  288. } catch (InterpreterException e) {
  289. fail(e.getMessage());
  290. }
  291. }
  292. /**
  293. * Tests whether overloaded methods can be properly invoked if they can be resolved
  294. * to one method using the actual arguments.
  295. */
  296. public void testOverloadedInvWithOneMatch() {
  297. try {
  298. // invokes overloadedtest(int)
  299. ATObject result = atTestObject.meta_invoke(atTestObject,
  300. AGSymbol.jAlloc("overloadedtest"),
  301. NATTable.atValue(new ATObject[] { NATNumber.ZERO }));
  302. assertEquals("(int)", result.asNativeText().javaValue);
  303. // invokes overloadedtest(SymbiosisTest)
  304. result = atTestObject.meta_invoke(atTestObject,
  305. AGSymbol.jAlloc("overloadedtest"),
  306. NATTable.atValue(new ATObject[] { atTestObject }));
  307. assertEquals("(SymbiosisTest)", result.asNativeText().javaValue);
  308. // invokes overloadedtest()
  309. result = atTestObject.meta_invoke(atTestObject,
  310. AGSymbol.jAlloc("overloadedtest"),
  311. NATTable.EMPTY);
  312. assertEquals("()", result.asNativeText().javaValue);
  313. } catch (InterpreterException e) {
  314. fail(e.getMessage());
  315. }
  316. }
  317. /**
  318. * Invokes an overloaded method where the symbiosis cannot disambiguate automatically.
  319. */
  320. public void testOverloadedInvWithMultipleMatches() {
  321. try {
  322. // invokes overloadedmatch2(Object|SymbiosisTest) => error
  323. atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("overloadedmatch2"),
  324. NATTable.atValue(new ATObject[] { atTestObject }));
  325. fail("Expected a symbiosis exception");
  326. } catch (XSymbiosisFailure e) {
  327. // success: expected exception
  328. } catch (InterpreterException e) {
  329. fail(e.getMessage());
  330. }
  331. }
  332. /**
  333. * Invokes an overloaded method that does not match the specified argument type
  334. */
  335. public void testOverloadedInvWithNoMatch() {
  336. try {
  337. // invokes overloadedtest(NATObject) => error
  338. atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("overloadedtest"),
  339. NATTable.atValue(new ATObject[] { new NATObject() }));
  340. fail("Expected a symbiosis exception");
  341. } catch (XSymbiosisFailure e) {
  342. // success: expected exception
  343. } catch (InterpreterException e) {
  344. fail(e.getMessage());
  345. }
  346. }
  347. /**
  348. * Invokes a method that is not defined in the class.
  349. */
  350. public void testNonExistentMethod() {
  351. try {
  352. // invokes foo(1) => error
  353. atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("foo"),
  354. NATTable.atValue(new ATObject[] { NATNumber.ONE }));
  355. fail("Expected a selector not found exception");
  356. } catch (XSelectorNotFound e) {
  357. // success: expected exception
  358. } catch (InterpreterException e) {
  359. fail(e.getMessage());
  360. }
  361. }
  362. /**
  363. * Tests first-class field access for both instances and classes
  364. */
  365. public void testFirstClassFields() {
  366. try {
  367. // def result := (reflect: atTestObject).grabField("xtest")
  368. ATField result = atTestObject.meta_grabField(AGSymbol.jAlloc("xtest")).asField();
  369. assertEquals("xtest", result.base_getName().toString());
  370. assertEquals(TEST_OBJECT_INIT, result.base_readField().asNativeNumber().javaValue);
  371. // result := (reflect: atTestClass).grabField("ytest")
  372. result = atTestClass.meta_grabField(AGSymbol.jAlloc("ytest")).asField();
  373. assertEquals("ytest", result.base_getName().toString());
  374. assertEquals(ytest, result.base_readField().asNativeText().javaValue);
  375. } catch (InterpreterException e) {
  376. fail(e.getMessage());
  377. }
  378. }
  379. /**
  380. * Tests first-class method access for both instances and classes
  381. */
  382. public void testFirstClassMethods() {
  383. try {
  384. // def result := (reflect: atTestObject).grabMethod("gettertest")
  385. ATMethod result = atTestObject.meta_grabMethod(AGSymbol.jAlloc("gettertest")).asMethod();
  386. assertEquals("gettertest", result.base_getName().toString());
  387. // assert (42 == result())
  388. assertEquals(TEST_OBJECT_INIT, result.base_apply(NATTable.EMPTY,
  389. new NATContext(atTestObject, atTestObject)).asNativeNumber().javaValue);
  390. // clo := atTestObject.gettertest
  391. ATClosure clo = atTestObject.meta_select(atTestObject, AGSymbol.jAlloc("gettertest")).asClosure();
  392. // assert (42 == clo())
  393. assertEquals(TEST_OBJECT_INIT, clo.base_apply(NATTable.EMPTY).asNativeNumber().javaValue);
  394. // result := (reflect: atTestClass).grabMethod("prefix")
  395. result = atTestClass.meta_grabMethod(AGSymbol.jAlloc("prefix")).asMethod();
  396. assertEquals("prefix", result.base_getName().toString());
  397. // assert ("AmbientTalk" == result(""))
  398. assertEquals(ytest, result.base_apply(NATTable.atValue(new ATObject[] { NATText.atValue("") }),
  399. new NATContext(atTestClass, atTestClass)).asNativeText().javaValue);
  400. } catch (InterpreterException e) {
  401. fail(e.getMessage());
  402. }
  403. }
  404. /**
  405. * Tests casting to manually resolve overloaded method invocations
  406. * Selecting a method from a Java object results in a JavaClosure instance. Such a Java
  407. * closure understands the message 'cast', which allows the programmer to manually restrict
  408. * the wrapped JavaMethods to specific type signatures. In this case, the two choices
  409. * overloadedmatch2(Object)
  410. * overloadedmatch2(SymbiosisTest)
  411. * are manually restricted such that only the second one remains applicable
  412. */
  413. public void testCasting() {
  414. try {
  415. // invokes overloadedmatch2(SymbiosisTest) via explicit casting
  416. ATClosure method = atTestObject.meta_select(atTestObject, AGSymbol.jAlloc("overloadedmatch2")).asClosure();
  417. ATClosure castedMethod = method.meta_invoke(method, AGSymbol.jAlloc("cast"), NATTable.atValue(new ATObject[] { atTestClass })).asClosure();
  418. castedMethod.base_apply(NATTable.atValue(new ATObject[] { atTestObject }));
  419. } catch (InterpreterException e) {
  420. fail(e.getMessage());
  421. }
  422. }
  423. /**
  424. * Tests whether the parent pointers of the AT symbionts refer to the proper objects.
  425. */
  426. public void testSymbiontParents() {
  427. try {
  428. // the dynamic parent of atTestObject is atTestClass
  429. assertEquals(atTestClass, atTestObject.base_getSuper());
  430. // the dynamic parent of atTestClass is nil
  431. assertEquals(NATNil._INSTANCE_, atTestClass.base_getSuper());
  432. // the lexical parent of atTestObject is the lexical root
  433. assertEquals(Evaluator.getGlobalLexicalScope(), atTestObject.meta_getLexicalParent());
  434. // the lexical parent of atTestClass is the lexical root
  435. assertEquals(Evaluator.getGlobalLexicalScope(), atTestClass.meta_getLexicalParent());
  436. } catch (InterpreterException e) {
  437. fail(e.getMessage());
  438. }
  439. }
  440. /**
  441. * Tests whether new per-instance methods and fields can be added to a wrapped Java object.
  442. */
  443. public void testSymbiontInstanceAdditions() {
  444. try {
  445. // (reflect: atTestObject).defineField("x", 1)
  446. atTestObject.meta_defineField(AGSymbol.jAlloc("x"), NATNumber.ONE);
  447. // assert(atTestObject.x == 1)
  448. assertEquals(NATNumber.ONE, atTestObject.meta_select(atTestObject, AGSymbol.jAlloc("x")));
  449. // (reflect: atTestObject).addMethod(<method:"foo",[x],{x}>)
  450. ATMethod foo = evalAndReturn("def foo(x) { x }; foo").asClosure().base_getMethod();
  451. atTestObject.meta_addMethod(foo);
  452. // assert(atTestObject.foo(0) == 0)
  453. assertEquals(NATNumber.ZERO, atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("foo"),
  454. NATTable.atValue(new ATObject[] { NATNumber.ZERO })));
  455. } catch (InterpreterException e) {
  456. fail(e.getMessage());
  457. }
  458. }
  459. /**
  460. * Tests whether no duplicate methods or fields can be added to a wrapped Java object.
  461. */
  462. public void testSymbiontDuplicates() {
  463. try {
  464. try {
  465. // def atTestObject.xtest := 1
  466. atTestObject.meta_defineField(AGSymbol.jAlloc("xtest"), NATNumber.ONE);
  467. fail("expected a duplicate slot exception");
  468. } catch (XDuplicateSlot e) {
  469. // expected exception: success
  470. }
  471. try {
  472. // def atTestObject.gettertest() { nil }
  473. ATMethod getter = evalAndReturn("def gettertest() { nil }; gettertest").asClosure().base_getMethod();
  474. atTestObject.meta_addMethod(getter);
  475. fail("expected a duplicate slot exception");
  476. } catch (XDuplicateSlot e) {
  477. // expected exception: success
  478. }
  479. } catch (InterpreterException e) {
  480. fail(e.getMessage());
  481. }
  482. }
  483. /**
  484. * Tests whether new per-class methods and fields can be added to a wrapped Java class.
  485. * Also tests whether existing instances can make use of these newly added methods
  486. */
  487. public void testSymbiontClassAdditions() {
  488. try {
  489. // (reflect: atTestClass).defineField("z", 1)
  490. atTestClass.meta_defineField(AGSymbol.jAlloc("z"), NATNumber.ONE);
  491. // assert(atTestClass.z == 1)
  492. assertEquals(NATNumber.ONE, atTestClass.meta_select(atTestClass, AGSymbol.jAlloc("z")));
  493. // assert(aTestObject.z == 1) -> delegation to class
  494. assertEquals(NATNumber.ONE, atTestObject.meta_select(atTestObject, AGSymbol.jAlloc("z")));
  495. // (reflect: atTestClass).addMethod(<method:"get",[],{self.xtest}>)
  496. ATMethod get = evalAndReturn("def get() { self.xtest }; get").asClosure().base_getMethod();
  497. atTestClass.meta_addMethod(get);
  498. // assert(atTestObject.xtest == atTestObject.get())
  499. assertEquals(atTestObject.meta_select(atTestObject, AGSymbol.jAlloc("xtest")),
  500. atTestObject.meta_invoke(atTestObject, AGSymbol.jAlloc("get"), NATTable.EMPTY));
  501. } catch (InterpreterException e) {
  502. fail(e.getMessage());
  503. }
  504. }
  505. /**
  506. * Tests cloning behaviour for both wrapped class instances and classes.
  507. */
  508. public void testCloning() {
  509. try {
  510. // cloning a class results in the same class
  511. assertEquals(atTestClass, atTestClass.meta_clone());
  512. try {
  513. // cloning a java object results in an error
  514. atTestObject.meta_clone();
  515. fail("expected an illegal operation exception");
  516. } catch (XIllegalOperation e) {
  517. // expected exception: success
  518. }
  519. } catch (InterpreterException e) {
  520. fail(e.getMessage());
  521. }
  522. }
  523. /**
  524. * Tests the invocation of new on a wrapped Java Class.
  525. * Instantiates the Java class via the default init implementation.
  526. */
  527. public void testWorkingInstanceCreation() {
  528. try {
  529. // def instance := atTestClass.new(1)
  530. ATObject instance = atTestClass.meta_newInstance(NATTable.atValue(new ATObject[] { NATNumber.ONE }));
  531. assertEquals(JavaObject.class, instance.getClass());
  532. assertEquals(NATNumber.ONE, instance.meta_select(instance, AGSymbol.jAlloc("xtest")));
  533. Object realInstance = instance.asJavaObjectUnderSymbiosis().getWrappedObject();
  534. assertEquals(SymbiosisTest.class, realInstance.getClass());
  535. assertEquals(1, ((SymbiosisTest) realInstance).xtest);
  536. } catch (InterpreterException e) {
  537. fail(e.getMessage());
  538. }
  539. }
  540. /**
  541. * Tests whether classes with private constructors terminate cleanly.
  542. */
  543. public void testNonInstantiatableCreation() {
  544. try {
  545. // def instance := JavaObject.new(1)
  546. JavaClass.wrapperFor(JavaObject.class).meta_newInstance(NATTable.atValue(new ATObject[] { NATNumber.ONE }));
  547. fail("expected a not instantiatable exception");
  548. } catch (XNotInstantiatable e) {
  549. // expected exception: success
  550. } catch (InterpreterException e) {
  551. fail(e.getMessage());
  552. }
  553. }
  554. /**
  555. * Tests whether incorrect arguments passed to constructor terminate cleanly.
  556. */
  557. public void testIllegalArgsInstanceCreation() {
  558. try {
  559. // def instance := atTestClass.new(1.0)
  560. atTestClass.meta_newInstance(NATTable.atValue(new ATObject[] { NATFraction.atValue(1.0) }));
  561. fail("expected a symbiosis failure with 0 matches");
  562. } catch (XSymbiosisFailure e) {
  563. // expected exception: success
  564. } catch (InterpreterException e) {
  565. fail(e.getMessage());
  566. }
  567. }
  568. /**
  569. * Tests whether overloaded constructors which cannot be resolved terminates cleanly.
  570. */
  571. public void testOverloadedInstanceCreation() {
  572. try {
  573. // def instance := atTestClass.new(atTestObject) => 2 matches
  574. atTestClass.meta_newInstance(NATTable.atValue(new ATObject[] { atTestObject }));
  575. fail("expected a symbiosis failure with 2 matches");
  576. } catch (XSymbiosisFailure e) {
  577. // expected exception: success
  578. } catch (InterpreterException e) {
  579. fail(e.getMessage());
  580. }
  581. }
  582. /**
  583. * Tests an instance creation that raises an exception
  584. */
  585. public void testExceptionInInstanceCreation() {
  586. try {
  587. // def instance := atTestClass.new(atTestClass)
  588. atTestClass.meta_newInstance(NATTable.atValue(new ATObject[] { atTestClass }));
  589. fail("expected the constructor to throw an exception");
  590. } catch (XJavaException e) {
  591. // expected exception: success if it was an ExceptionTest instance
  592. assertEquals(ExceptionTest.class, e.getWrappedJavaException().getClass());
  593. } catch (InterpreterException e) {
  594. fail(e.getMessage());
  595. }
  596. }
  597. /**
  598. * Tests the invocation of new on a wrapped Java Object, rather than on a Java Class.
  599. */
  600. public void testCreationViaJavaObject() {
  601. try {
  602. // def instance := atTestObject.new(55)
  603. ATObject instance = atTestObject.meta_newInstance(
  604. NATTable.atValue(new ATObject[] { NATNumber.atValue(55) }));
  605. assertEquals(55, instance.meta_select(instance, AGSymbol.jAlloc("xtest")).asNativeNumber().javaValue);
  606. assertEquals(atTestClass, instance.base_getSuper());
  607. assertEquals(jTestObject.xtest, atTestObject.meta_select(atTestObject,
  608. AGSymbol.jAlloc("xtest")).asNativeNumber().javaValue);
  609. } catch (InterpreterException e) {
  610. fail(e.getMessage());
  611. }
  612. }
  613. /**
  614. * Tests the invocation of new on a wrapped Java Class.
  615. * Instantiates the Java class via a custom new implementation.
  616. *
  617. * BEWARE: this test should be the last for testing symbiotic instance creation as it
  618. * MODIFIES the test fixture (the JavaClass wrapper object)! Ths is because the JavaClass wrapper
  619. * is pooled and reused throughout subsequent tests.
  620. */
  621. public void testCustomInstanceCreation() {
  622. try {
  623. // def orignew := atTestClass.new; def atTestClass.new(x,y) { def o := orignew(x); def o.ytest := y; o }
  624. ATClosure newClo = evalAndReturn("def new(x,y) { def o := orignew(x); def o.ytest := y; o }; new").asClosure();
  625. atTestClass.meta_defineField(AGSymbol.jAlloc("orignew"), atTestClass.meta_select(atTestClass, AGSymbol.jAlloc("new")));
  626. atTestClass.meta_addMethod(newClo.base_getMethod());
  627. // def instance := atTestClass.new(10, 11)
  628. ATObject instance = atTestClass.meta_invoke(atTestClass, AGSymbol.jAlloc("new"),
  629. NATTable.atValue(new ATObject[] { NATNumber.atValue(10), NATNumber.atValue(11) }));
  630. assertEquals(10, instance.meta_select(instance, AGSymbol.jAlloc("xtest")).asNativeNumber().javaValue);
  631. assertEquals(11, instance.meta_select(instance, AGSymbol.jAlloc("ytest")).asNativeNumber().javaValue);
  632. } catch (InterpreterException e) {
  633. fail(e.getMessage());
  634. }
  635. }
  636. /**
  637. * Tests whether jlobby.java results in a new JavaPackage.
  638. * Tests whether jlobby.java.lang results in a new JavaPackage.
  639. * Tests whether jlobby.java.lang.Object results in the proper loading of that class
  640. */
  641. public void testJLobbyPackageLoading() throws InterpreterException {
  642. ATObject jpkg = jLobby_.meta_select(jLobby_, AGSymbol.jAlloc("java"));
  643. assertEquals(JavaPackage.class, jpkg.getClass());
  644. assertTrue(jLobby_.meta_respondsTo(AGSymbol.jAlloc("java")).asNativeBoolean().javaValue);
  645. ATObject jlpkg = jpkg.meta_select(jpkg, AGSymbol.jAlloc("lang"));
  646. assertEquals(JavaPackage.class, jlpkg.getClass());
  647. assertTrue(jpkg.meta_respondsTo(AGSymbol.jAlloc("lang")).asNativeBoolean().javaValue);
  648. ATObject jObject = jlpkg.meta_select(jlpkg, AGSymbol.jAlloc("Object"));
  649. assertEquals(JavaClass.class, jObject.getClass());
  650. assertTrue(jlpkg.meta_respondsTo(AGSymbol.jAlloc("Object")).asNativeBoolean().javaValue);
  651. }
  652. /**
  653. * Tests whether lowercase classes can be loaded via the class method of a JavaPackage.
  654. */
  655. public void testJLobbyExplicitClassLoading() throws InterpreterException {
  656. ATObject eduVubAtObjectsSymbiosisPkg = new JavaPackage("edu.vub.at.objects.symbiosis.");
  657. // load the class manually: invoke pkg.class("lowercaseClassTest")
  658. ATObject cls = eduVubAtObjectsSymbiosisPkg.meta_invoke(
  659. eduVubAtObjectsSymbiosisPkg,
  660. AGSymbol.jAlloc("class"),
  661. NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("lowercaseClassTest") }));
  662. assertEquals(JavaClass.class, cls.getClass());
  663. assertTrue(eduVubAtObjectsSymbiosisPkg.meta_respondsTo(
  664. AGSymbol.jAlloc("lowercaseClassTest")).asNativeBoolean().javaValue);
  665. }
  666. /**
  667. * Tests whether access to a nonexistent class gives rise to a selector not found exception.
  668. */
  669. public void testJLobbyNonexistentClassLoading() throws InterpreterException {
  670. try {
  671. jLobby_.meta_select(jLobby_, AGSymbol.jAlloc("Foo"));
  672. fail("expected a class not found exception");
  673. } catch (XClassNotFound e) {
  674. // success: expected exception
  675. }
  676. }
  677. /**
  678. * Tests whether the uppercase package 'foo.Bar' can be loaded via the package method of a JavaPackage.
  679. */
  680. public void testJLobbyExplicitPackageLoading() throws InterpreterException {
  681. // def fooPkg := jLobby.foo;
  682. ATObject fooPkg = jLobby_.meta_select(jLobby_, AGSymbol.jAlloc("foo"));
  683. // def BarPkg := foo.package(`Bar);
  684. ATObject BarPkg = fooPkg.meta_invoke(fooPkg,
  685. AGSymbol.jAlloc("package"),
  686. NATTable.atValue(new ATObject[] { AGSymbol.jAlloc("Bar") }));
  687. assertEquals(JavaPackage.class, BarPkg.getClass());
  688. assertTrue(fooPkg.meta_respondsTo(AGSymbol.jAlloc("Bar")).asNativeBoolean().javaValue);
  689. }
  690. /**
  691. * BUGFIX TEST: jlobby.java.lang.StringBuffer.new(10) failed to discriminate between constructors
  692. * StringBuffer(String) and StringBuffer(int), reason was that anything native was convertible to
  693. * NATText and also to String. Fixed by reimplementing asNativeText in NATNil to throw a type
  694. * exception as usual.
  695. */
  696. public void testBugfixOverloadedConstructor() throws InterpreterException {
  697. // def jStringBuffer := jLobby.java.lang.StringBuffer;
  698. ATObject jStringBuffer = JavaClass.wrapperFor(StringBuffer.class);
  699. // jStringBuffer.new(10)
  700. jStringBuffer.meta_invoke(jStringBuffer, AGSymbol.jAlloc("new"), NATTable.atValue(new ATObject[] { NATNumber.atValue(10) }));
  701. }
  702. /**
  703. * Tests whether Java interface types are correctly treated as AT/2 types.
  704. * Test cases: interface java.util.Set extends java.util.Collection
  705. */
  706. public void testInterfacesAndTypes() throws InterpreterException {
  707. JavaClass jSet = JavaClass.wrapperFor(Set.class);
  708. JavaClass jCollection = JavaClass.wrapperFor(Collection.class);
  709. ATTypeTag atSet = jSet.asTypeTag();
  710. ATTypeTag atCollection = jCollection.asTypeTag();
  711. // type name = 'java.util.Set'
  712. assertEquals(AGSymbol.jAlloc("java.util.Set"), atSet.base_getTypeName());
  713. // type parents = [ java.util.Collection ]
  714. assertEquals(jCollection, atSet.base_getSuperTypes().base_at(NATNumber.ONE));
  715. // Set isSubtypeOf Collection? true
  716. assertTrue(atSet.base_isSubtypeOf(atCollection).asNativeBoolean().javaValue);
  717. // Collection isSubtypeOf Set? false
  718. assertFalse(atCollection.base_isSubtypeOf(atSet).asNativeBoolean().javaValue);
  719. // Set isSubtypeOf Set? true
  720. assertTrue(atSet.base_isSubtypeOf(atSet).asNativeBoolean().javaValue);
  721. }
  722. /**
  723. * Test whether JavaObject wrappers are correctly typed with all
  724. * of the interfaces of the wrapped instance's class.
  725. *
  726. * Test case: java.util.Vector implements List, RandomAccess, Cloneable, Serializable
  727. */
  728. public void testTypedJavaObject() throws InterpreterException {
  729. JavaClass jVector = JavaClass.wrapperFor(Vector.class);
  730. JavaObject vec = jVector.meta_newInstance(NATTable.EMPTY).asJavaObjectUnderSymbiosis();
  731. ATTypeTag jListType = JavaClass.wrapperFor(List.class).asTypeTag();
  732. ATTypeTag jCollectionType = JavaClass.wrapperFor(Collection.class).asTypeTag();
  733. ATTypeTag jSerializableType = JavaClass.wrapperFor(Serializable.class).asTypeTag();
  734. ATTypeTag jSetType = JavaClass.wrapperFor(Set.class).asTypeTag();
  735. // vec is tagged with List? true
  736. assertTrue(vec.meta_isTaggedAs(jListType).asNativeBoolean().javaValue);
  737. // vec is tagged with Collection? true
  738. assertTrue(vec.meta_isTaggedAs(jCollectionType).asNativeBoolean().javaValue);
  739. // vec is tagged with Serializable? true
  740. assertTrue(vec.meta_isTaggedAs(jSerializableType).asNativeBoolean().javaValue);
  741. // vec is tagged with Set? false
  742. assertFalse(vec.meta_isTaggedAs(jSetType).asNativeBoolean().javaValue);
  743. }
  744. }
  745. class lowercaseClassTest { }