org.hamcrest.core.IsEqual Java Examples

The following examples show how to use org.hamcrest.core.IsEqual. 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: MatrixElementTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void equalsOnlyReturnsTrueForEquivalentObjects() {
    // Arrange:
    final MatrixElement element = new MatrixElement(5, 4, 7.0);

    // Assert:
    MatcherAssert.assertThat(DESC_TO_ELEMENT_MAP.get("default"), IsEqual.equalTo(element));
    MatcherAssert
        .assertThat(DESC_TO_ELEMENT_MAP.get("diff-row"), IsNot.not(IsEqual.equalTo(element)));
    MatcherAssert
        .assertThat(DESC_TO_ELEMENT_MAP.get("diff-col"), IsNot.not(IsEqual.equalTo(element)));
    MatcherAssert
        .assertThat(DESC_TO_ELEMENT_MAP.get("diff-val"), IsNot.not(IsEqual.equalTo(element)));
    MatcherAssert.assertThat(null, IsNot.not(IsEqual.equalTo(element)));
    MatcherAssert.assertThat(5, IsNot.not(IsEqual.equalTo(element)));
}
 
Example #2
Source File: SessionTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Test
@SpecificationTest(section = "9.session.detach",
        description = "Detaches the current transport from the named session.")
public void detach() throws Exception
{
    try (FrameTransport transport = new FrameTransport(getBrokerAdmin()).connect())
    {
        final Interaction interaction = transport.newInteraction();
        byte[] sessionName = "test".getBytes(StandardCharsets.UTF_8);
        final int channelId = 1;
        SessionDetached sessionDetached = interaction.negotiateOpen()
                                                     .channelId(channelId)
                                                     .session()
                                                     .attachName(sessionName)
                                                     .attach()
                                                     .consumeResponse(SessionAttached.class)
                                                     .session()
                                                     .detachName(sessionName)
                                                     .detach()
                                                     .consumeResponse()
                                                     .getLatestResponse(SessionDetached.class);

        assertThat(sessionDetached.getName(), IsEqual.equalTo(sessionName));
        assertThat(sessionDetached.getChannel(), IsEqual.equalTo(channelId));
    }
}
 
Example #3
Source File: SleepFutureTest.java    From nem.core with MIT License 6 votes vote down vote up
@Test
public void sleepFuturesOfDifferentDurationsAreExecutedConcurrently() throws InterruptedException {
	// Arrange:
	final CompletableFuture future1 = SleepFuture.create(TIME_UNIT);
	final CompletableFuture future5 = SleepFuture.create(TIME_UNIT * 5);

	Thread.sleep(TIME_UNIT + DELTA);

	// Assert:
	Assert.assertThat(future1.isDone(), IsEqual.equalTo(true));
	Assert.assertThat(future5.isDone(), IsEqual.equalTo(false));

	Thread.sleep(TIME_UNIT * 4);

	Assert.assertThat(future1.isDone(), IsEqual.equalTo(true));
	Assert.assertThat(future5.isDone(), IsEqual.equalTo(true));
}
 
Example #4
Source File: TaskTest.java    From ews-java-api with MIT License 6 votes vote down vote up
/**
 * Test for checking if the value changes in case of a thrown exception
 *
 * @throws Exception
 */
@Test
public void testDontChangeValueOnException() throws Exception {
  // set valid value
  final Double targetValue = 50.5;
  taskMock.setPercentComplete(targetValue);

  assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue()));
  assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class));
  assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue));

  final Double invalidValue = -0.1;
  try {
    taskMock.setPercentComplete(invalidValue);
  } catch (IllegalArgumentException ex) {
    // ignored
  }

  assertThat(taskMock.getPercentComplete(), IsNot.not(IsNull.nullValue()));
  assertThat(taskMock.getPercentComplete(), IsInstanceOf.instanceOf(Double.class));
  assertThat(taskMock.getPercentComplete(), IsEqual.equalTo(targetValue));
}
 
Example #5
Source File: AbstractBaseITests.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testView() {
    {
        getRestTemplate().getForEntity("/view", String.class);
        Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1));
    }
    List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());
    assertOnErrors(mockSpans);

    MockSpan span = mockSpans.get(0);
    Assert.assertEquals("view", span.operationName());

    Assert.assertEquals(5, span.tags().size());
    Assert.assertEquals(Tags.SPAN_KIND_SERVER, span.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("GET", span.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(getUrl("/view"), span.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(200, span.tags().get(Tags.HTTP_STATUS.getKey()));
    Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey()));

    assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion"));
}
 
Example #6
Source File: SlicedTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("PMD.AvoidDuplicateLiterals")
public void sliceIterable() throws Exception {
    new Assertion<>(
        "Must get sliced iterable of elements",
        new Sliced<>(
            1,
            2,
            "one", "two", "three", "four"
        ),
        new IsEqual<>(
            new IterableOf<>(
                "two", "three"
            )
        )
    ).affirm();
}
 
Example #7
Source File: Ed25519GroupElementTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void subReturnsExpectedResult() {
    for (int i = 0; i < 1000; i++) {
        // Arrange:
        final Ed25519GroupElement g1 = MathUtils.getRandomGroupElement();
        final Ed25519GroupElement g2 = MathUtils.getRandomGroupElement();

        // Act:
        final Ed25519GroupElement h1 = g1.subtract(g2.toCached());
        final Ed25519GroupElement h2 =
            MathUtils.addGroupElements(g1, MathUtils.negateGroupElement(g2));

        // Assert:
        MatcherAssert.assertThat(h2, IsEqual.equalTo(h1));
    }
}
 
Example #8
Source File: NemesisBlockInfoTest.java    From nem.core with MIT License 6 votes vote down vote up
@Test
public void canCreateNemesisBlock() {
	// Arrange:
	final Hash generationHash = Utils.generateRandomHash();
	final Address address = Utils.generateRandomAddress();

	// Act:
	final NemesisBlockInfo info = new NemesisBlockInfo(
			generationHash,
			address,
			Amount.fromNem(44221122),
			"awesome-nemesis.bin");

	// Assert:
	Assert.assertThat(info.getGenerationHash(), IsEqual.equalTo(generationHash));
	Assert.assertThat(info.getAddress(), IsEqual.equalTo(address));
	Assert.assertThat(info.getAmount(), IsEqual.equalTo(Amount.fromNem(44221122)));
	Assert.assertThat(info.getDataFileName(), IsEqual.equalTo("awesome-nemesis.bin"));
}
 
Example #9
Source File: UpdatePermissionsV2EndToEndTest.java    From credhub with Apache License 2.0 6 votes vote down vote up
@Test
public void PUT_whenUUIDIsInvalid_ReturnStatusNotFound() throws Exception {
  final String credUUID = "not-a-uuid";

  final MockHttpServletRequestBuilder putPermissionRequest = put("/api/v2/permissions/" + credUUID)
    .header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN)
    .accept(APPLICATION_JSON)
    .contentType(APPLICATION_JSON)
    .content("{"
      + "  \"actor\": \"" + USER_A_ACTOR_ID + "\",\n"
      + "  \"path\": \"" + "badCredentialName" + "\",\n"
      + "  \"operations\": [\"" + "write" + "\"]\n"
      + "}");

  final String responseJson = mockMvc.perform(putPermissionRequest).andExpect(status().isNotFound()).andReturn().getResponse().getContentAsString();
  final String errorMessage = new JSONObject(responseJson).getString("error");

  assertThat(errorMessage, is(IsEqual.equalTo("The request includes a permission that does not exist.")));
}
 
Example #10
Source File: PsAllTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * PsAll with multiple passes that all can be entered returns the
 * identity specified by an index.
 * @throws Exception If fails
 */
@Test
public void testSuccessfullIdx() throws Exception {
    final Pass resulting = new PsFixed(
        new Identity.Simple("urn:foo:test")
    );
    final RqFake request = new RqFake();
    MatcherAssert.assertThat(
        new PsAll(
            Arrays.asList(
                new PsFake(true),
                new PsFake(true),
                new PsFake(true),
                resulting
            ),
            Tv.THREE
        ).enter(request).get().urn(),
        new IsEqual<>(resulting.enter(request).get().urn())
    );
}
 
Example #11
Source File: RqSocketTest.java    From takes with MIT License 6 votes vote down vote up
@Test
public void hashCodeMustEqualToSameTypeRequest() throws Exception {
    final Request request = new RqWithHeader(
        new RqFake(), "X-Takes-LocalPort: 55555"
    );
    new Assertion<>(
        "RqSocket must equal to other RqSocket",
        new RqSocket(
            request
        ).hashCode(),
        new IsEqual<>(
            new RqSocket(
                request
            ).hashCode()
        )
    ).affirm();
}
 
Example #12
Source File: FeignTracingTest.java    From feign-opentracing with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentSpanFromSpanManager() throws InterruptedException {
    {
        Span span = mockTracer.buildSpan("parent")
                .start();

        mockWebServer.enqueue(new MockResponse()
                .setResponseCode(200));

        try (Scope scope = mockTracer.activateSpan(span)) {
            StringEntityRequest
                entity = feign.<StringEntityRequest>newInstance(
                new Target.HardCodedTarget(StringEntityRequest.class,
                    mockWebServer.url("/foo").toString()));
            entity.get();
        } finally {
            span.finish();
        }
    }
    Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2));

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(2, mockSpans.size());
    Assert.assertEquals(mockSpans.get(1).context().traceId(), mockSpans.get(0).context().traceId());
    Assert.assertEquals(mockSpans.get(1).context().spanId(), mockSpans.get(0).parentId());
}
 
Example #13
Source File: HeadInputStreamTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
public void testSkippingLessThanTotal() throws Exception {
    final HeadInputStream stream = new HeadInputStream(
        new InputOf("testSkippingLessThanTotal").stream(),
        5
    );
    final long skipped = stream.skip(3L);
    new Assertion<>(
        "Incorrect number of bytes skipped",
        skipped,
        new IsEqual<>(3L)
    ).affirm();
    new Assertion<>(
        "Incorrect head of the input stream has been read",
        new InputOf(stream),
        new InputHasContent("tS")
    ).affirm();
}
 
Example #14
Source File: AmbTest.java    From cyclops with Apache License 2.0 6 votes vote down vote up
@Test
public void race(){
    AtomicReference<Vector<Integer>> data = new AtomicReference(Vector.empty());
    AtomicBoolean complete = new AtomicBoolean(false);
    AtomicReference<Throwable> error = new AtomicReference<Throwable>(null);

    Spouts.amb(Spouts.range(1, 10), Spouts.range(11, 20)).forEach(z->{
        assertFalse(complete.get());
        data.updateAndGet(s->s.plus(z));
    },e->{
        error.set(e);
    },()->{
        complete.set(true);
    });

    assertThat("Values " +  data,data.get(), hasItems(11, 12, 13, 14, 15, 16, 17, 18, 19));
    Assert.assertThat(complete.get(), IsEqual.equalTo(true));
    assertNull(error.get());
}
 
Example #15
Source File: HeadersOfTest.java    From verano-http with MIT License 6 votes vote down vote up
@Test
public void extractHeaderMapFromDict() {
    final Map<String, List<String>> headers = new Headers.Of(
        new HashDict(
            new KvpOf("test", "test"),
            new KvpOf("h.name", "john"),
            new KvpOf("h.name", "mark"),
            new KvpOf("h.surname", "doe")
        )
    ).asMap();
    MatcherAssert.assertThat(
        headers.size(),
        new IsEqual<>(2)
    );
    MatcherAssert.assertThat(
        headers.get("name"),
        Matchers.contains("john", "mark")
    );
    MatcherAssert.assertThat(
        headers.get("surname"),
        Matchers.contains("doe")
    );
}
 
Example #16
Source File: BlockCipherTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
void dataCanBeDecryptedWithSenderPrivateKeyAndRecipientPublicKey() {
    // Arrange:
    final CryptoEngine engine = this.getCryptoEngine();
    final KeyPair skp = KeyPair.random(engine);
    final KeyPair rkp = KeyPair.random(engine);
    final BlockCipher blockCipher1 =
        this.getBlockCipher(skp, KeyPair.onlyPublic(rkp.getPublicKey(), engine));
    final BlockCipher blockCipher2 =
        this.getBlockCipher(KeyPair.onlyPublic(rkp.getPublicKey(), engine), skp);
    final byte[] input = "Some text".getBytes();

    // Act:
    final byte[] encryptedBytes = blockCipher1.encrypt(input);
    final byte[] decryptedBytes = blockCipher2.decrypt(encryptedBytes);

    // Assert:
    MatcherAssert.assertThat(ConvertUtils.toHex(decryptedBytes),
        IsEqual.equalTo(ConvertUtils.toHex(input)));
}
 
Example #17
Source File: Ed25519EncodedFieldElementTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void isNegativeReturnsCorrectResult() {
    for (int i = 0; i < 10000; i++) {
        // Arrange:
        final byte[] values = RandomUtils.generateRandomBytes(32);
        values[31] &= 0x7F;
        final Ed25519EncodedFieldElement encoded = new Ed25519EncodedFieldElement(values);
        final boolean isNegative =
            MathUtils.toBigInteger(encoded)
                .mod(Ed25519Field.P)
                .mod(new BigInteger("2"))
                .equals(BigInteger.ONE);

        // Assert:
        MatcherAssert.assertThat(encoded.isNegative(), IsEqual.equalTo(isNegative));
    }
}
 
Example #18
Source File: HashesTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testLeading00Hashes() {
    final String hex = "00137c7c32881d1fff2e905f5b7034bcbcdb806d232f351db48a7816285c548f";
    final PrivateKey privateKey = PrivateKey.fromHexString(hex);
    MatcherAssert.assertThat(ConvertUtils.toHex(privateKey.getBytes()),
        IsEqual.equalTo("00137C7C32881D1FFF2E905F5B7034BCBCDB806D232F351DB48A7816285C548F"));
    final byte[] hash = Hashes.sha512(privateKey.getBytes());

    MatcherAssert.assertThat(ConvertUtils.toHex(hash),
        IsEqual.equalTo("47C755C29EC3494D59A4A7ECC497302271D46F2F69E1697AC15FA8C2B480CBC2FF6517F780C51B59E7E79AAF74C9CE04E65FCFDC62A157956AE0DC23C105E6B7"));

    final byte[] d = Arrays.copyOfRange(hash, 0, 32);
    String actual = ConvertUtils.toHex(d);
    String expected = "47C755C29EC3494D59A4A7ECC497302271D46F2F69E1697AC15FA8C2B480CBC2";
    MatcherAssert.assertThat(actual, IsEqual.equalTo(expected));
}
 
Example #19
Source File: MapEnvelopeTest.java    From cactoos with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void mapEnvelopeShouldCompareDerivedClasses() {
    final int key = 1;
    final String value = "one";
    final MapEntry<Integer, String> entry = new MapEntry<>(key, value);
    final MapEnvelope<Integer, String> base = new MapOf<>(entry);
    final Map<Integer, String> hashmap = new HashMap<>();
    hashmap.put(key, value);
    final DerivedMapEnvelope<Integer, String> derived =
        new DerivedMapEnvelope<>(hashmap);
    new Assertion<>(
        "Base and derived MapEnvelope of same content should be equal.",
        base,
        new IsEqual<>(derived)
    ).affirm();
}
 
Example #20
Source File: DeleteTest.java    From verano-http with MIT License 6 votes vote down vote up
@Test
public void buildsDeleteRequestWithEmptyPath() {
    final Dict dict = new Delete(new ContentType("text/html"));
    MatcherAssert.assertThat(
        new CollectionOf<>(dict).size(),
        new IsEqual<>(3)
    );
    MatcherAssert.assertThat(
        dict.get("method"),
        new IsEqual<>("DELETE")
    );
    MatcherAssert.assertThat(
        dict.get("path").isEmpty(),
        new IsEqual<>(true)
    );
    MatcherAssert.assertThat(
        dict.get("h.Content-Type"),
        new IsEqual<>("text/html")
    );
}
 
Example #21
Source File: DeleteTest.java    From verano-http with MIT License 6 votes vote down vote up
@Test
public void buildsDeleteRequestWithoutParameters() {
    final Dict dict = new Delete("/items");
    MatcherAssert.assertThat(
        new CollectionOf<>(dict).size(),
        new IsEqual<>(2)
    );
    MatcherAssert.assertThat(
        dict.get("method"),
        new IsEqual<>("DELETE")
    );
    MatcherAssert.assertThat(
        dict.get("path"),
        new IsEqual<>("/items")
    );
}
 
Example #22
Source File: BlockCipherTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
void dataCanBeEncryptedWithSenderPrivateKeyAndRecipientPublicKey() {
    // Arrange:
    final CryptoEngine engine = this.getCryptoEngine();
    final KeyPair skp = KeyPair.random(engine);
    final KeyPair rkp = KeyPair.random(engine);
    final BlockCipher blockCipher =
        this.getBlockCipher(skp, KeyPair.onlyPublic(rkp.getPublicKey(), engine));
    final byte[] input = RandomUtils.generateRandomBytes();

    // Act:
    final byte[] encryptedBytes = blockCipher.encrypt(input);

    // Assert:
    MatcherAssert.assertThat(encryptedBytes, IsNot.not(IsEqual.equalTo(input)));
}
 
Example #23
Source File: DeserializableEntityMessageConverterTest.java    From nem.deploy with MIT License 6 votes vote down vote up
@Test
public void canReadCompatibleTypesWithDeserializerConstructor() {
	// Arrange:
	final MediaType supportedType = new MediaType("application", "json");
	final DeserializableEntityMessageConverter mc = createMessageConverter();

	final Class[] types = new Class[] {
			MockSerializableEntity.class,
			ObjectWithConstructorThatThrowsCheckedException.class,
			ObjectWithConstructorThatThrowsUncheckedException.class
	};

	// Assert:
	for (final Class type : types) {
		Assert.assertThat(mc.canRead(type, supportedType), IsEqual.equalTo(true));
	}
}
 
Example #24
Source File: BoundedByteBufferTest.java    From cactoos-http with MIT License 5 votes vote down vote up
@Test
public void worksWithSmallerArray() {
    final int limit = 4;
    final BoundedByteBuffer buffer = new BoundedByteBuffer(limit);
    final int[] bytes = {1, 2};
    Arrays.stream(bytes).forEach(b -> buffer.offer((byte) b));
    MatcherAssert.assertThat(
        buffer.equalTo(new byte[] {1, 2}),
        new IsEqual<>(true)
    );
}
 
Example #25
Source File: NamedObserverTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void defaultGetNameReturnsTypeName() {
	// Arrange:
	final NamedObserver observer = new CrazyNameObserver();

	// Act:
	final String name = observer.getName();

	// Assert:
	Assert.assertThat(name, IsEqual.equalTo("CrazyNameObserver"));
}
 
Example #26
Source File: ReflectiveElevatedClassLoaderFactoryTest.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testLoadClassInvalidApiClassloader()
        throws ClassNotFoundException, IllegalAccessException, InstantiationException, MalformedURLException {
    ClassloaderBuilder builder = new ClassloaderBuilder();
    builder.newClassloader("_customPlugin");
    builder.setParent("_customPlugin", new URLClassLoader(new URL[0]), new Mask());
    builder.setLoadingOrder("_customPlugin", ClassloaderBuilder.LoadingOrder.SELF_FIRST);

    File[] sonarQubeDistributions = new File("sonarqube-lib/").listFiles();

    for (File pluginJar : new File(sonarQubeDistributions[0], "extensions/plugins/").listFiles()) {
        builder.addURL("_customPlugin", pluginJar.toURI().toURL());
    }

    Map<String, ClassLoader> loaders = builder.build();
    ClassLoader classLoader = loaders.get("_customPlugin");

    Class<? extends Plugins> loadedClass =
            (Class<? extends Plugins>) classLoader.loadClass("org.sonar.plugins.scm.svn.SvnPlugin");

    expectedException.expect(IllegalStateException.class);
    expectedException.expectMessage(IsEqual.equalTo(
            "Expected classloader of type 'org.sonar.classloader.ClassRealm' but got 'java.net.URLClassLoader'"));

    ReflectiveElevatedClassLoaderFactory testCase = new ReflectiveElevatedClassLoaderFactory();
    testCase.createClassLoader((Class<? extends Plugin>) loadedClass);

}
 
Example #27
Source File: BlockChainConfigurationTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void getEstimatedBlocksPerYearReturnsNumberOfBlocksPerYear() {
	// Arrange:
	final BlockChainConfiguration configuration = createConfiguration();

	// Assert:
	Assert.assertThat(configuration.getEstimatedBlocksPerYear(), IsEqual.equalTo(1920 * 365));
}
 
Example #28
Source File: FreemarkerClientPartialsNToManyPropertyTest.java    From angularjs-addon with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testGenerateHiddenProperty() throws Exception
{
   Map<String, Object> root = createInspectionResultWrapper(ENTITY_NAME, ENTITY_VERSION_PROP);

   Resource<URL> templateResource = resourceFactory.create(getClass().getResource(
            Deployments.BASE_PACKAGE_PATH + Deployments.N_TO_MANY_PROPERTY_DETAIL_INCLUDE));
   Template processor = processorFactory.create(templateResource, FreemarkerTemplate.class);
   String output = processor.process(root);
   assertThat(output.trim(), IsEqual.equalTo(""));
}
 
Example #29
Source File: Ed25519GroupTest.java    From nem.core with MIT License 5 votes vote down vote up
@Test
public void zeroP2IsAsExpected() {
	// Arrange:
	final Ed25519GroupElement zeroP2 = Ed25519GroupElement.p2(Ed25519Field.ZERO, Ed25519Field.ONE, Ed25519Field.ONE);

	// Assert:
	Assert.assertThat(zeroP2, IsEqual.equalTo(Ed25519Group.ZERO_P2));
}
 
Example #30
Source File: IteratorOfBooleansTest.java    From cactoos with MIT License 5 votes vote down vote up
@Test
public void emptyIteratorDoesNotHaveNext() {
    MatcherAssert.assertThat(
        "hasNext is true for empty iterator",
        new IteratorOfBooleans().hasNext(),
        new IsEqual<>(false)
    );
}