github.com/cyrilou242/gomobile-java@v0.0.0-20220215185836-09daef25a210/bind/java/SeqTest.java (about)

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package go;
     6  
     7  import go.MoreAsserts;
     8  import java.util.Arrays;
     9  import java.util.Random;
    10  
    11  import testpkg.*;
    12  import secondpkg.Secondpkg;
    13  
    14  import static go.MoreAsserts.*;
    15  
    16  public class SeqTest {
    17    public SeqTest() {
    18    }
    19  
    20    public void testConst() {
    21      assertEquals("const String", "a string", Testpkg.AString);
    22      assertEquals("const Int", 7, Testpkg.AnInt);
    23      assertEquals("const Bool", true, Testpkg.ABool);
    24      assertEquals("const Float", 0.12345, Testpkg.AFloat, 0.0001);
    25  
    26      assertEquals("const MinInt32", -1<<31, Testpkg.MinInt32);
    27      assertEquals("const MaxInt32", (1<<31) - 1, Testpkg.MaxInt32);
    28      assertEquals("const MinInt64", -1L<<63, Testpkg.MinInt64);
    29      assertEquals("const MaxInt64", (1L<<63) - 1, Testpkg.MaxInt64);
    30      assertEquals("const SmallestNonzeroFloat64", 4.940656458412465441765687928682213723651e-324, Testpkg.SmallestNonzeroFloat64, 1e-323);
    31      assertEquals("const MaxFloat64", 1.797693134862315708145274237317043567981e+308, Testpkg.MaxFloat64, 0.0001);
    32      assertEquals("const SmallestNonzeroFloat32", 1.401298464324817070923729583289916131280e-45, Testpkg.SmallestNonzeroFloat32, 1e-44);
    33      assertEquals("const MaxFloat32", 3.40282346638528859811704183484516925440e+38, Testpkg.MaxFloat32, 0.0001);
    34      assertEquals("const Log2E", 1/0.693147180559945309417232121458176568075500134360255254120680009, Testpkg.Log2E, 0.0001);
    35    }
    36  
    37    public void testRefMap() {
    38      // Ensure that the RefMap.live count is kept in sync
    39      // even a particular reference number is removed and
    40      // added again
    41      Seq.RefMap m = new Seq.RefMap();
    42      Seq.Ref r = new Seq.Ref(1, null);
    43      m.put(r.refnum, r);
    44      m.remove(r.refnum);
    45      m.put(r.refnum, r);
    46      // Force the RefMap to grow, to activate the sanity
    47      // checking of the live count in RefMap.grow.
    48      for (int i = 2; i < 24; i++) {
    49        m.put(i, new Seq.Ref(i, null));
    50      }
    51    }
    52  
    53    public void testVar() {
    54      assertEquals("var StringVar", "a string var", Testpkg.getStringVar());
    55  
    56      String newStringVar = "a new string var";
    57      Testpkg.setStringVar(newStringVar);
    58      assertEquals("var StringVar", newStringVar, Testpkg.getStringVar());
    59  
    60      assertEquals("var IntVar", 77, Testpkg.getIntVar());
    61  
    62      long newIntVar = 777;
    63      Testpkg.setIntVar(newIntVar);
    64      assertEquals("var IntVar", newIntVar, Testpkg.getIntVar());
    65  
    66      S s0 = Testpkg.getStructVar();
    67      assertEquals("var StructVar", "a struct var", s0.string());
    68      S s1 = Testpkg.new_();
    69      Testpkg.setStructVar(s1);
    70      assertEquals("var StructVar", s1.string(), Testpkg.getStructVar().string());
    71  
    72      AnI obj = new AnI();
    73      obj.name = "this is an I";
    74      Testpkg.setInterfaceVar(obj);
    75      assertEquals("var InterfaceVar", obj.string(), Testpkg.getInterfaceVar().string());
    76    }
    77  
    78  
    79  //  public void testAssets() {
    80  //    // Make sure that a valid context is set before reading assets
    81  //    Seq.setContext(getInstrumentation().getContext());
    82  //    String want = "Hello, Assets.\n";
    83  //    String got = Testpkg.ReadAsset();
    84  //    assertEquals("Asset read", want, got);
    85  //  }
    86  
    87    public void testAdd() {
    88      long res = Testpkg.add(3, 4);
    89      assertEquals("Unexpected arithmetic failure", 7, res);
    90    }
    91  
    92    public void testBool() {
    93      assertTrue(Testpkg.negate(false));
    94      assertFalse(Testpkg.negate(true));
    95    }
    96  
    97    public void testShortString() {
    98      String want = "a short string";
    99      String got = Testpkg.strDup(want);
   100      assertEquals("Strings should match", want, got);
   101  
   102      want = "";
   103      got = Testpkg.strDup(want);
   104      assertEquals("Strings should match (empty string)", want, got);
   105  
   106      got = Testpkg.strDup(null);
   107      assertEquals("Strings should match (null string)", want, got);
   108    }
   109  
   110    public void testLongString() {
   111      StringBuilder b = new StringBuilder();
   112      for (int i = 0; i < 128*1024; i++) {
   113        b.append("0123456789");
   114      }
   115      String want = b.toString();
   116      String got = Testpkg.strDup(want);
   117      assertEquals("Strings should match", want, got);
   118    }
   119  
   120    public void testUnicode() {
   121      String[] tests = new String[]{
   122        "abcxyz09{}",
   123        "Hello, 世界",
   124        "\uffff\uD800\uDC00\uD800\uDC01\uD808\uDF45\uDBFF\uDFFF",
   125        // From Go std lib tests in unicode/utf16/utf16_test.go
   126        "\u0001\u0002\u0003\u0004",
   127        "\uffff\ud800\udc00\ud800\udc01\ud808\udf45\udbff\udfff",
   128        "\ud800a",
   129        "\udfff"
   130      };
   131      String[] wants = new String[]{
   132        "abcxyz09{}",
   133        "Hello, 世界",
   134        "\uffff\uD800\uDC00\uD800\uDC01\uD808\uDF45\uDBFF\uDFFF",
   135        "\u0001\u0002\u0003\u0004",
   136        "\uffff\ud800\udc00\ud800\udc01\ud808\udf45\udbff\udfff",
   137        "\ufffda",
   138        "\ufffd"
   139      };
   140      for (int i = 0; i < tests.length; i++) {
   141        String got = Testpkg.strDup(tests[i]);
   142        String want = wants[i];
   143        assertEquals("Strings should match", want, got);
   144      }
   145    }
   146  
   147    public void testNilErr() throws Exception {
   148      Testpkg.err(null); // returns nil, no exception
   149    }
   150  
   151    public void testErr() {
   152      String msg = "Go errors are dropped into the confusing space of exceptions";
   153      try {
   154        Testpkg.err(msg);
   155        fail("expected non-nil error to be turned into an exception");
   156      } catch (Exception e) {
   157        assertEquals("messages should match", msg, e.getMessage());
   158      }
   159    }
   160  
   161    public void testByteArray() {
   162      for (int i = 0; i < 2048; i++) {
   163        if (i == 0) {
   164          byte[] got = Testpkg.bytesAppend(null, null);
   165          assertEquals("Bytes(null+null) should match", (byte[])null, got);
   166          got = Testpkg.bytesAppend(new byte[0], new byte[0]);
   167          assertEquals("Bytes(empty+empty) should match", (byte[])null, got);
   168          continue;
   169        }
   170  
   171        byte[] want = new byte[i];
   172        new Random().nextBytes(want);
   173  
   174        byte[] s1 = null;
   175        byte[] s2 = null;
   176        if (i > 0) {
   177          s1 = Arrays.copyOfRange(want, 0, 1);
   178        }
   179        if (i > 1) {
   180          s2 = Arrays.copyOfRange(want, 1, i);
   181        }
   182        byte[] got = Testpkg.bytesAppend(s1, s2);
   183        MoreAsserts.assertEquals("Bytes(len="+i+") should match", want, got);
   184      }
   185    }
   186  
   187    // Test for golang.org/issue/9486.
   188    public void testByteArrayAfterString() {
   189      byte[] bytes = new byte[1024];
   190      for (int i=0; i < bytes.length; i++) {
   191             bytes[i] = 8;
   192      }
   193  
   194      String stuff = "stuff";
   195      byte[] got = Testpkg.appendToString(stuff, bytes);
   196  
   197      try {
   198        byte[] s = stuff.getBytes("UTF-8");
   199        byte[] want = new byte[s.length + bytes.length];
   200        System.arraycopy(s, 0, want, 0, s.length);
   201        System.arraycopy(bytes, 0, want, s.length, bytes.length);
   202        MoreAsserts.assertEquals("Bytes should match", want, got);
   203      } catch (Exception e) {
   204        fail("Cannot perform the test: " + e.toString());
   205      }
   206    }
   207  
   208    public void testGoRefGC() {
   209      S s = Testpkg.new_();
   210      runGC();
   211      long collected = Testpkg.numSCollected();
   212      assertEquals("Only S should be pinned", 0, collected);
   213  
   214      s = null;
   215      runGC();
   216      collected = Testpkg.numSCollected();
   217      assertEquals("S should be collected", 1, collected);
   218    }
   219  
   220    private class AnI implements I {
   221      public void e() throws Exception {
   222        throw new Exception("my exception from E");
   223      }
   224  
   225      boolean calledF;
   226      public void f() {
   227        calledF = true;
   228      }
   229  
   230      public I i() {
   231        return this;
   232      }
   233  
   234      public S s() {
   235        return Testpkg.new_();
   236      }
   237  
   238      public String stoString(S s) {
   239        return s.string();
   240      }
   241  
   242      public long v() {
   243        return 1234;
   244      }
   245  
   246      public long ve() throws Exception {
   247        throw new Exception("my exception from VE");
   248      }
   249  
   250      public String name;
   251  
   252      public String string() {
   253        return name;
   254      }
   255  
   256    }
   257  
   258    // TODO(hyangah): add tests for methods that take parameters.
   259  
   260    public void testInterfaceMethodReturnsError() {
   261      final AnI obj = new AnI();
   262      try {
   263        Testpkg.callE(obj);
   264        fail("Expecting exception but none was thrown.");
   265      } catch (Exception e) {
   266        assertEquals("Error messages should match", "my exception from E", e.getMessage());
   267      }
   268    }
   269  
   270    public void testInterfaceMethodVoid() {
   271      final AnI obj = new AnI();
   272      Testpkg.callF(obj);
   273      assertTrue("Want AnI.F to be called", obj.calledF);
   274    }
   275  
   276    public void testInterfaceMethodReturnsInterface() {
   277      AnI obj = new AnI();
   278      obj.name = "testing AnI.I";
   279      I i = Testpkg.callI(obj);
   280      assertEquals("Want AnI.I to return itself", i.string(), obj.string());
   281  
   282      runGC();
   283  
   284      i = Testpkg.callI(obj);
   285      assertEquals("Want AnI.I to return itself", i.string(), obj.string());
   286    }
   287  
   288    public void testInterfaceMethodReturnsStructPointer() {
   289      final AnI obj = new AnI();
   290      for (int i = 0; i < 5; i++) {
   291        S s = Testpkg.callS(obj);
   292        runGC();
   293      }
   294    }
   295  
   296    public void testInterfaceMethodTakesStructPointer() {
   297      final AnI obj = new AnI();
   298      S s = Testpkg.callS(obj);
   299      String got = obj.stoString(s);
   300      String want = s.string();
   301      assertEquals("Want AnI.StoString(s) to call s's String", want, got);
   302    }
   303  
   304    public void testInterfaceMethodReturnsInt() {
   305      final AnI obj = new AnI();
   306      assertEquals("Values must match", 1234, Testpkg.callV(obj));
   307    }
   308  
   309    public void testInterfaceMethodReturnsIntOrError() {
   310      final AnI obj = new AnI();
   311      try {
   312        long v = Testpkg.callVE(obj);
   313        fail("Expecting exception but none was thrown and got value " + v);
   314      } catch (Exception e) {
   315        assertEquals("Error messages should match", "my exception from VE", e.getMessage());
   316      }
   317    }
   318  
   319    boolean finalizedAnI;
   320  
   321    private class AnI_Traced extends AnI {
   322      @Override
   323      public void finalize() throws Throwable {
   324        finalizedAnI = true;
   325        super.finalize();
   326      }
   327    }
   328  
   329    public void testJavaRefKeep() {
   330      finalizedAnI = false;
   331      AnI obj = new AnI_Traced();
   332      Testpkg.callF(obj);
   333      assertTrue("want F to be called", obj.calledF);
   334      Testpkg.callF(obj);
   335      obj = null;
   336      int attempts = 0;
   337      while (true) {
   338          runGC();
   339          if (finalizedAnI)
   340              break;
   341          attempts++;
   342          try {
   343              Thread.sleep(100);
   344          } catch (InterruptedException e) {
   345              throw new RuntimeException(e);
   346          }
   347          if (attempts >= 10)
   348              fail("want obj not to be kept by Go; tried " + attempts + " garbage collections.");
   349      }
   350  
   351      finalizedAnI = false;
   352      obj = new AnI_Traced();
   353      Testpkg.keep(obj);
   354      obj = null;
   355      runGC();
   356      assertFalse("want obj to be kept live by Go", finalizedAnI);
   357    }
   358  
   359    private int countI = 0;
   360  
   361    private class CountI implements I {
   362      public void f() { countI++; }
   363  
   364      public void e() throws Exception {}
   365      public I i() { return null; }
   366      public S s() { return null; }
   367      public String stoString(S s) { return ""; }
   368      public long v() { return 0; }
   369      public long ve() throws Exception { return 0; }
   370      public String string() { return ""; }
   371    }
   372  
   373    public void testGoRefMapGrow() {
   374      CountI obj = new CountI();
   375      Testpkg.keep(obj);
   376  
   377      // Push active references beyond base map size.
   378      for (int i = 0; i < 24; i++) {
   379        CountI o = new CountI();
   380        Testpkg.callF(o);
   381        if (i%3==0) {
   382          Testpkg.keep(o);
   383        }
   384      }
   385      runGC();
   386      for (int i = 0; i < 128; i++) {
   387        Testpkg.callF(new CountI());
   388      }
   389  
   390      Testpkg.callF(obj); // original object needs to work.
   391  
   392      assertEquals(countI, 1+24+128);
   393    }
   394  
   395    private void runGC() {
   396      System.gc();
   397      System.runFinalization();
   398      Testpkg.gc();
   399      System.gc();
   400      System.runFinalization();
   401    }
   402  
   403    public void testUnnamedParams() {
   404      final String msg = "1234567";
   405      assertEquals("want the length of \"1234567\" passed after unnamed params",
   406  		    7, Testpkg.unnamedParams(10, 20, msg));
   407    }
   408  
   409    public void testPointerToStructAsField() {
   410      Node a = Testpkg.newNode("A");
   411      Node b = Testpkg.newNode("B");
   412      a.setNext(b);
   413      String got = a.string();
   414      assertEquals("want Node A points to Node B", "A:B:<end>", got);
   415    }
   416  
   417    public void testImplementsInterface() {
   418      Interface intf = Testpkg.newConcrete();
   419    }
   420  
   421    public void testErrorField() {
   422      Node n = Testpkg.newNode("ErrTest");
   423      Exception want = new Exception("an error message");
   424      n.setErr(want);
   425      Exception got = n.getErr();
   426      assertTrue("want back the error we set", want == got);
   427      String msg = Testpkg.errorMessage(want);
   428      assertEquals("the error message must match", want.getMessage(), msg);
   429    }
   430  
   431    public void testErrorDup() {
   432      Exception err = Testpkg.getGlobalErr();
   433      assertTrue("the Go error instance must preserve its identity", Testpkg.isGlobalErr(err));
   434      assertEquals("the Go error message must be preserved", "global err", err.getMessage());
   435    }
   436  
   437    //test if we have JNI local reference table overflow error
   438    public void testLocalReferenceOverflow() {
   439      Testpkg.callWithCallback(new GoCallback() {
   440  
   441        @Override
   442        public void varUpdate() {
   443          //do nothing
   444        }
   445      });
   446    }
   447  
   448    public void testNullReferences() {
   449      assertTrue(Testpkg.callWithNull(null, new NullTest() {
   450        public NullTest null_() {
   451          return null;
   452        }
   453      }));
   454      assertEquals("Go nil interface is null", null, Testpkg.newNullInterface());
   455      assertEquals("Go nil struct pointer is null", null, Testpkg.newNullStruct());
   456  
   457      Issue20330 nullArger = new Issue20330();
   458      assertTrue(nullArger.callWithNull(null));
   459    }
   460  
   461    public void testPassByteArray() {
   462      Testpkg.passByteArray(new B() {
   463        @Override public void b(byte[] b) {
   464          byte[] want = new byte[]{1, 2, 3, 4};
   465          MoreAsserts.assertEquals("bytes should match", want, b);
   466        }
   467      });
   468    }
   469  
   470    public void testReader() {
   471      byte[] b = new byte[8];
   472      try {
   473        long n = Testpkg.readIntoByteArray(b);
   474        assertEquals("wrote to the entire byte array", b.length, n);
   475        byte[] want = new byte[b.length];
   476        for (int i = 0; i < want.length; i++)
   477          want[i] = (byte)i;
   478        MoreAsserts.assertEquals("bytes should match", want, b);
   479       } catch (Exception e) {
   480         fail("Failed to write: " + e.toString());
   481       }
   482    }
   483  
   484    public void testGoroutineCallback() {
   485      Testpkg.goroutineCallback(new Receiver() {
   486        @Override public void hello(String msg) {
   487        }
   488      });
   489    }
   490  
   491    public void testImportedPkg() {
   492      Testpkg.callImportedI(new secondpkg.I() {
   493        @Override public long f(long i) {
   494          return i;
   495        }
   496      });
   497      assertEquals("imported string should match", Secondpkg.HelloString, Secondpkg.hello());
   498      secondpkg.I i = Testpkg.newImportedI();
   499      secondpkg.S s = Testpkg.newImportedS();
   500      i = Testpkg.getImportedVarI();
   501      s = Testpkg.getImportedVarS();
   502      assertEquals("numbers should match", 8, i.f(8));
   503      assertEquals("numbers should match", 8, s.f(8));
   504      Testpkg.setImportedVarI(i);
   505      Testpkg.setImportedVarS(s);
   506      ImportedFields fields = Testpkg.newImportedFields();
   507      i = fields.getI();
   508      s = fields.getS();
   509      fields.setI(i);
   510      fields.setS(s);
   511      Testpkg.withImportedI(i);
   512      Testpkg.withImportedS(s);
   513  
   514      secondpkg.IF f = new AnI();
   515      f = Testpkg.new_();
   516      secondpkg.Ser ser = Testpkg.newSer();
   517    }
   518  
   519    public void testRoundtripEquality() {
   520      I want = new AnI();
   521      assertTrue("java object passed through Go should not be wrapped", want == Testpkg.iDup(want));
   522      InterfaceDupper idup = new InterfaceDupper(){
   523        @Override public Interface iDup(Interface i) {
   524          return i;
   525        }
   526      };
   527      assertTrue("Go interface passed through Java should not be wrapped", Testpkg.callIDupper(idup));
   528      ConcreteDupper cdup = new ConcreteDupper(){
   529        @Override public Concrete cDup(Concrete c) {
   530          return c;
   531        }
   532      };
   533      assertTrue("Go struct passed through Java should not be wrapped", Testpkg.callCDupper(cdup));
   534    }
   535  
   536    public void testConstructor() {
   537      Interface i = new Concrete();
   538      i.f();
   539  
   540      S2 s = new S2(1, 2);
   541      assertEquals("new S2().sum", 3.0, s.sum());
   542      assertEquals("new S2().tryTwoStrings", "gostring", s.tryTwoStrings("go", "string"));
   543  
   544  	  new S3();
   545  
   546  	  S4 s4 = new S4(123);
   547  	  assertEquals("Constructor argument", 123, s4.getI());
   548  
   549      s4 = new S4(123.456);
   550      assertEquals("Overloaded constructor argument", 123, s4.getI());
   551  
   552      s4 = new S4(false);
   553      assertEquals("Exceptional constructor", 0, s4.getI());
   554  
   555      try {
   556        s4 = new S4(true);
   557        fail("Constructor error wasn't caught");
   558      } catch (Exception e) {
   559      }
   560    }
   561  
   562    public void testEmptyError() {
   563      try {
   564        Testpkg.emptyError();
   565        fail("Empty error wasn't caught");
   566      } catch (Exception e) {
   567      }
   568      EmptyErrorer empty = new EmptyErrorer() {
   569        @Override public void emptyError() throws Exception {
   570          throw new Exception("");
   571        }
   572      };
   573      try {
   574        Testpkg.callEmptyError(empty);
   575        fail("Empty exception wasn't caught");
   576      } catch (Exception e) {
   577      }
   578    }
   579  
   580    public void testInitCaller() {
   581      Testpkg.init();
   582  
   583      InitCaller initer = Testpkg.newInitCaller();
   584      initer.init();
   585    }
   586  
   587    public void testSIGPIPE() {
   588      Testpkg.testSIGPIPE();
   589    }
   590  
   591    public void testTags() {
   592      assertEquals("Constant from a tagged file", 42, Testpkg.TaggedConst);
   593    }
   594  
   595    public void testClassNameWithPackageName() {
   596      testpkg.Testpkg_ o = new secondpkg.Secondpkg_();
   597      secondpkg.Secondpkg_ o2 = Secondpkg.newSecondpkg();
   598      o2.m();
   599      o2.setV("hi");
   600      assertEquals(o2.getV(), "hi");
   601      Testpkg.clashingParameterFromOtherPackage(o2);
   602    }
   603  }