Java Code Examples for io.opentracing.mock.MockSpan#tags()

The following examples show how to use io.opentracing.mock.MockSpan#tags() . 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: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@Test
void shouldTagException() {
    final ResponseEntity<String> response = client
            .getForEntity("http://localhost:8080/exception", String.class);

    assertTrue(response.getStatusCode().is5xxServerError());

    final MockSpan span = span();
    final Map<String, Object> tags = span.tags();

    assertThat(tags, hasEntry("error", true));

    final List<MockSpan.LogEntry> logs = span.logEntries();
    assertThat(logs, hasSize(3));

    assertThat(logs.get(0).fields(), hasEntry(equalTo("message"),
            hasFeature(Objects::toString, containsString("Error"))));
    assertThat(logs.get(1).fields(),
            hasEntry("error.kind", "NestedServletException"));
    assertThat((Throwable) logs.get(1).fields().get("error.object"),
            hasFeature(Throwables::getRootCause,
                    instanceOf(UnsupportedOperationException.class)));
    assertThat(logs.get(2).fields(),
            hasEntry(equalTo("stack"), instanceOf(String.class)));
}
 
Example 2
Source File: DefaultConfigurationTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
private void verify(final Connection connection) throws SQLException {
    try (final Statement statement = connection.createStatement()) {

        statement.execute("SELECT 1");
    } finally {
        connection.close();
    }

    final MockSpan span = getOnlyElement(tracer.finishedSpans());
    final Map<String, Object> tags = span.tags();

    assertThat(span.operationName(), is("execute"));
    assertThat(tags, hasEntry("span.kind", "client"));
    assertThat(tags, hasEntry("component", "JDBC"));
    assertThat(tags, hasEntry("db.statement", "SELECT 1"));
    assertThat(tags, hasEntry("db.type", "sql"));
}
 
Example 3
Source File: OpenTracingSQLExecutionHookTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertExecuteSuccessForTrunkThread() {
    DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class);
    when(dataSourceMetaData.getHostName()).thenReturn("localhost");
    when(dataSourceMetaData.getPort()).thenReturn(8888);
    sqlExecutionHook.start("success_ds", "SELECT * FROM success_tbl;", Arrays.asList("1", 2), dataSourceMetaData, true, null);
    sqlExecutionHook.finishSuccess();
    MockSpan actual = getActualSpan();
    assertThat(actual.operationName(), is("/ShardingSphere/executeSQL/"));
    Map<String, Object> actualTags = actual.tags();
    assertThat(actualTags.get(Tags.COMPONENT.getKey()), is(ShardingTags.COMPONENT_NAME));
    assertThat(actualTags.get(Tags.SPAN_KIND.getKey()), is(Tags.SPAN_KIND_CLIENT));
    assertThat(actualTags.get(Tags.PEER_HOSTNAME.getKey()), is("localhost"));
    assertThat(actualTags.get(Tags.PEER_PORT.getKey()), is(8888));
    assertThat(actualTags.get(Tags.DB_TYPE.getKey()), is("sql"));
    assertThat(actualTags.get(Tags.DB_INSTANCE.getKey()), is("success_ds"));
    assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), is("SELECT * FROM success_tbl;"));
    assertThat(actualTags.get(ShardingTags.DB_BIND_VARIABLES.getKey()), is("[1, 2]"));
    verify(activeSpan, times(0)).deactivate();
    sqlExecutionHook.start("success_ds", "SELECT * FROM success_tbl;", null, dataSourceMetaData, true, null);
    sqlExecutionHook.finishSuccess();
}
 
Example 4
Source File: OpenTracingSQLExecutionHookTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertExecuteSuccessForTrunkThreadWhenParamsIsNull() {
    DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class);
    when(dataSourceMetaData.getHostName()).thenReturn("localhost");
    when(dataSourceMetaData.getPort()).thenReturn(8888);
    sqlExecutionHook.start("success_ds", "SELECT * FROM success_tbl;", null, dataSourceMetaData, true, null);
    sqlExecutionHook.finishSuccess();
    MockSpan actual = getActualSpan();
    assertThat(actual.operationName(), is("/ShardingSphere/executeSQL/"));
    Map<String, Object> actualTags = actual.tags();
    assertThat(actualTags.get(Tags.COMPONENT.getKey()), is(ShardingTags.COMPONENT_NAME));
    assertThat(actualTags.get(Tags.SPAN_KIND.getKey()), is(Tags.SPAN_KIND_CLIENT));
    assertThat(actualTags.get(Tags.PEER_HOSTNAME.getKey()), is("localhost"));
    assertThat(actualTags.get(Tags.PEER_PORT.getKey()), is(8888));
    assertThat(actualTags.get(Tags.DB_TYPE.getKey()), is("sql"));
    assertThat(actualTags.get(Tags.DB_INSTANCE.getKey()), is("success_ds"));
    assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), is("SELECT * FROM success_tbl;"));
    assertThat(actualTags.get(ShardingTags.DB_BIND_VARIABLES.getKey()), is(""));
    verify(activeSpan, times(0)).deactivate();
}
 
Example 5
Source File: OpenTracingSQLExecutionHookTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertExecuteSuccessForBranchThread() {
    DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class);
    when(dataSourceMetaData.getHostName()).thenReturn("localhost");
    when(dataSourceMetaData.getPort()).thenReturn(8888);
    sqlExecutionHook.start("success_ds", "SELECT * FROM success_tbl;", Arrays.asList("1", 2), dataSourceMetaData, false, ExecutorDataMap.getValue());
    sqlExecutionHook.finishSuccess();
    MockSpan actual = getActualSpan();
    assertThat(actual.operationName(), is("/ShardingSphere/executeSQL/"));
    Map<String, Object> actualTags = actual.tags();
    assertThat(actualTags.get(Tags.COMPONENT.getKey()), is(ShardingTags.COMPONENT_NAME));
    assertThat(actualTags.get(Tags.SPAN_KIND.getKey()), is(Tags.SPAN_KIND_CLIENT));
    assertThat(actualTags.get(Tags.PEER_HOSTNAME.getKey()), is("localhost"));
    assertThat(actualTags.get(Tags.PEER_PORT.getKey()), is(8888));
    assertThat(actualTags.get(Tags.DB_TYPE.getKey()), is("sql"));
    assertThat(actualTags.get(Tags.DB_INSTANCE.getKey()), is("success_ds"));
    assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), is("SELECT * FROM success_tbl;"));
    assertThat(actualTags.get(ShardingTags.DB_BIND_VARIABLES.getKey()), is("[1, 2]"));
    verify(activeSpan).deactivate();
}
 
Example 6
Source File: OpenTracingSQLExecutionHookTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertExecuteFailure() {
    DataSourceMetaData dataSourceMetaData = mock(DataSourceMetaData.class);
    when(dataSourceMetaData.getHostName()).thenReturn("localhost");
    when(dataSourceMetaData.getPort()).thenReturn(8888);
    sqlExecutionHook.start("failure_ds", "SELECT * FROM failure_tbl;", Collections.emptyList(), dataSourceMetaData, true, null);
    sqlExecutionHook.finishFailure(new RuntimeException("SQL execution error"));
    MockSpan actual = getActualSpan();
    assertThat(actual.operationName(), is("/ShardingSphere/executeSQL/"));
    Map<String, Object> actualTags = actual.tags();
    assertThat(actualTags.get(Tags.COMPONENT.getKey()), is(ShardingTags.COMPONENT_NAME));
    assertThat(actualTags.get(Tags.SPAN_KIND.getKey()), is(Tags.SPAN_KIND_CLIENT));
    assertThat(actualTags.get(Tags.PEER_HOSTNAME.getKey()), is("localhost"));
    assertThat(actualTags.get(Tags.PEER_PORT.getKey()), is(8888));
    assertThat(actualTags.get(Tags.DB_TYPE.getKey()), is("sql"));
    assertThat(actualTags.get(Tags.DB_INSTANCE.getKey()), is("failure_ds"));
    assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), is("SELECT * FROM failure_tbl;"));
    assertThat(actualTags.get(ShardingTags.DB_BIND_VARIABLES.getKey()), is(""));
    assertSpanError(RuntimeException.class, "SQL execution error");
    verify(activeSpan, times(0)).deactivate();
}
 
Example 7
Source File: PeerSpanDecoratorTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldIgnoreAbsentPort() {
    final MockTracer tracer = new MockTracer();
    final MockSpan span = tracer.buildSpan("test").start();

    final RequestArguments arguments = RequestArguments.create()
            .withBaseUrl(URI.create("http://localhost"))
            .withUriTemplate("/test");

    unit.onRequest(span, arguments);

    final Map<String, Object> tags = span.tags();

    assertThat(tags, hasEntry("peer.hostname", "localhost"));
    assertThat(tags, hasEntry("peer.address", "localhost"));
    assertThat(tags, not(hasKey("peer.port")));
}
 
Example 8
Source File: CustomConfigurationTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@Test
void tracesDataSource() throws SQLException {
    try (final Connection connection = dataSource.getConnection();
         final Statement statement = connection.createStatement()) {

        statement.execute("SELECT 1");
    }

    final MockSpan span = getOnlyElement(tracer.finishedSpans());
    final Map<String, Object> tags = span.tags();

    assertThat(span.operationName(), is("EXECUTE"));
    assertThat(tags, aMapWithSize(2));
    assertThat(tags, hasEntry("span.kind", "client"));
    assertThat(tags, hasEntry("test", "true"));
}
 
Example 9
Source File: RewritableTracerTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void assertTags(final JsonObject expectedSpan, final MockSpan span, final String message) {
  final JsonObject expectedTags = expectedSpan.getObject("tags");
  final Map<String,Object> tags = span.tags();
  if (expectedTags == null) {
    assertEquals(message, 0, tags.size());
    return;
  }

  for (final Map.Entry<String,Object> entry : expectedTags.entrySet()) {
    final String key = entry.getKey();
    assertEquals(message + " tag " + key, entry.getValue(), tags.get(key));
  }

  assertEquals(message, expectedTags.size(), tags.size());
}
 
Example 10
Source File: TagInterceptorTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void interceptsTags() {
    unit.buildSpan("test").start()
            .setTag("test", true)
            .finish();

    final MockSpan span = getOnlyElement(tracer.finishedSpans());
    final Map<String, Object> tags = span.tags();

    assertThat(tags, aMapWithSize(2));
    assertThat(tags, hasEntry("type", "test"));
    assertThat(tags, hasEntry("v", 1));
}
 
Example 11
Source File: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldTagException() {
    final ClientResponse response = client.get()
            .uri("/exception")
            .exchange()
            .block();

    assertTrue(response.statusCode().is5xxServerError());

    final MockSpan span = span();
    final Map<String, Object> tags = span.tags();

    assertThat(tags, hasEntry("http.path", "/exception"));
    assertThat(tags, hasEntry("error", true));

    final List<MockSpan.LogEntry> logs = span.logEntries();
    assertThat(logs, hasSize(3));

    assertThat(logs.get(0).fields(), hasEntry(equalTo("message"),
            hasFeature(Objects::toString, containsString("Error"))));
    assertThat(logs.get(1).fields(),
            hasEntry("error.kind", "UnsupportedOperationException"));
    assertThat(logs.get(1).fields().get("error.object"),
            instanceOf(UnsupportedOperationException.class));
    assertThat(logs.get(2).fields(),
            hasEntry(equalTo("stack"), instanceOf(String.class)));
}
 
Example 12
Source File: CustomDataSourceTracerTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void tracesDataSource() throws SQLException {
    try (final Connection connection = dataSource.getConnection();
         final Statement statement = connection.createStatement()) {

        statement.execute("SELECT 1");
    }

    final MockSpan span = getOnlyElement(tracer.finishedSpans());
    final Map<String, Object> tags = span.tags();

    assertThat(tags, aMapWithSize(2));
    assertThat(tags, hasEntry("span.kind", "client"));
    assertThat(tags, hasEntry("component", "JDBC"));
}
 
Example 13
Source File: OpenTracingParsingHookTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertExecuteFailure() {
    registry.start("SELECT * FROM XXX;");
    registry.finishFailure(new ShardingSphereException("parse SQL error"));
    MockSpan actual = getActualSpan();
    assertThat(actual.operationName(), is("/ShardingSphere/parseSQL/"));
    Map<String, Object> actualTags = actual.tags();
    assertThat(actualTags.get(Tags.COMPONENT.getKey()), is(ShardingTags.COMPONENT_NAME));
    assertThat(actualTags.get(Tags.SPAN_KIND.getKey()), is(Tags.SPAN_KIND_CLIENT));
    assertThat(actualTags.get(Tags.DB_STATEMENT.getKey()), is("SELECT * FROM XXX;"));
    assertSpanError(ShardingSphereException.class, "parse SQL error");
}
 
Example 14
Source File: MetricsTest.java    From java-metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTags() {
    MetricsReporter reporter = Mockito.mock(MetricsReporter.class);
    MockTracer tracer = new MockTracer();
    Tracer metricsTracer = Metrics.decorate(tracer, reporter);

    Scope parent = metricsTracer.buildSpan("parent")
            .withTag("booleanTag", true)
            .withTag("numericTag", new Integer(100))
            .startActive(true);

    parent.close();

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(1, spans.size());
    MockSpan span = spans.get(0);
    Map<String, Object> tags = span.tags();

    Object booleanTag = tags.get("booleanTag");
    assertNotNull("Expected a tag named 'booleanTag'", booleanTag);
    assertTrue("booleanTag should be a Boolean", booleanTag instanceof Boolean);
    assertEquals("booleanTag should be true", true, booleanTag);

    Object numericTag = tags.get("numericTag");
    assertNotNull("Expected a tag named 'numericTag'", numericTag);
    assertTrue("numericTag should be a Number", numericTag instanceof Number);
    assertEquals("numericTag should be 100", 100, numericTag);
}
 
Example 15
Source File: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 4 votes vote down vote up
private Map<String, Object> tags() {
    final MockSpan span = span();
    return span.tags();
}
 
Example 16
Source File: OpenTracingIntegrationTest.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 20000)
public void testSend() throws Exception {
    try (TestAmqpPeer testPeer = new TestAmqpPeer();) {
        JmsConnectionFactory factory = new JmsConnectionFactory(createPeerURI(testPeer));

        MockTracer mockTracer = new MockTracer();
        JmsTracer tracer = OpenTracingTracerFactory.create(mockTracer);
        factory.setTracer(tracer);

        testPeer.expectSaslAnonymous();
        testPeer.expectOpen();
        testPeer.expectBegin();

        Connection connection = factory.createConnection();
        connection.start();

        testPeer.expectBegin();

        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        String queueName = "myQueue";
        Queue queue = session.createQueue(queueName);

        testPeer.expectSenderAttach();

        MessageProducer producer = session.createProducer(queue);

        // Expect a message with the trace info annotation set
        String msgContent = "myTracedMessageContent";
        TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher();
        messageMatcher.setHeadersMatcher(new MessageHeaderSectionMatcher(true));
        MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true);
        msgAnnotationsMatcher.withEntry(Symbol.valueOf(ANNOTATION_KEY), Matchers.any(Map.class));
        messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher);
        messageMatcher.setPropertiesMatcher(new MessagePropertiesSectionMatcher(true));
        messageMatcher.setMessageContentMatcher(new EncodedAmqpValueMatcher(msgContent));

        testPeer.expectTransfer(messageMatcher);

        TextMessage message = session.createTextMessage(msgContent);
        producer.send(message);

        testPeer.waitForAllHandlersToComplete(2000);

        List<MockSpan> finishedSpans = mockTracer.finishedSpans();
        assertEquals("Expected 1 finished span: " + finishedSpans, 1, finishedSpans.size());
        Span sendSpan = finishedSpans.get(0);
        assertEquals("Unexpected span class", MockSpan.class, sendSpan.getClass());
        MockSpan sendMockSpan = (MockSpan) sendSpan;

        assertEquals("Expected span to have no parent", 0, sendMockSpan.parentId());
        assertEquals("Unexpected span operation name", SEND_SPAN_NAME, sendMockSpan.operationName());

        // Verify tags set on the completed span
        Map<String, Object> spanTags = sendMockSpan.tags();
        assertFalse("Expected some tags", spanTags.isEmpty());
        assertFalse("Expected error tag not to be set", spanTags.containsKey(Tags.ERROR.getKey()));
        assertEquals(Tags.SPAN_KIND_PRODUCER, spanTags.get(Tags.SPAN_KIND.getKey()));
        assertEquals(queueName, spanTags.get(Tags.MESSAGE_BUS_DESTINATION.getKey()));
        assertEquals(COMPONENT, spanTags.get(Tags.COMPONENT.getKey()));

        // Verify log set on the completed span
        List<LogEntry> entries = sendMockSpan.logEntries();
        assertEquals("Expected 1 log entry: " + entries, 1, entries.size());

        Map<String, ?> entryFields = entries.get(0).fields();
        assertFalse("Expected some log entry fields", entryFields.isEmpty());
        assertNotNull("Expected a state description", entryFields.get(STATE));
        assertEquals(DELIVERY_SETTLED, entryFields.get(Fields.EVENT));

        // Verify the context sent on the wire matches the original span
        Object obj = msgAnnotationsMatcher.getReceivedAnnotation(Symbol.valueOf(ANNOTATION_KEY));
        assertTrue("annotation was not a map", obj instanceof Map);
        @SuppressWarnings("unchecked")
        Map<String, String> traceInfo = (Map<String, String>) obj;
        assertFalse("Expected some content in map", traceInfo.isEmpty());

        SpanContext extractedContext = mockTracer.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(traceInfo));
        assertEquals("Unexpected context class", MockContext.class, extractedContext.getClass());
        assertEquals("Extracted context spanId did not match original", sendMockSpan.context().spanId(), ((MockContext) extractedContext).spanId());

        testPeer.expectClose();
        connection.close();

        testPeer.waitForAllHandlersToComplete(2000);
    }
}
 
Example 17
Source File: StandardSpanDecoratorTest.java    From opentracing-toolbox with MIT License 4 votes vote down vote up
private Map<String, Object> tags() {
    final MockSpan span = span();
    return span.tags();
}
 
Example 18
Source File: OpenTracingWebExtensionAutoConfigurationTest.java    From opentracing-toolbox with MIT License 4 votes vote down vote up
private Map<String, Object> tags() {
    final MockSpan span = span();
    return span.tags();
}
 
Example 19
Source File: OpenTracingWebFluxExtensionAutoConfigurationTest.java    From opentracing-toolbox with MIT License 4 votes vote down vote up
private Map<String, Object> tags() {
    final MockSpan span = span();
    return span.tags();
}
 
Example 20
Source File: OpenTracingServletExtensionAutoConfigurationTest.java    From opentracing-toolbox with MIT License 4 votes vote down vote up
private Map<String, Object> tags() {
    final MockSpan span = span();
    return span.tags();
}