Java Code Examples for org.junit.Assert#assertNotEquals()

The following examples show how to use org.junit.Assert#assertNotEquals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestOMVolumeCreateRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Verify modifiedOmRequest and originalRequest.
 * @param modifiedRequest
 * @param originalRequest
 */
private void verifyRequest(OMRequest modifiedRequest,
    OMRequest originalRequest) {
  VolumeInfo original = originalRequest.getCreateVolumeRequest()
      .getVolumeInfo();
  VolumeInfo updated = modifiedRequest.getCreateVolumeRequest()
      .getVolumeInfo();

  Assert.assertEquals(original.getAdminName(), updated.getAdminName());
  Assert.assertEquals(original.getVolume(), updated.getVolume());
  Assert.assertEquals(original.getOwnerName(),
      updated.getOwnerName());
  Assert.assertNotEquals(original.getCreationTime(),
      updated.getCreationTime());
  Assert.assertNotEquals(original.getModificationTime(),
      updated.getModificationTime());
}
 
Example 2
Source File: SessionizeUDFTest.java    From incubator-hivemall with Apache License 2.0 6 votes vote down vote up
@Test
public void testTwoArgs() {
    SessionizeUDF udf = new SessionizeUDF();

    Text session1 = new Text(udf.evaluate(val(30L), val(10L)));
    Assert.assertNotNull(session1);

    Text session2 = new Text(udf.evaluate(val(35L), val(10L)));
    Assert.assertEquals(session1, session2);

    Text session3 = new Text(udf.evaluate(val(40L), val(10L)));
    Assert.assertEquals(session2, session3);

    Text session4 = new Text(udf.evaluate(val(50L), val(10L)));
    Assert.assertNotEquals(session3, session4);
}
 
Example 3
Source File: Neo4JGraphWhileCurrentSessionTest.java    From neo4j-gremlin-bolt with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void givenGraphWithSessionShouldReturnAnotherSessionFromADifferentThread() throws InterruptedException {
    // arrange
    Mockito.when(driver.session(Mockito.any())).thenReturn(session);
    Mockito.when(provider.fieldName()).thenAnswer(invocation -> "id");
    try (Neo4JGraph graph = new Neo4JGraph(driver, provider, provider)) {
        try (final Neo4JSession neo4JSession1 = graph.currentSession()) {
            Assert.assertNotNull("Failed to create Neo4JSession instance", neo4JSession1);
            // act
            Thread thread = new Thread(() -> {
                try (Neo4JSession neo4JSession2 = graph.currentSession()) {
                    // assert
                    Assert.assertNotNull("Failed to return Neo4JSession instance", neo4JSession2);
                    Assert.assertNotEquals("Using the same session from a different thread", neo4JSession1, neo4JSession2);
                }
            });
            thread.start();
            thread.join();
        }
    }
}
 
Example 4
Source File: ReplicationStoreMetaTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testEquals(){
	
	ReplicationStoreMeta meta = createRandomMeta();

	ReplicationStoreMeta meta2 = SerializationUtils.clone(meta);
	Assert.assertEquals(meta, meta2);

	ReplicationStoreMeta meta3 = new ReplicationStoreMeta(meta);
	Assert.assertEquals(meta, meta3);
	
	meta3.setBeginOffset(meta3.getBeginOffset()+1);
	Assert.assertNotEquals(meta, meta3);
}
 
Example 5
Source File: Point2STest.java    From commons-geometry with Apache License 2.0 5 votes vote down vote up
@Test
public void testNaN() {
    // act/assert
    Assert.assertTrue(Point2S.NaN.isNaN());
    Assert.assertEquals(Point2S.NaN, Point2S.of(Double.NaN, 1.0));
    Assert.assertNotEquals(Point2S.of(1.0, 1.3), Point2S.NaN);
    Assert.assertNull(Point2S.NaN.getVector());

    Assert.assertEquals(Point2S.NaN.hashCode(), Point2S.of(Double.NaN, Double.NaN).hashCode());
}
 
Example 6
Source File: AionMapTest.java    From AVM with MIT License 5 votes vote down vote up
@Test
public void checkHashCode() {
    final int size = 20;
    final int hashCount = 10;
    AionMap<TestElement, String> map = createAionMap(size, hashCount);

    AionMap<TestElement, String> mapSame = map;
    Assert.assertEquals(map.hashCode(), mapSame.hashCode());

    AionMap<TestElement, String> mapDifferent = createAionMap(size, hashCount);
    Assert.assertNotEquals(map.hashCode(), mapDifferent.hashCode());
}
 
Example 7
Source File: TestOMVolumeDeleteRequest.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreExecute() throws Exception {
  String volumeName = UUID.randomUUID().toString();
  OMRequest originalRequest = deleteVolumeRequest(volumeName);

  OMVolumeDeleteRequest omVolumeDeleteRequest =
      new OMVolumeDeleteRequest(originalRequest);

  OMRequest modifiedRequest = omVolumeDeleteRequest.preExecute(ozoneManager);
  Assert.assertNotEquals(originalRequest, modifiedRequest);
}
 
Example 8
Source File: ValidationStepDefinitions.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
/**
 * Verify that an aliased value is not equal to the supplied string
 * @param alias The aliased value to check
 * @param valueAlias Add the word alias to indicate that the expected value is an alias key
 * @param expectedValue The value that the aliased value is expected to equal
 */
@Then("(?:I verify(?: that)? )?(?:the )?alias \"([^\"]*)\" is not equal to((?: the)? alias)? \"([^\"]*)\"")
public void verifyIsNotEqual(final String alias, final String valueAlias, final String expectedValue) {
	final String fixedValue = autoAliasUtils.getValue(
		expectedValue, StringUtils.isNotBlank(valueAlias), State.getFeatureStateForThread());

	final String value = State.getFeatureStateForThread().getDataSet().get(alias);
	Assert.assertNotEquals(fixedValue, value);
}
 
Example 9
Source File: MemberTest.java    From incubator-retired-gossip with Apache License 2.0 5 votes vote down vote up
@Test
public void testHashCodeFromGossip40() throws URISyntaxException {
  Assert.assertNotEquals(
          new LocalMember("mycluster", new URI("udp://4.4.4.4:1000"), "myid", 1, new HashMap<String,String>(), 10, 5, "exponential")
                  .hashCode(),
          new LocalMember("mycluster", new URI("udp://4.4.4.5:1005"), "yourid", 11, new HashMap<String,String>(), 11, 6, "exponential")
                  .hashCode());
}
 
Example 10
Source File: SortedDedupedJexlStringBuildingVisitorTest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpressionDelayed() throws Exception {
    JexlNode queryA = JexlASTHelper.parseJexlQuery("FOO == 'abc'");
    JexlNode queryB = ASTDelayedPredicate.create(JexlASTHelper.parseJexlQuery("FOO == 'abc'"));
    Assert.assertNotEquals(nodeToKey(queryA), nodeToKey(queryB));
    
}
 
Example 11
Source File: GattUtilsTest.java    From bitgatt with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void testCopyServiceWithCharacteristicWithDescriptorChildWithData() {
    byte[] data = new byte[]{0x01, 0x02, 0x03};
    BluetoothGattService service = mock(BluetoothGattService.class);
    when(service.getUuid()).thenReturn(UUID.fromString("70FE657D-BBB0-4D17-B6A6-8C0545C4001F"));
    when(service.getType()).thenReturn(BluetoothGattService.SERVICE_TYPE_PRIMARY);
    BluetoothGattCharacteristic characteristic = mock(BluetoothGattCharacteristic.class);
    // this should be the same as the real thing, the data inside could change as it's pointing
    // to something else.
    when(characteristic.getValue()).thenReturn(data);
    when(characteristic.getUuid()).thenReturn(UUID.fromString("E69169D1-11A7-4545-B7FC-02A3ADFC3EAC"));
    when(characteristic.getPermissions()).thenReturn(BluetoothGattCharacteristic.PERMISSION_READ);
    when(characteristic.getProperties()).thenReturn(BluetoothGattCharacteristic.PROPERTY_NOTIFY);
    BluetoothGattDescriptor descriptor = mock(BluetoothGattDescriptor.class);
    // this should be the same as the real thing, the data inside could change as it's pointing
    // to something else.
    when(descriptor.getValue()).thenReturn(data);
    when(descriptor.getUuid()).thenReturn(UUID.fromString("F752AF23-EA2C-45BA-892C-5964B0D244A2"));
    when(descriptor.getPermissions()).thenReturn(BluetoothGattDescriptor.PERMISSION_READ);
    characteristic.addDescriptor(descriptor);
    service.addCharacteristic(characteristic);
    BluetoothGattServiceCopy result = new GattUtils().copyService(service);
    if(result == null) {
        fail(String.format(Locale.ENGLISH, "The result was null for service: %s, with characteristic data: %s", characteristic.getUuid(), Arrays.toString(characteristic.getValue())));
        return;
    }
    Assert.assertNotEquals(descriptor, characteristic.getDescriptor(descriptor.getUuid()));
    Assert.assertNotEquals(characteristic, service.getCharacteristic(characteristic.getUuid()));
    Assert.assertArrayEquals(descriptor.getValue(), data);
}
 
Example 12
Source File: FillTest.java    From Oak with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    Random r = new Random();

    int id = (int) Thread.currentThread().getId() % ThreadIndexCalculator.MAX_THREADS;
    int amount = (int) Math.round(NUM_OF_ENTRIES * 0.5) / NUM_THREADS;
    int start = id * amount + (int) Math.round(NUM_OF_ENTRIES * 0.5);
    int end = (id + 1) * amount + (int) Math.round(NUM_OF_ENTRIES * 0.5);

    int[] arr = new int[amount];
    for (int i = start, j = 0; i < end; i++, j++) {
        arr[j] = i;
    }

    int usedIdx = arr.length - 1;

    for (int i = 0; i < amount; i++) {

        int nextIdx = r.nextInt(usedIdx + 1);
        Integer next = arr[nextIdx];

        int tmp = arr[usedIdx];
        arr[usedIdx] = next;
        arr[nextIdx] = tmp;
        usedIdx--;

        oak.zc().putIfAbsent(next, next);
    }

    for (int i = end - 1; i >= start; i--) {
        Assert.assertNotEquals(oak.get(i), null);
    }

}
 
Example 13
Source File: AttrListTest.java    From fastods with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testEquals() throws IOException, SAXException {
    Assert.assertEquals(this.attrList, this.attrList);
    Assert.assertNotEquals("attrList", this.attrList);
    Assert.assertNotEquals(this.attrList, "attrList");

    final Document document =
            this.builder.parse(new ByteArrayInputStream(("<s b='2' a='1'/>").getBytes(
                    Charsets.UTF_8)));
    final NamedNodeMap attributes2 = document.getElementsByTagName("s").item(0).getAttributes();
    final AttrList attrList2 = AttrList.create(attributes2);
    Assert.assertEquals(attrList2, this.attrList);
    Assert.assertEquals(attrList2.hashCode(), this.attrList.hashCode());
}
 
Example 14
Source File: AdvancedDcMetaServiceTestForConcurrent.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
@Test
public void testDcComparator() {
    DcMeta jqFuture = service.getDcMeta("NTGXH");
    jqFuture.addCluster(new ClusterMeta("add"));

    DcComparator dcComparator = new DcComparator(getDcMeta("NTGXH"), jqFuture);

    Assert.assertNotEquals(0, dcComparator.getAdded().size());
    Assert.assertEquals(0, dcComparator.getRemoved().size());
    Assert.assertEquals(0, dcComparator.getMofified().size());
}
 
Example 15
Source File: TestReplacePartitions.java    From iceberg with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationSuccess() {
  table.newFastAppend()
      .appendFile(FILE_A)
      .appendFile(FILE_B)
      .commit();

  TableMetadata base = readMetadata();
  long baseId = base.currentSnapshot().snapshotId();

  table.newReplacePartitions()
      .addFile(FILE_G)
      .validateAppendOnly()
      .commit();

  long replaceId = readMetadata().currentSnapshot().snapshotId();
  Assert.assertNotEquals("Should create a new snapshot", baseId, replaceId);
  Assert.assertEquals("Table should have 2 manifests",
      2, table.currentSnapshot().manifests().size());

  // manifest is not merged because it is less than the minimum
  validateManifestEntries(table.currentSnapshot().manifests().get(0),
      ids(replaceId),
      files(FILE_G),
      statuses(Status.ADDED));

  validateManifestEntries(table.currentSnapshot().manifests().get(1),
      ids(baseId, baseId),
      files(FILE_A, FILE_B),
      statuses(Status.ADDED, Status.ADDED));
}
 
Example 16
Source File: TransferFailed004.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test(enabled = true, description = "Suicide nonexistent target")
public void test1SuicideNonexistentTarget() {
  Assert.assertTrue(PublicMethed
      .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey,
          blockingStubFull));
  String filePath = "src/test/resources/soliditycode_v0.5.4/TransferFailed001.sol";
  String contractName = "CpuOfTransferFailedTest";
  HashMap retMap = PublicMethed.getByCodeAbi(filePath, contractName);
  String code = retMap.get("byteCode").toString();
  String abi = retMap.get("abi").toString();

  contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit,
      0L, 100, null, contractExcKey,
      contractExcAddress, blockingStubFull);
  PublicMethed.waitProduceNextBlock(blockingStubFull);
  Assert.assertTrue(PublicMethed
      .sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey,
          blockingStubFull));

  Account info;

  AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress,
      blockingStubFull);
  info = PublicMethed.queryAccount(contractExcKey, blockingStubFull);
  Long beforeBalance = info.getBalance();
  Long beforeCpuUsed = resourceInfo.getCpuUsed();
  Long beforeNetUsed = resourceInfo.getNetUsed();
  Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed();
  logger.info("beforeBalance:" + beforeBalance);
  logger.info("beforeCpuUsed:" + beforeCpuUsed);
  logger.info("beforeNetUsed:" + beforeNetUsed);
  logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed);
  String txid = "";
  String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\"";

  txid = PublicMethed.triggerContract(contractAddress,
      "testSuicideNonexistentTarget(address)", num, false,
      0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull);
  Optional<TransactionInfo> infoById = null;
  PublicMethed.waitProduceNextBlock(blockingStubFull);
  infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull);
  logger.info("infobyid : --- " + infoById);

  Long fee = infoById.get().getFee();
  Long netUsed = infoById.get().getReceipt().getNetUsage();
  Long cpuUsed = infoById.get().getReceipt().getCpuUsage();
  Long netFee = infoById.get().getReceipt().getNetFee();
  long cpuUsageTotal = infoById.get().getReceipt().getCpuUsageTotal();
  logger.info("fee:" + fee);
  logger.info("netUsed:" + netUsed);
  logger.info("cpuUsed:" + cpuUsed);
  logger.info("netFee:" + netFee);
  logger.info("cpuUsageTotal:" + cpuUsageTotal);

  Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1);
  AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress,
      blockingStubFull1);
  Long afterBalance = infoafter.getBalance();
  Long afterCpuUsed = resourceInfoafter.getCpuUsed();
  Long afterNetUsed = resourceInfoafter.getNetUsed();
  Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed();
  logger.info("afterBalance:" + afterBalance);
  logger.info("afterCpuUsed:" + afterCpuUsed);
  logger.info("afterNetUsed:" + afterNetUsed);
  logger.info("afterFreeNetUsed:" + afterFreeNetUsed);

  Assert.assertTrue(infoById.get().getResultValue() == 1);
  Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult());
  Assert.assertEquals(
      "transfer all token or transfer all Gsc failed in suicide: "
          + "Validate InternalTransfer error, no ToAccount. And not allowed "
          + "to create account in smart contract.",
      ByteArray.toStr(infoById.get().getResMessage().toByteArray()));

  Assert.assertTrue(afterBalance + fee == beforeBalance);
  Assert.assertTrue(beforeCpuUsed + cpuUsed >= afterCpuUsed);
  Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed);
  Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed);
  Assert.assertNotEquals(10000000, cpuUsageTotal);


}
 
Example 17
Source File: TransferFailed001.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test(enabled = true, description = "Transfer Gsc nonexistent target")
public void test3TransferGscNonexistentTarget() {

  Assert.assertTrue(PublicMethed
      .sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey,
          blockingStubFull));

  Account info;

  AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress,
      blockingStubFull);
  info = PublicMethed.queryAccount(contractExcKey, blockingStubFull);
  Long beforeBalance = info.getBalance();
  Long beforeCpuUsed = resourceInfo.getCpuUsed();
  Long beforeNetUsed = resourceInfo.getNetUsed();
  Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed();
  logger.info("beforeBalance:" + beforeBalance);
  logger.info("beforeCpuUsed:" + beforeCpuUsed);
  logger.info("beforeNetUsed:" + beforeNetUsed);
  logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed);
  ECKey ecKey2 = new ECKey(Utils.getRandom());
  byte[] nonexistentAddress = ecKey2.getAddress();
  String txid = "";
  String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\"";

  txid = PublicMethed.triggerContract(contractAddress,
      "testTransferGscNonexistentTarget(uint256,address)", num, false,
      0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull);
  Optional<TransactionInfo> infoById = null;
  PublicMethed.waitProduceNextBlock(blockingStubFull);
  infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull);
  logger.info("infobyid : --- " + infoById);

  Long fee = infoById.get().getFee();
  Long netUsed = infoById.get().getReceipt().getNetUsage();
  Long cpuUsed = infoById.get().getReceipt().getCpuUsage();
  Long netFee = infoById.get().getReceipt().getNetFee();
  long cpuUsageTotal = infoById.get().getReceipt().getCpuUsageTotal();
  logger.info("fee:" + fee);
  logger.info("netUsed:" + netUsed);
  logger.info("cpuUsed:" + cpuUsed);
  logger.info("netFee:" + netFee);
  logger.info("cpuUsageTotal:" + cpuUsageTotal);

  Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1);
  AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress,
      blockingStubFull1);
  Long afterBalance = infoafter.getBalance();
  Long afterCpuUsed = resourceInfoafter.getCpuUsed();
  Long afterNetUsed = resourceInfoafter.getNetUsed();
  Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed();
  logger.info("afterBalance:" + afterBalance);
  logger.info("afterCpuUsed:" + afterCpuUsed);
  logger.info("afterNetUsed:" + afterNetUsed);
  logger.info("afterFreeNetUsed:" + afterFreeNetUsed);

  Assert.assertTrue(infoById.get().getResultValue() == 1);
  Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult());
  Assert.assertEquals(
      "transfer gsc failed: Validate InternalTransfer error, no ToAccount."
          + " And not allowed to create account in smart contract.",
      ByteArray.toStr(infoById.get().getResMessage().toByteArray()));

  Assert.assertTrue(afterBalance + fee == beforeBalance);
  Assert.assertTrue(beforeCpuUsed + cpuUsed >= afterCpuUsed);
  Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed);
  Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed);
  Assert.assertNotEquals(10000000, cpuUsageTotal);


}
 
Example 18
Source File: ColumnTest.java    From DataFrame with MIT License 4 votes vote down vote up
@Test
public void testBooleanColumn() {
    BooleanColumn column = new BooleanColumn();
    column.append(true);
    column.append(false);
    column.appendAll(Arrays.asList(new Boolean[]{true, true, false}));
    Assert.assertEquals(5, column.size());
    BooleanColumn copyColumn = column.copyEmpty();
    Assert.assertEquals(0, copyColumn.size());

    copyColumn = column.copy();
    Assert.assertArrayEquals(column.toArray(), copyColumn.toArray());

    copyColumn.set(0, false);
    Assert.assertNotEquals(column.get(0), copyColumn.get(0));


    copyColumn = new BooleanColumn("test", column.toArray(new Boolean[0]));
    Assert.assertArrayEquals(column.toArray(), copyColumn.toArray());
    copyColumn.set(0, false);
    Assert.assertNotEquals(column.get(0), copyColumn.get(0));

    copyColumn = new BooleanColumn("test", column.toArray(new Boolean[0]), 2);
    Assert.assertEquals(2, copyColumn.size());
    Assert.assertEquals(column.get(0), copyColumn.get(0));
    Assert.assertEquals(column.get(1), copyColumn.get(1));


    BooleanColumn a = new BooleanColumn("a", new Boolean[]{true, true, false, false});

    BooleanColumn b = new BooleanColumn("b", new Boolean[]{true, false, false, true});

    Assert.assertArrayEquals(
            new Boolean[]{true, false, false, false}
            , a.copy().and(b)
                    .toArray());

    Assert.assertArrayEquals(
            new Boolean[]{false, true, false, false}
            , a.copy().andNot(b)
                    .toArray());

    Assert.assertArrayEquals(
            new Boolean[]{true, true, false, true}
            , a.copy().or(b)
                    .toArray());

    Assert.assertArrayEquals(
            new Boolean[]{false, true, false, true}
            , a.copy().xor(b)
                    .toArray());

    Assert.assertArrayEquals(
            new Boolean[]{false, false, true, true}
            , a.copy().flip()
                    .toArray());

    try {
        Assert.assertEquals(
                (Boolean) true, column.getParser().parse("true")
        );
        Assert.assertEquals(
                (Boolean) false, column.getParser().parse("false")
        );
        Assert.assertEquals(
                (Boolean) true, column.getParser().parse("TRUE")
        );
        Assert.assertEquals(
                (Boolean) false, column.getParser().parse("FALSE")
        );
        Assert.assertEquals(
                null, column.getParser().parseOrNull("false1")
        );
    } catch (ParseException e) {
        e.printStackTrace();
    }

}
 
Example 19
Source File: VTImpliedMatchCorrelatorTest.java    From ghidra with Apache License 2.0 4 votes vote down vote up
@Test
public void testImpliedMatches_ExactFunctionBytesMatch() throws Exception {

	//Run the Exact Function Correlator
	String exactMatchCorrelator = "Exact Function Bytes Match";
	runTestCorrelator(exactMatchCorrelator);

	// apply all exact matches
	List<VTMatchSet> exactMatchSets = session.getMatchSets();
	for (VTMatchSet ms : exactMatchSets) {
		if (ms.getProgramCorrelatorInfo().getName().equals(exactMatchCorrelator)) {
			ApplyMatchTask task =
				new ApplyMatchTask(controller, (List<VTMatch>) ms.getMatches());
			runTask(task);
		}
	}

	//get the matches only from the correlator just run
	VTMatchSet testMatchSet = getVTMatchSet("Implied Match");

	Assert.assertNotEquals("vtMatchSet does not exist", null, testMatchSet);

	/* 
	 * Test that only non-thunks are in this set
	 */

	// first test the number of implied matches
	assertEquals(17, testMatchSet.getMatchCount());

	// now test the expected matches which are real functions or data, not thunks
	// if all are in set and we tested the size then no thunks are in the set
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00400000"), addr(destProg, "00400000"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "0040003c"), addr(destProg, "0040003c"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004000e0"), addr(destProg, "004000d0"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004000f8"), addr(destProg, "004000e8"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00400154"), addr(destProg, "00400144"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004001c8"), addr(destProg, "004001b8"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004123f0"), addr(destProg, "004123d0"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00416a84"), addr(destProg, "00416a84"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00416a9c"), addr(destProg, "00416a9c"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00416dbc"), addr(destProg, "00416dbc"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "0041713c"), addr(destProg, "0041713c"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004176cc"), addr(destProg, "004176cc"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004176d0"), addr(destProg, "004176cc"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "004178d8"), addr(destProg, "004178d8"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00418008"), addr(destProg, "00418008"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "00418168"), addr(destProg, "00418168"), testMatchSet));
	assertTrue(
		isMatchInMatchSet(addr(srcProg, "0041816c"), addr(destProg, "0041816c"), testMatchSet));
}
 
Example 20
Source File: DeduplicatingContentStoreTest.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
@Test
public void unconfiguredDeduplication() throws Exception
{
    final DictionaryService dictionaryService = EasyMock.mock(DictionaryService.class);

    final DeduplicatingContentStore deduplicatingContentStore = new DeduplicatingContentStore();
    deduplicatingContentStore.setNamespaceService(PREFIX_RESOLVER);
    deduplicatingContentStore.setDictionaryService(dictionaryService);

    final FileContentStore fileContentStore = new FileContentStore();
    fileContentStore.setRootDirectory(backingStoreFolder.getAbsolutePath());
    fileContentStore.setProtocol(STORE_PROTOCOL);
    deduplicatingContentStore.setBackingStore(fileContentStore);

    final FileContentStore temporaryContentStore = new FileContentStore();
    temporaryContentStore.setRootDirectory(temporaryStoreFolder.getAbsolutePath());
    temporaryContentStore.setProtocol(TEMPORARY_STORE_PROTOCOL);
    deduplicatingContentStore.setTemporaryStore(temporaryContentStore);

    fileContentStore.afterPropertiesSet();
    temporaryContentStore.afterPropertiesSet();
    deduplicatingContentStore.afterPropertiesSet();

    final String commonText = generateText(SEED_PRNG.nextLong());
    final String differentText = generateText(SEED_PRNG.nextLong());
    final ContentWriter firstWriter = testIndividualWriteAndRead(deduplicatingContentStore, commonText);

    Assert.assertTrue("Content URL of first writer does not contain expected path segments of 3x 2 bytes and SHA-512 hash",
            firstWriter.getContentUrl()
                    .matches("^" + STORE_PROTOCOL + ContentStore.PROTOCOL_DELIMITER + "([a-fA-F0-9]{4}/){3}[a-fA-F0-9]{128}\\.bin$"));

    final Path rootPath = backingStoreFolder.toPath();
    final long pathCountBeforeSecondWrite = TestUtilities.walk(rootPath, (stream) -> {
        return stream.filter((path) -> {
            return !path.equals(rootPath);
        }).count();
    }, FileVisitOption.FOLLOW_LINKS);

    final ContentWriter secondWriter = testIndividualWriteAndRead(deduplicatingContentStore, commonText);

    Assert.assertEquals("Content URL of second writer does not match previous writer of identical content", firstWriter.getContentUrl(),
            secondWriter.getContentUrl());

    final long pathCountAfterSecondWrite = TestUtilities.walk(rootPath, (stream) -> {
        return stream.filter((path) -> {
            return !path.equals(rootPath);
        }).count();
    }, FileVisitOption.FOLLOW_LINKS);

    Assert.assertEquals("Number of path elements in backing store should not change by writing same content twice",
            pathCountBeforeSecondWrite, pathCountAfterSecondWrite);

    final ContentWriter thirdWriter = testIndividualWriteAndRead(deduplicatingContentStore, differentText);

    Assert.assertNotEquals("Content URL of third writer matches previous writer of non-identical content", firstWriter.getContentUrl(),
            thirdWriter.getContentUrl());
    Assert.assertTrue("Content URL of third writer does not contain expected path segments of 3x 2 bytes and SHA-512 hash",
            thirdWriter.getContentUrl()
                    .matches("^" + STORE_PROTOCOL + ContentStore.PROTOCOL_DELIMITER + "([a-fA-F0-9]{4}/){3}[a-fA-F0-9]{128}\\.bin$"));

    final long pathCountAfterThirdWrite = TestUtilities.walk(rootPath, (stream) -> {
        return stream.filter((path) -> {
            return !path.equals(rootPath);
        }).count();
    }, FileVisitOption.FOLLOW_LINKS);

    Assert.assertNotEquals("Number of path elements in backing store should change by writing different content",
            pathCountBeforeSecondWrite, pathCountAfterThirdWrite);
}