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 Project: ews-java-api   Author: OfficeDev   File: TaskTest.java    License: 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 #2
Source Project: java-spring-web   Author: opentracing-contrib   File: AbstractBaseITests.java    License: 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 #3
Source Project: qpid-broker-j   Author: apache   File: SessionTest.java    License: 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 #4
Source Project: nem.core   Author: NemProject   File: SleepFutureTest.java    License: 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 #5
Source Project: cactoos   Author: yegor256   File: SlicedTest.java    License: 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 #6
Source Project: symbol-sdk-java   Author: nemtech   File: Ed25519GroupElementTest.java    License: 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 #7
Source Project: nem.core   Author: NemProject   File: NemesisBlockInfoTest.java    License: 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 #8
Source Project: credhub   Author: cloudfoundry-incubator   File: UpdatePermissionsV2EndToEndTest.java    License: 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 #9
Source Project: takes   Author: yegor256   File: PsAllTest.java    License: 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 #10
Source Project: takes   Author: yegor256   File: RqSocketTest.java    License: 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 #11
Source Project: feign-opentracing   Author: OpenFeign   File: FeignTracingTest.java    License: 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 #12
Source Project: nem.deploy   Author: NemProject   File: DeserializableEntityMessageConverterTest.java    License: 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 #13
Source Project: cactoos   Author: yegor256   File: HeadInputStreamTest.java    License: 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 Project: cyclops   Author: aol   File: AmbTest.java    License: 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 Project: symbol-sdk-java   Author: nemtech   File: BlockCipherTest.java    License: 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 #16
Source Project: verano-http   Author: Vatavuk   File: DeleteTest.java    License: 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 #17
Source Project: verano-http   Author: Vatavuk   File: DeleteTest.java    License: 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 #18
Source Project: cactoos   Author: yegor256   File: MapEnvelopeTest.java    License: 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 #19
Source Project: symbol-sdk-java   Author: nemtech   File: HashesTest.java    License: 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 #20
Source Project: symbol-sdk-java   Author: nemtech   File: Ed25519EncodedFieldElementTest.java    License: 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 #21
Source Project: symbol-sdk-java   Author: nemtech   File: BlockCipherTest.java    License: 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 #22
Source Project: verano-http   Author: Vatavuk   File: HeadersOfTest.java    License: 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 #23
Source Project: symbol-sdk-java   Author: nemtech   File: MatrixElementTest.java    License: 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 #24
Source Project: symbol-sdk-java   Author: nemtech   File: ColumnVectorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void scalarCanBeAddedToVector() {
    // Arrange:
    final ColumnVector a = new ColumnVector(2, -4, 1);

    // Act:
    final ColumnVector result = a.add(8);

    // Assert:
    MatcherAssert.assertThat(result, IsNot.not(IsEqual.equalTo(a)));
    MatcherAssert.assertThat(result, IsEqual.equalTo(new ColumnVector(10, 4, 9)));
}
 
Example #25
Source Project: cactoos   Author: yegor256   File: SumOfTest.java    License: MIT License 5 votes vote down vote up
@Test
public void withIterableOfInts() {
    final Collection<Integer> ints = new ListOf<>(1, 2, 3, 4);
    MatcherAssert.assertThat(
        new SumOf(ints).intValue(),
        new IsEqual<>(10)
    );
}
 
Example #26
Source Project: hbase   Author: apache   File: TestSecurityHeadersFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testHstsAndCspSettings() throws IOException {
  Configuration conf = new Configuration();
  conf.set("hbase.http.filter.hsts.value",
      "max-age=63072000;includeSubDomains;preload");
  conf.set("hbase.http.filter.csp.value",
      "default-src https: data: 'unsafe-inline' 'unsafe-eval'");
  http = createTestServer(conf);
  http.start();
  baseUrl = getServerURL(http);

  URL url = new URL(baseUrl, "/");
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  assertThat(conn.getResponseCode(), equalTo(HttpURLConnection.HTTP_OK));

  assertThat("Header 'Strict-Transport-Security' is missing from Rest response",
      conn.getHeaderField("Strict-Transport-Security"), Is.is(not((String)null)));
  assertThat("Header 'Strict-Transport-Security' has invalid value",
      conn.getHeaderField("Strict-Transport-Security"),
      IsEqual.equalTo("max-age=63072000;includeSubDomains;preload"));

  assertThat("Header 'Content-Security-Policy' is missing from Rest response",
      conn.getHeaderField("Content-Security-Policy"), Is.is(not((String)null)));
  assertThat("Header 'Content-Security-Policy' has invalid value",
      conn.getHeaderField("Content-Security-Policy"),
      IsEqual.equalTo("default-src https: data: 'unsafe-inline' 'unsafe-eval'"));
}
 
Example #27
Source Project: pnc   Author: project-ncl   File: RestResponseFormattingTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnErrorInJsonFormat() {
    String response = given().header("Accept", "application/json")
            .contentType(ContentType.JSON)
            .port(getHttpPort())
            .expect()
            .statusCode(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
            .body("errorMessage", IsEqual.equalTo("Test exception."))
            .when()
            .get(BASE_PATH + "/debug/throw")
            .asString();
    logger.info(response);
}
 
Example #28
@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 Project: java-spring-web   Author: opentracing-contrib   File: AbstractBaseITests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
    public void testControllerException() throws Exception {
        {
            getRestTemplate().getForEntity("/exception", String.class);
            Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2));
        }
        List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans();
        Assert.assertEquals(2, mockSpans.size());
        assertOnErrors(mockSpans);

        MockSpan span = mockSpans.get(0);
        Assert.assertEquals("exception", span.operationName());
        Assert.assertEquals(6, 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("/exception"), span.tags().get(Tags.HTTP_URL.getKey()));
        Assert.assertEquals(500, span.tags().get(Tags.HTTP_STATUS.getKey()));
        Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey()));
        Assert.assertEquals(Boolean.TRUE, span.tags().get(Tags.ERROR.getKey()));

        assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion", "error"));
//        error log
        Assert.assertEquals(3, span.logEntries().get(2).fields().size());
        Assert.assertEquals(Tags.ERROR.getKey(), span.logEntries().get(2).fields().get("event"));
        Assert.assertEquals(TestController.EXCEPTION_MESSAGE,
                span.logEntries().get(2).fields().get("message"));
        Assert.assertNotNull(span.logEntries().get(2).fields().get("stack"));

        span = mockSpans.get(1);
        Assert.assertEquals(0, span.tags().size());
        Assert.assertEquals(mockSpans.get(0).context().spanId(), span.parentId());
        Assert.assertEquals(0, span.tags().size());
        assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion"));
        Assert.assertEquals("BasicErrorController",
                span.logEntries().get(0).fields().get("handler.class_simple_name"));
    }
 
Example #30
Source Project: cactoos   Author: yegor256   File: MapEnvelopeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void equalsDoesNotFailOnNulls() {
    final MapEntry<String, String> first =
        new MapEntry<>("key3", "value3");
    final MapEntry<String, String> second =
        new MapEntry<>("key4", null);
    MatcherAssert.assertThat(
        "Map must allow null values",
        new MapOf<String, String>(first, second),
        new IsEqual<>(new MapOf<String, String>(first, second))
    );
}