@Test
  public void test_2GB_over() throws IOException {
    Assume.assumeTrue(CC.FULL_TEST);

    byte[] data = new byte[51111];
    int dataHash = Arrays.hashCode(data);

    Set<Long> recids = new TreeSet<Long>();

    for (int i = 0; i < 1e5; i++) {
      long recid = engine.recordPut(data, Serializer.BYTE_ARRAY_SERIALIZER);
      recids.add(recid);

      //            if(i%10000==0){
      //            System.out.println(recid);
      //            for(Long l:recids){
      //                byte[] b = engine.recordGet(l, Serializer.BYTE_ARRAY_SERIALIZER);
      //                int hash = Arrays.hashCode(b);
      //                assertEquals(l,dataHash, hash);
      //            }
      //            }

    }

    engine.commit();

    for (Long l : recids) {
      byte[] b = engine.recordGet(l, Serializer.BYTE_ARRAY_SERIALIZER);
      int hash = Arrays.hashCode(b);
      assertEquals(dataHash, hash);
    }
  }
Beispiel #2
0
  @org.junit.Test
  public void testGenerateValuesWood() throws Exception {
    for (char i : "ABCD".toCharArray()) {
      mappingCollector.setValueBefore("wood" + i, 32);
      mappingCollector.addConversion(4, "planks" + i, Arrays.asList("wood" + i));
    }

    for (char i : "ABCD".toCharArray()) {
      mappingCollector.addConversion(4, "planks" + i, Arrays.asList("wood"));
    }

    for (char i : "ABCD".toCharArray())
      for (char j : "ABCD".toCharArray())
        mappingCollector.addConversion(4, "stick", Arrays.asList("planks" + i, "planks" + j));
    mappingCollector.addConversion(
        1, "crafting_table", Arrays.asList("planksA", "planksA", "planksA", "planksA"));
    for (char i : "ABCD".toCharArray())
      for (char j : "ABCD".toCharArray())
        mappingCollector.addConversion(
            1, "wooden_hoe", Arrays.asList("stick", "stick", "planks" + i, "planks" + j));

    Map<String, Integer> values = valueGenerator.generateValues();
    for (char i : "ABCD".toCharArray()) assertEquals(32, getValue(values, "wood" + i));
    for (char i : "ABCD".toCharArray()) assertEquals(8, getValue(values, "planks" + i));
    assertEquals(4, getValue(values, "stick"));
    assertEquals(32, getValue(values, "crafting_table"));
    assertEquals(24, getValue(values, "wooden_hoe"));
  }
  @Test
  public void testResultFunctionThrows() {
    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    final List<Integer> list = Arrays.asList(1, 2, 3);

    Func1<Integer, List<Integer>> func =
        new Func1<Integer, List<Integer>>() {
          @Override
          public List<Integer> call(Integer t1) {
            return list;
          }
        };
    Func2<Integer, Integer, Integer> resFunc =
        new Func2<Integer, Integer, Integer>() {

          @Override
          public Integer call(Integer t1, Integer t2) {
            throw new TestException();
          }
        };

    List<Integer> source = Arrays.asList(16, 32, 64);

    Observable.from(source).flatMapIterable(func, resFunc).subscribe(o);

    verify(o, never()).onCompleted();
    verify(o, never()).onNext(any());
    verify(o).onError(any(TestException.class));
  }
  @Test
  public void getInstances() throws Exception {
    // Test a non-empty and an empty list.
    List<List<ModuleURN>> lists =
        Arrays.asList(
            Arrays.asList(new ModuleURN("test:prov:me:A"), new ModuleURN("test:prov:me:B")),
            new ArrayList<ModuleURN>());

    final ModuleURN input = new ModuleURN("test:prov:me");
    for (List<ModuleURN> list : lists) {
      final List<ModuleURN> urnList = list;
      testAPI(
          new WSTester<List<ModuleURN>>() {
            @Override
            protected List<ModuleURN> invokeApi(boolean isNullParams) throws Exception {
              return getClient().getInstances(isNullParams ? null : input);
            }

            @Override
            protected List<ModuleURN> setReturnValue(boolean isNullParams) {
              List<ModuleURN> moduleURNs = isNullParams ? null : urnList;
              getMockSAService().setURNList(moduleURNs);
              // nulls are returned as empty lists.
              return moduleURNs == null ? new ArrayList<ModuleURN>() : moduleURNs;
            }

            @Override
            protected void verifyInputParams(boolean isNullParams) {
              assertEquals(isNullParams ? null : input, getMockSAService().getURN());
            }
          });
      resetServiceParameters();
    }
  }
  @Test
  public void testFlatMapTransformsException() {
    Observable<Integer> onNext = Observable.from(Arrays.asList(1, 2, 3));
    Observable<Integer> onCompleted = Observable.from(Arrays.asList(4));
    Observable<Integer> onError = Observable.from(Arrays.asList(5));

    Observable<Integer> source =
        Observable.concat(
            Observable.from(Arrays.asList(10, 20, 30)),
            Observable.<Integer>error(new RuntimeException("Forced failure!")));

    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    source.flatMap(just(onNext), just(onError), just0(onCompleted)).subscribe(o);

    verify(o, times(3)).onNext(1);
    verify(o, times(3)).onNext(2);
    verify(o, times(3)).onNext(3);
    verify(o).onNext(5);
    verify(o).onCompleted();
    verify(o, never()).onNext(4);

    verify(o, never()).onError(any(Throwable.class));
  }
Beispiel #6
0
  @Test
  public void mustBeAbleToUseFlatMapMerge() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Iterable<Integer> input1 = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
    final Iterable<Integer> input2 = Arrays.asList(10, 11, 12, 13, 14, 15, 16, 17, 18, 19);
    final Iterable<Integer> input3 = Arrays.asList(20, 21, 22, 23, 24, 25, 26, 27, 28, 29);
    final Iterable<Integer> input4 = Arrays.asList(30, 31, 32, 33, 34, 35, 36, 37, 38, 39);

    final List<Source<Integer, NotUsed>> mainInputs = new ArrayList<Source<Integer, NotUsed>>();
    mainInputs.add(Source.from(input1));
    mainInputs.add(Source.from(input2));
    mainInputs.add(Source.from(input3));
    mainInputs.add(Source.from(input4));

    CompletionStage<List<Integer>> future =
        Source.from(mainInputs)
            .flatMapMerge(3, ConstantFun.<Source<Integer, NotUsed>>javaIdentityFunction())
            .grouped(60)
            .runWith(Sink.<List<Integer>>head(), materializer);

    List<Integer> result = future.toCompletableFuture().get(3, TimeUnit.SECONDS);
    final Set<Integer> set = new HashSet<Integer>();
    for (Integer i : result) {
      set.add(i);
    }
    final Set<Integer> expected = new HashSet<Integer>();
    for (int i = 0; i < 40; ++i) {
      expected.add(i);
    }

    assertEquals(expected, set);
  }
Beispiel #7
0
 @Test
 public void restore() throws RuleBaseException, TransformException {
   Node comp1 = content.query().single("/id('comp1')").node();
   Node comp2 = content.query().single("/id('comp2')").node();
   Node cname = content.query().single("/id('cname')").node();
   setModNearestAncestorImplementing(
       NodeTarget.class,
       new NodeTarget() {
         public ItemList targets() throws TransformException {
           return content.query().all("/id('comp1 comp2')");
         }
       });
   setModData("(<sort-siblings run-length='2'/>, <sort-siblings run-length='1'/>)");
   setModReferences(cname, comp2, cname);
   SortBySiblingBlock block = define("<sort before='sibling'>uml:name</sort>");
   SortBySiblingBlock.SortBySiblingSeg seg =
       (SortBySiblingBlock.SortBySiblingSeg) block.createSeg(mod);
   seg.restore();
   assertEquals(
       Arrays.asList(
           new Pair[] {
             Pair.of(comp1, Arrays.asList(cname, comp2)), Pair.of(comp2, Arrays.asList(cname))
           }),
       seg.siblingsByTarget);
 }
Beispiel #8
0
  @Test
  public void testDirSerializer() throws IOException {

    long[][] l = new long[16][];
    l[3] = new long[] {0, 0, 12, 13, 14, 0, Long.MAX_VALUE, 0};
    l[6] = new long[] {1, 2, 3, 4, 5, 6, 7, 8};

    DataOutput2 out = new DataOutput2();
    HTreeMap.DIR_SERIALIZER.serialize(out, l);

    DataInput2 in = swap(out);

    long[][] b = HTreeMap.DIR_SERIALIZER.deserialize(in, -1);

    assertEquals(null, b[0]);
    assertEquals(null, b[1]);
    assertEquals(null, b[2]);
    assertEquals(
        Arrays.toString(new long[] {0, 0, 12, 13, 14, 0, Long.MAX_VALUE, 0}),
        Arrays.toString(b[3]));
    assertEquals(null, b[4]);
    assertEquals(null, b[5]);
    assertEquals(Arrays.toString(new long[] {1, 2, 3, 4, 5, 6, 7, 8}), Arrays.toString(b[6]));
    assertEquals(null, b[7]);
  }
 @Test
 public void valuesToArray() {
   HazelcastClient hClient = getHazelcastClient();
   IMap map = hClient.getMap("valuesToArray");
   assertEquals(0, map.size());
   map.put("a", "1");
   map.put("b", "2");
   map.put("c", "3");
   assertEquals(3, map.size());
   {
     final Object[] values = map.values().toArray();
     Arrays.sort(values);
     assertArrayEquals(new Object[] {"1", "2", "3"}, values);
   }
   {
     final String[] values = (String[]) map.values().toArray(new String[3]);
     Arrays.sort(values);
     assertArrayEquals(new String[] {"1", "2", "3"}, values);
   }
   {
     final String[] values = (String[]) map.values().toArray(new String[2]);
     Arrays.sort(values);
     assertArrayEquals(new String[] {"1", "2", "3"}, values);
   }
   {
     final String[] values = (String[]) map.values().toArray(new String[5]);
     Arrays.sort(values, 0, 3);
     assertArrayEquals(new String[] {"1", "2", "3", null, null}, values);
   }
 }
  @Test
  public void updateTest() throws Exception {

    String query;
    Query update;

    query = "UPDATE foo.bar USING TIMESTAMP 42 SET a=12,b=[3,2,1],c=c+3 WHERE k=2;";
    update =
        update("foo", "bar")
            .using(timestamp(42))
            .with(set("a", 12))
            .and(set("b", Arrays.asList(3, 2, 1)))
            .and(incr("c", 3))
            .where(eq("k", 2));
    assertEquals(query, update.toString());

    query = "UPDATE foo SET a[2]='foo',b=[3,2,1]+b,c=c-{'a'} WHERE k=2;";
    update =
        update("foo")
            .with(setIdx("a", 2, "foo"))
            .and(prependAll("b", Arrays.asList(3, 2, 1)))
            .and(remove("c", "a"))
            .where(eq("k", 2));
    assertEquals(query, update.toString());
  }
Beispiel #11
0
  @Test
  public void mustBeAbleToUseZipWith() throws Exception {
    final JavaTestKit probe = new JavaTestKit(system);
    final Iterable<String> input1 = Arrays.asList("A", "B", "C");
    final Iterable<String> input2 = Arrays.asList("D", "E", "F");

    Source.from(input1)
        .zipWith(
            Source.from(input2),
            new Function2<String, String, String>() {
              public String apply(String s1, String s2) {
                return s1 + "-" + s2;
              }
            })
        .runForeach(
            new Procedure<String>() {
              public void apply(String elem) {
                probe.getRef().tell(elem, ActorRef.noSender());
              }
            },
            materializer);

    probe.expectMsgEquals("A-D");
    probe.expectMsgEquals("B-E");
    probe.expectMsgEquals("C-F");
  }
  @Test
  public void testNormal() {
    @SuppressWarnings("unchecked")
    Observer<Object> o = mock(Observer.class);

    final List<Integer> list = Arrays.asList(1, 2, 3);

    Func1<Integer, List<Integer>> func =
        new Func1<Integer, List<Integer>>() {
          @Override
          public List<Integer> call(Integer t1) {
            return list;
          }
        };
    Func2<Integer, Integer, Integer> resFunc =
        new Func2<Integer, Integer, Integer>() {

          @Override
          public Integer call(Integer t1, Integer t2) {
            return t1 | t2;
          }
        };

    List<Integer> source = Arrays.asList(16, 32, 64);

    Observable.from(source).flatMapIterable(func, resFunc).subscribe(o);

    for (Integer s : source) {
      for (Integer v : list) {
        verify(o).onNext(s | v);
      }
    }
    verify(o).onCompleted();
    verify(o, never()).onError(any(Throwable.class));
  }
  @Test
  public void testAdamUpdater() {
    INDArray m, v;
    double lr = 0.01;
    int iteration = 0;
    double beta1 = 0.8;
    double beta2 = 0.888;

    NeuralNetConfiguration conf =
        new NeuralNetConfiguration.Builder()
            .learningRate(lr)
            .iterations(iteration)
            .adamMeanDecay(beta1)
            .adamVarDecay(beta2)
            .layer(
                new DenseLayer.Builder()
                    .nIn(nIn)
                    .nOut(nOut)
                    .updater(org.deeplearning4j.nn.conf.Updater.ADAM)
                    .build())
            .build();

    int numParams = LayerFactories.getFactory(conf).initializer().numParams(conf, true);
    INDArray params = Nd4j.create(1, numParams);
    Layer layer = LayerFactories.getFactory(conf).create(conf, null, 0, params, true);
    Updater updater = UpdaterCreator.getUpdater(layer);
    int updaterStateSize = updater.stateSizeForLayer(layer);
    INDArray updaterState = Nd4j.create(1, updaterStateSize);
    updater.setStateViewArray(layer, updaterState, true);

    updater.update(layer, gradient, iteration, 1);

    double beta1t = FastMath.pow(beta1, iteration);
    double beta2t = FastMath.pow(beta2, iteration);
    double alphat = lr * FastMath.sqrt(1 - beta2t) / (1 - beta1t);
    if (Double.isNaN(alphat) || alphat == 0.0) alphat = epsilon;

    Gradient gradientDup = new DefaultGradient();
    gradientDup.setGradientFor(DefaultParamInitializer.WEIGHT_KEY, weightGradient);
    gradientDup.setGradientFor(DefaultParamInitializer.BIAS_KEY, biasGradient);

    for (Map.Entry<String, INDArray> entry : gradientDup.gradientForVariable().entrySet()) {
      val = entry.getValue();
      m = Nd4j.zeros(val.shape());
      v = Nd4j.zeros(val.shape());

      m.muli(beta1).addi(val.mul(1.0 - beta1));
      v.muli(beta2).addi(val.mul(val).mul(1.0 - beta2));
      gradExpected = m.mul(alphat).divi(Transforms.sqrt(v).addi(epsilon));
      if (!gradExpected.equals(gradient.getGradientFor(entry.getKey()))) {
        System.out.println(Arrays.toString(gradExpected.dup().data().asFloat()));
        System.out.println(
            Arrays.toString(gradient.getGradientFor(entry.getKey()).dup().data().asFloat()));
      }
      assertEquals(gradExpected, gradient.getGradientFor(entry.getKey()));
    }

    assertEquals(beta1, layer.conf().getLayer().getAdamMeanDecay(), 1e-4);
    assertEquals(beta2, layer.conf().getLayer().getAdamVarDecay(), 1e-4);
  }
  /** Test for creating zobjects with relationships */
  @Test
  @SuppressWarnings("serial")
  public void createAndDeleteRelated() throws Exception {
    SaveResult saveResult =
        module.create(ZObjectType.Account, Collections.singletonList(testAccount())).get(0);
    assertTrue(saveResult.isSuccess());

    final String accountId = saveResult.getId();
    try {
      SaveResult result =
          module
              .create(
                  ZObjectType.Contact,
                  Collections.<Map<String, Object>>singletonList(
                      new HashMap<String, Object>() {
                        {
                          put("Country", "US");
                          put("FirstName", "John");
                          put("LastName", "Doe");
                          put("AccountId", accountId);
                        }
                      }))
              .get(0);
      assertTrue(result.isSuccess());

      DeleteResult deleteResult =
          module.delete(ZObjectType.Contact, Arrays.asList(result.getId())).get(0);
      assertTrue(deleteResult.isSuccess());
    } finally {
      module.delete(ZObjectType.Account, Arrays.asList(accountId)).get(0);
    }
  }
 @Test
 public void large_record_update() {
   byte[] b = new byte[100000];
   Arrays.fill(b, (byte) 111);
   long recid = engine.recordPut(b, Serializer.BYTE_ARRAY_SERIALIZER);
   Arrays.fill(b, (byte) 222);
   engine.recordUpdate(recid, b, Serializer.BYTE_ARRAY_SERIALIZER);
   byte[] b2 = engine.recordGet(recid, Serializer.BYTE_ARRAY_SERIALIZER);
   assertArrayEquals(b, b2);
 }
 @Test
 public void testNnclean() throws Exception {
   double[] y = HET_DEL_5X_5N;
   double[] nonnoise =
       new double[] {260.0736, 197.4272, 194.8618, 1217.8588, 1228.2190, 1151.7017};
   double[] result = scorer.nnclean(y, scorer.cleanYIndices(y, 30, 2, 5));
   Arrays.sort(result);
   Arrays.sort(nonnoise);
   assertArrayEquals(nonnoise, result, 0.000001);
 }
Beispiel #17
0
  @Test
  public void test_dir_node_serialization() throws IOException {

    BTreeMap.DirNode n =
        new BTreeMap.DirNode(new Object[] {1, 2, 3}, false, true, false, mkchild(4, 5, 6, 0));
    BTreeMap.DirNode n2 = (BTreeMap.DirNode) TT.clone(n, m.nodeSerializer);

    assertTrue(Arrays.equals(nodeKeysToArray(n), nodeKeysToArray(n2)));
    assertTrue(Arrays.equals((int[]) n.child, (int[]) n2.child));
  }
Beispiel #18
0
  @org.junit.Test
  public void testGenerateValuesMultiRecipesInvalidIngredient() throws Exception {
    mappingCollector.setValueBefore("a1", 1);
    mappingCollector.addConversion(1, "b2", Arrays.asList("a1", "a1"));
    mappingCollector.addConversion(1, "b2", Arrays.asList("invalid"));

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(1, getValue(values, "a1"));
    assertEquals(2, getValue(values, "b2"));
    assertEquals(0, getValue(values, "invalid"));
  }
Beispiel #19
0
  @Test
  public void root_leaf_insert() {
    if (valsOutside) return;

    m.put(11, 12);
    final long rootRecid = engine.get(m.rootRecidRef, Serializer.RECID);
    BTreeMap.LeafNode n = (BTreeMap.LeafNode) engine.get(rootRecid, m.nodeSerializer);
    assertTrue(Arrays.equals(new Object[] {null, 11, null}, nodeKeysToArray(n)));
    assertTrue(Arrays.equals(new Object[] {12}, (Object[]) n.vals));
    assertEquals(0, n.next);
  }
Beispiel #20
0
 @org.junit.Test
 public void testOverwriteConversions() {
   mappingCollector.setValueBefore("a", 1);
   mappingCollector.setValueFromConversion(1, "b", Arrays.asList("a", "a", "a"));
   mappingCollector.addConversion(1, "b", Arrays.asList("a"));
   mappingCollector.addConversion(1, "c", Arrays.asList("b", "b"));
   Map<String, Integer> values = valueGenerator.generateValues();
   assertEquals(1, getValue(values, "a"));
   assertEquals(3, getValue(values, "b"));
   assertEquals(6, getValue(values, "c"));
 }
Beispiel #21
0
  @org.junit.Test
  public void testGenerateValuesSimple() throws Exception {
    mappingCollector.setValueBefore("a1", 1);
    mappingCollector.addConversion(1, "c4", Arrays.asList("a1", "a1", "a1", "a1"));
    mappingCollector.addConversion(1, "b2", Arrays.asList("a1", "a1"));

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(1, getValue(values, "a1"));
    assertEquals(2, getValue(values, "b2"));
    assertEquals(4, getValue(values, "c4"));
  }
Beispiel #22
0
  @org.junit.Test
  public void testGenerateValuesWool() throws Exception {
    final String[] dyes = new String[] {"Blue", "Brown", "White", "Other"};
    final int[] dyeValue = new int[] {864, 176, 48, 16};
    for (int i = 0; i < dyes.length; i++) {
      mappingCollector.setValueBefore("dye" + dyes[i], dyeValue[i]);
      mappingCollector.addConversion(
          1, "wool" + dyes[i], Arrays.asList("woolWhite", "dye" + dyes[i]));
    }
    mappingCollector.setValueBefore("string", 12);
    mappingCollector.addConversion(
        1, "woolWhite", Arrays.asList("string", "string", "string", "string"));

    mappingCollector.setValueBefore("stick", 4);
    mappingCollector.setValueBefore("plank", 8);
    for (String dye : dyes) {
      mappingCollector.addConversion(
          1,
          "bed",
          Arrays.asList("plank", "plank", "plank", "wool" + dye, "wool" + dye, "wool" + dye));
      mappingCollector.addConversion(3, "carpet" + dye, Arrays.asList("wool" + dye, "wool" + dye));
      mappingCollector.addConversion(
          1,
          "painting",
          Arrays.asList(
              "wool" + dye,
              "stick",
              "stick",
              "stick",
              "stick",
              "stick",
              "stick",
              "stick",
              "stick"));
    }

    Map<String, Integer> values = valueGenerator.generateValues();
    for (int i = 0; i < dyes.length; i++) {
      assertEquals(dyeValue[i], getValue(values, "dye" + dyes[i]));
    }
    assertEquals(12, getValue(values, "string"));
    assertEquals(48, getValue(values, "woolWhite"));
    assertEquals(224, getValue(values, "woolBrown"));
    assertEquals(912, getValue(values, "woolBlue"));
    assertEquals(64, getValue(values, "woolOther"));

    assertEquals(32, getValue(values, "carpetWhite"));
    assertEquals(149, getValue(values, "carpetBrown"));
    assertEquals(608, getValue(values, "carpetBlue"));
    assertEquals(42, getValue(values, "carpetOther"));

    assertEquals(168, getValue(values, "bed"));
    assertEquals(80, getValue(values, "painting"));
  }
  @Test
  public void testInit_NonEmptyCollection() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    when(connection1.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);"))
        .thenReturn(preparedStatement);
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {2});

    // The objects to add
    Set<Car> initWithObjects = new HashSet<Car>(2);
    initWithObjects.add(
        new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps")));
    initWithObjects.add(
        new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags")));

    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.init(initWithObjects, new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(statement, times(2)).close();
    verify(connection, times(1)).close();

    verify(preparedStatement, times(2)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(1)).setObject(2, "abs");
    verify(preparedStatement, times(1)).setObject(2, "gps");
    verify(preparedStatement, times(1)).setObject(2, "airbags");
    verify(preparedStatement, times(3)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(preparedStatement, times(1)).close();
    verify(connection1, times(1)).close();
  }
Beispiel #24
0
  @org.junit.Test
  public void testGenerateValuesSimpleWoodToWorkBench() throws Exception {
    mappingCollector.setValueBefore("planks", 1);
    mappingCollector.addConversion(4, "planks", Arrays.asList("wood"));
    mappingCollector.addConversion(
        1, "workbench", Arrays.asList("planks", "planks", "planks", "planks"));

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(0, getValue(values, "wood"));
    assertEquals(1, getValue(values, "planks"));
    assertEquals(4, getValue(values, "workbench"));
  }
Beispiel #25
0
  @org.junit.Test
  public void testGenerateValuesDelayedCycleRecipeExploit() throws Exception {
    mappingCollector.setValueBefore("a1", 1);
    // Exploitable Cycle Recype
    mappingCollector.addConversion(1, "exploitable1", Arrays.asList("a1"));
    mappingCollector.addConversion(2, "exploitable2", Arrays.asList("exploitable1"));
    mappingCollector.addConversion(1, "exploitable1", Arrays.asList("exploitable2"));

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(1, getValue(values, "a1"));
    assertEquals(0, getValue(values, "exploitable1"));
    assertEquals(0, getValue(values, "exploitable2"));
  }
Beispiel #26
0
  @org.junit.Test
  public void testGenerateValuesSimpleMultiRecipeWithEmptyAlternative() throws Exception {
    mappingCollector.setValueBefore("a1", 1);
    // 2 Recipes for c4
    mappingCollector.addConversion(1, "c4", Arrays.asList("a1", "a1", "a1", "a1"));
    mappingCollector.addConversion(1, "c4", new LinkedList<String>());
    mappingCollector.addConversion(1, "b2", Arrays.asList("a1", "a1"));

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(1, getValue(values, "a1"));
    assertEquals(2, getValue(values, "b2"));
    assertEquals(4, getValue(values, "c4")); // 2 * c4 = 2 * b2 => 2 * (2) = 2 * (2)
  }
Beispiel #27
0
  @org.junit.Test
  public void testGenerateValuesSimpleFixedDoNotInheritMultiRecipes() throws Exception {
    mappingCollector.setValueBefore("a1", 1);
    mappingCollector.addConversion(1, "c", Arrays.asList("a1", "a1"));
    mappingCollector.addConversion(1, "c", Arrays.asList("a1", "b"));
    mappingCollector.setValueBefore("b", 0);
    mappingCollector.setValueAfter("b", 20);

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(1, getValue(values, "a1"));
    assertEquals(20, getValue(values, "b"));
    assertEquals(2, getValue(values, "c"));
  }
  @Test
  public void testNotifyObjectsRemoved() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(connection1.prepareStatement("DELETE FROM " + TABLE_NAME + " WHERE objectKey = ?;"))
        .thenReturn(preparedStatement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {1});

    // The objects to add
    Set<Car> removedObjects = new HashSet<Car>(2);
    removedObjects.add(
        new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps")));
    removedObjects.add(
        new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags")));

    @SuppressWarnings({"unchecked", "unused"})
    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.removeAll(removedObjects, new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(connection, times(1)).close();

    verify(preparedStatement, times(1)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(2)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(connection1, times(1)).close();
  }
Beispiel #29
0
  @org.junit.Test
  public void testGenerateValuesDeepInvalidConversion() throws Exception {
    mappingCollector.setValueBefore("a1", 1);
    mappingCollector.addConversion(1, "b", Arrays.asList("a1", "invalid1"));
    mappingCollector.addConversion(1, "invalid1", Arrays.asList("a1", "invalid2"));
    mappingCollector.addConversion(1, "invalid2", Arrays.asList("a1", "invalid3"));

    Map<String, Integer> values = valueGenerator.generateValues();
    assertEquals(1, getValue(values, "a1"));
    assertEquals(0, getValue(values, "b"));
    assertEquals(0, getValue(values, "invalid1"));
    assertEquals(0, getValue(values, "invalid2"));
    assertEquals(0, getValue(values, "invalid3"));
  }
Beispiel #30
0
 @SuppressWarnings("unchecked")
 @Test(expected = TransformException.class)
 public void verifyNotSibling() throws RuleBaseException, TransformException {
   Node uc1 = content.query().single("/id('uc1')").node();
   Node comp1 = content.query().single("/id('comp1')").node();
   Node um1 = content.query().single("/id('um1')").node();
   setModScope(uc1.query());
   SortBySiblingBlock block = define("<sort before='sibling'>.//uml:method</sort>");
   SortBySiblingBlock.SortBySiblingSeg seg =
       (SortBySiblingBlock.SortBySiblingSeg) block.createSeg(mod);
   seg.siblingsByTarget =
       Arrays.<Pair<Node, List<Node>>>asList(new Pair[] {Pair.of(comp1, Arrays.asList(um1))});
   seg.verify();
 }