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

The following examples show how to use io.opentracing.mock.MockSpan#finish() . 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: TracingRedissonTest.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = tracer.buildSpan("test").start();
  try (Scope ignore = tracer.activateSpan(parent)) {
    Span activeSpan = tracer.activeSpan();

    RMap<String, String> map = client.getMap("map_async_continue_span");

    assertFalse(map.containsKeyAsync("key").toCompletableFuture().thenApply(s -> {
      System.out.println(
          "active span: " + tracer.activeSpan() + " in thread: " + Thread.currentThread()
              .getName());
      assertSame(activeSpan, tracer.activeSpan());
      return s;
    }).get(15, TimeUnit.SECONDS));

  }
  parent.finish();

  await().atMost(15, TimeUnit.SECONDS).until(reportedSpansSize(), equalTo(2));
  List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());

  assertNull(tracer.activeSpan());
}
 
Example 2
Source File: AssertionUtils.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a span is created when an active span exists joins the active
 */
static void commandSpanJoinsActiveSpan(MockTracer tracer, Runnable command) {
  final MockSpan parent = tracer.buildSpan("parent").start();
  try (Scope ignored = tracer.activateSpan(parent)) {
    command.run();
    assertEquals(1, tracer.finishedSpans().size());
  }
  parent.finish();

  assertEquals(2, tracer.finishedSpans().size());
  Optional<MockSpan> redisSpan = tracer.finishedSpans().stream()
      .filter((s) -> "java-redis".equals(s.tags().get(Tags.COMPONENT.getKey()))).findFirst();

  Optional<MockSpan> parentSpan =
      tracer.finishedSpans().stream().filter((s) -> "parent".equals(s.operationName()))
          .findFirst();

  assertTrue(redisSpan.isPresent());
  assertTrue(parentSpan.isPresent());

  assertEquals(redisSpan.get().context().traceId(), parentSpan.get().context().traceId());
  assertEquals(redisSpan.get().parentId(), parentSpan.get().context().spanId());
}
 
Example 3
Source File: SpringTest.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void spring_with_parent() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    BasicDataSource dataSource = getDataSource(false);

    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    jdbcTemplate.execute("CREATE TABLE with_parent_1 (id INTEGER)");
    jdbcTemplate.execute("CREATE TABLE with_parent_2 (id INTEGER)");

    dataSource.close();
  }
  parent.finish();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(DB_CONNECTION_SPAN_COUNT + 3, spans.size());

  checkSameTrace(spans);
  checkNoEmptyTags(spans);
}
 
Example 4
Source File: AssertionUtils.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
/**
 * Make sure that a span is created when an active span exists joins the active
 */
static void commandSpanJoinsActiveSpan(MockTracer tracer, Runnable command) {
  final MockSpan parent = tracer.buildSpan("parent").start();
  try (Scope ignored = tracer.activateSpan(parent)) {
    command.run();
    assertEquals(1, tracer.finishedSpans().size());
  }
  parent.finish();

  assertEquals(2, tracer.finishedSpans().size());
  Optional<MockSpan> redisSpan = tracer.finishedSpans().stream()
      .filter((s) -> "java-redis".equals(s.tags().get(Tags.COMPONENT.getKey()))).findFirst();

  Optional<MockSpan> parentSpan =
      tracer.finishedSpans().stream().filter((s) -> "parent".equals(s.operationName()))
          .findFirst();

  assertTrue(redisSpan.isPresent());
  assertTrue(parentSpan.isPresent());

  assertEquals(redisSpan.get().context().traceId(), parentSpan.get().context().traceId());
  assertEquals(redisSpan.get().parentId(), parentSpan.get().context().spanId());
}
 
Example 5
Source File: AbstractClientTest.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentSpan() {
    MockSpan parentSpan = mockTracer.buildSpan("foo").start();

    Response response = client.target(url("/hello"))
            .request()
            .property(TracingProperties.CHILD_OF, parentSpan.context())
            .get();
    response.close();
    assertNoActiveSpan();

    parentSpan.finish();

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(2, mockSpans.size());
    assertOnErrors(mockTracer.finishedSpans());

    MockSpan clientSpan = mockSpans.get(0);
    Assert.assertEquals(parentSpan.context().traceId(), clientSpan.context().traceId());
    Assert.assertEquals(parentSpan.context().spanId(), clientSpan.parentId());
}
 
Example 6
Source File: HibernateTest.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void jpa_with_parent_and_active_span_only() {
  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    EntityManagerFactory entityManagerFactory = Persistence
        .createEntityManagerFactory("jpa_active_span_only");

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    entityManager.getTransaction().begin();
    entityManager.persist(new Employee());
    entityManager.persist(new Employee());
    entityManager.getTransaction().commit();
    entityManager.close();
    entityManagerFactory.close();
  }
  parent.finish();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(12, spans.size());
  checkSameTrace(spans);
  assertNull(mockTracer.activeSpan());
}
 
Example 7
Source File: IntegrationTest.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void spanJoinsActiveSpan() {
  MockSpan span = tracer.buildSpan("parent").start();
  try (Scope ignored = tracer.activateSpan(span)) {
    redisTemplate.opsForList().leftPushAll("test-list", 1, 2, 3);
    assertEquals(1, tracer.finishedSpans().size());
    assertEquals("LPUSH", tracer.finishedSpans().get(0).operationName());
  } finally {
    span.finish();
  }

  assertEquals(2, tracer.finishedSpans().size());
  Optional<MockSpan> redisSpan = tracer.finishedSpans().stream()
      .filter((s) -> "java-redis".equals(s.tags().get(Tags.COMPONENT.getKey()))).findFirst();

  Optional<MockSpan> parentSpan =
      tracer.finishedSpans().stream().filter((s) -> "parent".equals(s.operationName())).findFirst();

  assertTrue(redisSpan.isPresent());
  assertTrue(parentSpan.isPresent());

  assertEquals(redisSpan.get().context().traceId(), parentSpan.get().context().traceId());
  assertEquals(redisSpan.get().parentId(), parentSpan.get().context().spanId());
}
 
Example 8
Source File: HibernateTest.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void hibernate_with_parent_and_active_span_only() {
  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    SessionFactory sessionFactory = createSessionFactory(true);
    Session session = sessionFactory.openSession();

    session.beginTransaction();
    session.save(new Employee());
    session.save(new Employee());
    session.getTransaction().commit();
    session.close();
    sessionFactory.close();
  }
  parent.finish();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(12, spans.size());
  checkSameTrace(spans);
  assertNull(mockTracer.activeSpan());
}
 
Example 9
Source File: LifecycleTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldUseActiveSpan() {
    driver.addExpectation(onRequestTo("/users/me")
                    .withHeader("traceid", notNullValue(String.class))
                    .withHeader("spanid", notNullValue(String.class)),
            giveEmptyResponse().withStatus(200));

    final MockSpan span = tracer.buildSpan("test").start();

    try (final Scope ignored = tracer.activateSpan(span)) {
        unit.get("/users/{user}", "me")
                .call(pass())
                .join();
    } finally {
        span.finish();
    }

    assertThat(tracer.finishedSpans(), contains(span));
}
 
Example 10
Source File: LifecycleTest.java    From riptide with MIT License 6 votes vote down vote up
@Test
void shouldUseExplicitSpan() {
    driver.addExpectation(onRequestTo("/users/me")
                    .withHeader("traceid", notNullValue(String.class))
                    .withHeader("spanid", notNullValue(String.class)),
            giveEmptyResponse().withStatus(200));

    final MockSpan span = tracer.buildSpan("test").start();

    unit.get("/users/{user}", "me")
            .attribute(OpenTracingPlugin.SPAN, span)
            .call(pass())
            .join();

    span.finish();

    assertThat(tracer.finishedSpans(), contains(span));
}
 
Example 11
Source File: TracedHystrixCommandTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithCircuitBreaker() {
  MockSpan span = mockTracer.buildSpan("test_with_circuit_breaker").start();
  try (Scope scope = mockTracer.activateSpan(span)) {
    String response = greetingService.alwaysFail();
    assertThat(response).isNotNull();
  } finally {
    span.finish();
  }

  /**
   * 3 spans totally
   * <ul>
   *     <li>one thats started in test</li>
   *     <li>one thats added in alwaysFail method of Greeting Service</li>
   *     <li>one thats added in the defaultGreeting method which is a fallback</li>
   * </ul>
   */
  await().atMost(3, TimeUnit.SECONDS).until(() -> mockTracer.finishedSpans().size() == 3);

  List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(3, mockSpans.size());
  TestUtils.assertSameTraceId(mockSpans);
  MockSpan hystrixSpan = mockSpans.get(1);
  assertThat(hystrixSpan.tags()).isNotEmpty();
  //one thats added in the defaultGreeting method which is a fallback should have the custom tag added
  assertThat(hystrixSpan.tags().get("fallback")).isEqualTo("yes");
}
 
Example 12
Source File: JdbcTracingTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure that a span is created when an active span exists joins the active
 */
@Test
public void spanJoinsActiveSpan() throws SQLException {
  MockSpan span = tracer.buildSpan("parent").start();
  try (Scope ignored = tracer.activateSpan(span)) {
    assertTrue(dataSource.getConnection().prepareStatement("select 1").execute());
    assertEquals(1, tracer.finishedSpans().size());
  } finally {
    span.finish();
  }

  assertEquals(2, tracer.finishedSpans().size());
  Optional<MockSpan> jdbcSpan = tracer
      .finishedSpans()
      .stream()
      .filter((s) -> "java-jdbc".equals(s.tags().get(Tags.COMPONENT.getKey())))
      .findFirst();

  Optional<MockSpan> parentSpan = tracer
      .finishedSpans()
      .stream()
      .filter((s) -> "parent".equals(s.operationName()))
      .findFirst();

  assertTrue(jdbcSpan.isPresent());
  assertTrue(parentSpan.isPresent());

  assertEquals(jdbcSpan.get().context().traceId(), parentSpan.get().context().traceId());
  assertEquals(jdbcSpan.get().parentId(), parentSpan.get().context().spanId());
}
 
Example 13
Source File: AsyncAnnotationTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Async
public Future<String> fooAsync() {
  MockSpan innerSpan = tracer.buildSpan("fooInner").start();
  try (Scope fooScope = tracer.activateSpan(innerSpan)) {
    return new AsyncResult<>("whatever");
  } finally {
    innerSpan.finish();
  }

}
 
Example 14
Source File: MongoTracingTest.java    From java-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure that a span is created when an active span exists joins the active
 */
@Test
public void spanJoinsActiveSpan() {
  MockSpan span = tracer.buildSpan("parent").start();
  try (Scope ignored = tracer.activateSpan(span)) {
    assertEquals("Ok", this.mongoTemplate.executeCommand("{ buildInfo: 1 }").getDouble("ok"), 1.0, 0);
    assertEquals(1, tracer.finishedSpans().size());
  } finally {
    span.finish();
  }

  assertEquals(2, tracer.finishedSpans().size());
  Optional<MockSpan> mongoSpan = tracer
      .finishedSpans()
      .stream()
      .filter(s -> "java-mongo".equals(s.tags().get(Tags.COMPONENT.getKey())))
      .findFirst();

  Optional<MockSpan> parentSpan = tracer
      .finishedSpans()
      .stream()
      .filter(s -> "parent".equals(s.operationName()))
      .findFirst();

  assertTrue(mongoSpan.isPresent());
  assertTrue(parentSpan.isPresent());

  assertEquals(mongoSpan.get().context().traceId(), parentSpan.get().context().traceId());
  assertEquals(mongoSpan.get().parentId(), parentSpan.get().context().spanId());
}
 
Example 15
Source File: AgentTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void checkTraceIdFromSubscriberContext(MockTracer tracer) {
  final MockSpan initSpan = tracer.buildSpan("foo").start();
  final AtomicReference<Long> spanInSubscriberContext = new AtomicReference<>();
  try (final Scope scope = tracer.scopeManager().activate(initSpan)) {
    Mono.subscriberContext().map(context -> ((MockSpan)context.get(Span.class)).context().spanId()).doOnNext(spanInSubscriberContext::set).block();
  }
  finally {
    initSpan.finish();
  }

  assertEquals((long)spanInSubscriberContext.get(), initSpan.context().spanId());
}
 
Example 16
Source File: ActiveSpanLifecycleTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void shouldUseActiveSpan() throws SQLException {
    final DataSource dataSource = unit.trace(original);

    try (final Connection connection = dataSource.getConnection();
         final Statement statement = connection.createStatement()) {

        final MockSpan parent = tracer.buildSpan("parent").start();
        try (final Scope ignored = tracer.activateSpan(parent)) {
            statement.execute("SELECT 1");
        } finally {
            parent.finish();
        }
    }

    final List<MockSpan> spans = tracer.finishedSpans();
    final MockSpan span = Iterables.getOnlyElement(spans);

    assertThat(span.operationName(), is("parent"));
    assertThat(span.tags(), hasEntry("component", "JDBC"));
    assertThat(span.tags(), hasEntry("db.instance", "USERS"));
    assertThat(span.tags(), hasEntry("db.statement", "SELECT 1"));
    assertThat(span.tags(), hasEntry("db.type", "sql"));
    assertThat(span.tags(), hasEntry("db.user", ""));
    assertThat(span.tags(), hasEntry("peer.hostname", "users"));
    assertThat(span.tags(), not(hasKey("peer.port")));

    assertThat(span.tags(), not(hasKey("span.kind")));
}
 
Example 17
Source File: TracingLettuce51Test.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void async_continue_span() throws Exception {
  final MockSpan parent = mockTracer.buildSpan("test").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    Span activeSpan = mockTracer.activeSpan();

    RedisClient client = RedisClient.create("redis://localhost");

    StatefulRedisConnection<String, String> connection =
        new TracingStatefulRedisConnection<>(client.connect(),
            new TracingConfiguration.Builder(mockTracer).build());

    RedisAsyncCommands<String, String> commands = connection.async();

    assertEquals("OK",
        commands.set("key2", "value2").toCompletableFuture().thenApply(s -> {
          assertSame(activeSpan, mockTracer.activeSpan());
          return s;
        }).get(15, TimeUnit.SECONDS));

    connection.close();

    client.shutdown();
  }
  parent.finish();
  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example 18
Source File: TracingKafkaTest.java    From java-kafka-client with Apache License 2.0 5 votes vote down vote up
@Test
public void with_parent() throws Exception {
  Producer<Integer, String> producer = createTracingProducer();

  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    producer.send(new ProducerRecord<>("messages", 1, "test"));
  }
  parent.finish();

  final CountDownLatch latch = new CountDownLatch(1);
  createConsumer(latch, 1, false, null);

  producer.close();

  List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(3, mockSpans.size());

  assertNotNull(parent);

  for (MockSpan span : mockSpans) {
    assertEquals(parent.context().traceId(), span.context().traceId());
  }

  MockSpan sendSpan = getByOperationName(mockSpans, TracingKafkaUtils.TO_PREFIX + "messages");
  assertNotNull(sendSpan);

  MockSpan receiveSpan = getByOperationName(mockSpans,
      TracingKafkaUtils.FROM_PREFIX + "messages");
  assertNotNull(receiveSpan);

  assertEquals(sendSpan.context().spanId(), receiveSpan.parentId());
  assertEquals(parent.context().spanId(), sendSpan.parentId());

  assertNull(mockTracer.activeSpan());
}
 
Example 19
Source File: TracingRedissonTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void test_config_span_name() throws Exception {
  Config config = new Config();
  config.useSingleServer().setAddress("redis://127.0.0.1:6379");

  RedissonClient customClient = new TracingRedissonClient(Redisson.create(config),
      new TracingConfiguration.Builder(tracer)
          .traceWithActiveSpanOnly(true)
          .withSpanNameProvider(operation -> "Redis." + operation)
          .build());

  final MockSpan parent = tracer.buildSpan("test").start();
  try (Scope ignore = tracer.activateSpan(parent)) {
    RMap<String, String> map = customClient.getMap("map_config_span_name");
    map.getAsync("key").get(15, TimeUnit.SECONDS);
  }
  parent.finish();

  await().atMost(15, TimeUnit.SECONDS).until(reportedSpansSize(), equalTo(2));

  List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  MockSpan redisSpan = spans.get(0);
  assertEquals("Redis.getAsync", redisSpan.operationName());

  assertNull(tracer.activeSpan());
  customClient.shutdown();
}
 
Example 20
Source File: OpenTracingPluginTest.java    From riptide with MIT License 4 votes vote down vote up
@Test
void shouldTraceRequestAndServerError() {
    driver.addExpectation(onRequestTo("/"), giveEmptyResponse().withStatus(500));

    final MockSpan parent = tracer.buildSpan("test").start();

    try (final Scope ignored = tracer.activateSpan(parent)) {
        final CompletableFuture<ClientHttpResponse> future = unit.get(URI.create(driver.getBaseUrl()))
                .attribute(OpenTracingPlugin.TAGS, singletonMap("test", "true"))
                .attribute(OpenTracingPlugin.LOGS, singletonMap("retry_number", 2))
                .call(noRoute());

        final CompletionException error = assertThrows(CompletionException.class, future::join);
        assertThat(error.getCause(), is(instanceOf(UnexpectedResponseException.class)));
    } finally {
        parent.finish();
    }

    final List<MockSpan> spans = tracer.finishedSpans();
    assertThat(spans, hasSize(2));

    assertThat(spans.get(1), is(parent));

    final MockSpan child = spans.get(0);
    assertThat(child.parentId(), is(parent.context().spanId()));

    assertThat(child.tags(), hasEntry("component", "Riptide"));
    assertThat(child.tags(), hasEntry("span.kind", "client"));
    assertThat(child.tags(), hasEntry("peer.address", "localhost:" + driver.getPort()));
    assertThat(child.tags(), hasEntry("peer.hostname", "localhost"));
    assertThat(child.tags(), hasEntry("peer.port", driver.getPort()));
    assertThat(child.tags(), hasEntry("http.method", "GET"));
    assertThat(child.tags(), hasEntry("http.status_code", 500));
    assertThat(child.tags(), hasEntry("error", true));
    assertThat(child.tags(), hasEntry("test", "true"));
    assertThat(child.tags(), hasEntry("test.environment", "JUnit"));
    assertThat(child.tags(), hasEntry("spi", true));

    // since we didn't use a uri template
    assertThat(child.tags(), not(hasKey("http.path")));

    final List<LogEntry> logs = child.logEntries();
    assertThat(logs, hasSize(1));
    final LogEntry log = logs.get(0);
    assertThat(log.fields(), hasEntry("retry_number", 2));
}