io.opentracing.mock.MockSpan Java Examples

The following examples show how to use io.opentracing.mock.MockSpan. 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: RabbitMqTracingAutoConfigurationCustomizationItTest.java    From java-spring-rabbitmq with Apache License 2.0 10 votes vote down vote up
@Test
public void convertAndSend_withRoutingKeyAndMessagePostProcessor_shouldBeTraced() {
  // given
  Message requestMessage = createMessage();
  MessagePostProcessor messagePostProcessor = msg -> msg;

  // when
  rabbitTemplate.convertAndSend(ROUTING_KEY, requestMessage, messagePostProcessor);

  // then
  FinishedSpansHelper spans = awaitFinishedSpans();
  MockSpan sentSpan = spans.getSendSpan();
  MockSpan receiveSpan = spans.getReceiveSpan();

  assertOnSpans(sentSpan, receiveSpan, ROUTING_KEY);
}
 
Example #2
Source File: AbstractBaseITests.java    From java-spring-web with Apache License 2.0 7 votes vote down vote up
@Test
public void testAsyncDeferred() throws Exception {
    {
        getRestTemplate().getForEntity("/asyncDeferred", 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("test", 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("/asyncDeferred"), span.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(202, span.tags().get(Tags.HTTP_STATUS.getKey()));
    Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey()));

    assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterConcurrentHandlingStarted",
            "preHandle", "afterCompletion"));
}
 
Example #3
Source File: JdbcTest.java    From java-jdbc with Apache License 2.0 7 votes vote down vote up
@Test
public void testFailOriginalUrl() throws Exception {
  TracingDriver.ensureRegisteredAsTheFirstDriver();
  TracingDriver.setInterceptorMode(true);
  try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:jdbc")) {
    Statement statement = connection.createStatement();
    try {
      statement.executeUpdate("CREATE TABLE employer (id INTEGER2)");
    } catch (Exception ignore) {
    }
    assertGetDriver(connection);
  }

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
  MockSpan span = spans.get(1);
  assertTrue(span.tags().containsKey(Tags.ERROR.getKey()));
  checkNoEmptyTags(spans);
}
 
Example #4
Source File: JdbcTest.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailTracingUrl() throws Exception {
  try (Connection connection = DriverManager.getConnection("jdbc:tracing:h2:mem:jdbc")) {
    Statement statement = connection.createStatement();
    try {
      statement.executeUpdate("CREATE TABLE employer (id INTEGER2)");
    } catch (Exception ignore) {
    }
    assertGetDriver(connection);
  }

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
  MockSpan span = spans.get(1);
  assertTrue(span.tags().containsKey(Tags.ERROR.getKey()));
  checkNoEmptyTags(spans);
}
 
Example #5
Source File: HibernateTest.java    From java-jdbc with Apache License 2.0 6 votes vote down vote up
@Test
public void hibernate_with_parent() {
  final MockSpan parent = mockTracer.buildSpan("parent").start();
  try (Scope ignored = mockTracer.activateSpan(parent)) {
    SessionFactory sessionFactory = createSessionFactory(false);
    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 #6
Source File: TracingLettuce52Test.java    From java-redis-client with Apache License 2.0 6 votes vote down vote up
@Test
public void sync() {
  RedisClient client = RedisClient.create("redis://localhost");

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

  assertEquals("OK", commands.set("key", "value"));
  assertEquals("value", commands.get("key"));

  connection.close();

  client.shutdown();

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #7
Source File: SpringWebFluxTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet(final MockTracer tracer) {
  testRestTemplate.getForEntity("/", String.class);

  final List<MockSpan> mockSpans = tracer.finishedSpans();
  Assert.assertEquals(1, mockSpans.size());

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

  Assert.assertEquals(8, 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(testRestTemplate.getRootUri() + "/", span.tags().get(Tags.HTTP_URL.getKey()));
  Assert.assertEquals(200, span.tags().get(Tags.HTTP_STATUS.getKey()));
  Assert.assertEquals("java-spring-webflux", span.tags().get(Tags.COMPONENT.getKey()));
  Assert.assertNotNull(span.tags().get(Tags.PEER_PORT.getKey()));
  Assert.assertEquals("127.0.0.1", span.tags().get(Tags.PEER_HOST_IPV4.getKey()));
}
 
Example #8
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 #9
Source File: Dubbo27AgentTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorSpans(final MockTracer tracer) throws Exception {
    GreeterServiceImpl.isThrowExecption = true;
    try {
        client.get().sayHello("jorge");
    } catch (Exception e) {
        Assert.assertEquals(GreeterServiceImpl.errorMesg, e.getMessage());
    }
    List<MockSpan> mockSpans = tracer.finishedSpans();
    Assert.assertEquals(2, mockSpans.size());
    Assert.assertEquals("GreeterService/sayHello", mockSpans.get(0).operationName());
    Assert.assertEquals("GreeterService/sayHello", mockSpans.get(1).operationName());
    Assert.assertEquals(true, mockSpans.get(0).tags().get(Tags.ERROR.getKey()));
    Assert.assertEquals(true, mockSpans.get(1).tags().get(Tags.ERROR.getKey()));
    GreeterServiceImpl.isThrowExecption = false;
}
 
Example #10
Source File: DataSourceTracerTest.java    From opentracing-toolbox with MIT License 6 votes vote down vote up
@Test
void shouldTraceBatch() throws SQLException {
    try (final Connection connection = original.getConnection();
         final Statement statement = connection.createStatement()) {

        statement.execute("CREATE TABLE users(id BIGINT, name TEXT)");
    }

    final DataSource dataSource = unit.trace(original);

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

        statement.addBatch("INSERT INTO users(id, name) VALUES (1, 'Alice')");
        statement.addBatch("INSERT INTO users(id, name) VALUES (2, 'Bob')");
        statement.executeBatch();
    }

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

    assertThat(span.operationName(), is("executeBatch"));
    assertThat(span.tags(), hasEntry("db.statement",
            "INSERT INTO users(id, name) VALUES (1, 'Alice')\nINSERT INTO users(id, name) VALUES (2, 'Bob')"));
}
 
Example #11
Source File: AbstractServerDefaultConfigurationTest.java    From java-jaxrs with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultOperationNameAndTags() {
    Client client = ClientBuilder.newClient();
    Response response = client.target(url("/hello/1"))
            .request()
            .get();
    response.close();
    await().until(finishedSpansSizeEquals(1));

    Assert.assertEquals(1, mockTracer.finishedSpans().size());
    assertOnErrors(mockTracer.finishedSpans());

    MockSpan mockSpan = mockTracer.finishedSpans().get(0);
    Assert.assertEquals("GET:/hello/{id}", mockSpan.operationName());
    Assert.assertEquals(5, mockSpan.tags().size());
    Assert.assertEquals(Tags.SPAN_KIND_SERVER, mockSpan.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("jaxrs", mockSpan.tags().get(Tags.COMPONENT.getKey()));
    Assert.assertEquals(url("/hello/1"), mockSpan.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(200, mockSpan.tags().get(Tags.HTTP_STATUS.getKey()));
}
 
Example #12
Source File: OpenTracingDecoratorTest.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncExceptionWorks() throws Exception {
    OpenTracingDecorator decorator = new OpenTracingDecorator();
    DataFetchingEnvironment dfe = MockDataFetchEnvironment.myFastQueryDfe("Query", "myFastQuery", "someOperation", "1");

    MockExecutionContext mockExecutionContext = new MockExecutionContext();
    mockExecutionContext.setDataFetchingEnvironment(dfe);
    mockExecutionContext.setNewGraphQLContext(GraphQLContext.newContext().build());
    final CompletableFuture<Object> result = new CompletableFuture<>();
    mockExecutionContext.setResult(result);

    decorator.execute(mockExecutionContext);

    assertNoSpanIsFinished();

    result.completeExceptionally(new RuntimeException());

    assertOneSpanIsFinished();
    MockSpan span = MockTracerOpenTracingService.MOCK_TRACER.finishedSpans().get(0);
    assertContainsGraphQLTags(span, "Query", "myFastQuery", "someOperation", "1");
    assertErrorIsLogged(span);
}
 
Example #13
Source File: JettyServletTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testHelloRequest(final MockTracer tracer) throws IOException {
  MockFilter.count = 0;
  MockServlet.count = 0;

  final OkHttpClient client = new OkHttpClient();
  final Request request = new Request.Builder().url("http://localhost:" + serverPort + "/hello").build();
  final Response response = client.newCall(request).execute();

  assertEquals("MockServlet response", HttpServletResponse.SC_ACCEPTED, response.code());
  assertEquals("MockServlet count", 1, MockServlet.count);
  assertEquals("MockFilter count", 1, MockFilter.count);

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals("MockTracer spans: " + spans, 1, spans.size());
  assertEquals("MockTracer tagging: ", MockSpanDecorator.MOCK_TAG_VALUE, spans.get(0).tags().get(MockSpanDecorator.MOCK_TAG_KEY));

  final Request noTraceRequest = new Request.Builder().url("http://localhost:" + serverPort + "/skipit").build();
  final Response noTraceResponse = client.newCall(noTraceRequest).execute();

  assertEquals("MockServlet response", HttpServletResponse.SC_ACCEPTED, noTraceResponse.code());
  assertEquals("MockServlet count", 2, MockServlet.count);
  assertEquals("MockFilter count", 2, MockFilter.count);
  final List<MockSpan> no_change_spans = tracer.finishedSpans();
  assertEquals("MockTracer spans: " + no_change_spans, 1, no_change_spans.size());
}
 
Example #14
Source File: SpanLoggingTest.java    From microprofile-sandbox with Apache License 2.0 6 votes vote down vote up
/**
 * Test that Span Implicit logging will output to the Span when using the equivalent standard logging method (I.e.
 * .debug() also logs to Span).
 *
 * @param info Test information
 */
@Test
public void testSpanImplicit(TestInfo info) {
  setSpanImplicitLevel(Level.DEBUG);

  LazyEval lazy = mock(LazyEval.class);
  when(lazy.evaluate()).thenReturn("lazy");

  final MockSpan span = initSpan(info.getDisplayName());
  log.debug(e -> {
    lazy.evaluate();
    assertNotNull(e.spanId, "Span ID was null");
    return String.format("Span ID Log Message [%s]", e.spanId);
  });

  // Check the Span received logging.
  assertFalse(span.logEntries().isEmpty(), "Expected Log Entries");

  verify(lazy).evaluate();
  
  // The logger should also have received logging.
  Utils.assertLogCount(log, 1);
}
 
Example #15
Source File: RxJava2Test.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void consumerTest3(final MockTracer tracer) {
  final Observable<Integer> observable = createSequentialObservable(tracer, false);
  final List<Integer> result = new ArrayList<>();
  final Consumer<Integer> onNext = consumer(result);
  final List<String> completeList = new ArrayList<>();
  final List<String> errorList = new ArrayList<>();
  observable.subscribe(onNext, onError(errorList), onComplete(completeList, tracer));

  assertEquals(5, result.size());
  assertTrue(completeList.contains(COMPLETED));
  assertEquals(1, completeList.size());
  assertTrue(errorList.isEmpty());

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());

  assertNull(tracer.scopeManager().active());
}
 
Example #16
Source File: MVCJettyITest.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@Test
    public void testSecuredURLUnAuthorized() throws Exception {
        {
            getRestTemplate().getForEntity("/secured", 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("GET", 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("/secured"), span.tags().get(Tags.HTTP_URL.getKey()));
        Assert.assertEquals(401, span.tags().get(Tags.HTTP_STATUS.getKey()));
        Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey()));

//        request does not hit any controller
        assertLogEvents(span.logEntries(), Collections.<String>emptyList());
    }
 
Example #17
Source File: RabbitMqTracingManualConfigurationItTest.java    From java-spring-rabbitmq with Apache License 2.0 6 votes vote down vote up
@Test
public void sendAndReceive_withProcessedLongerThanRabbitTemplateTimeout_shouldProduceSpanWithError() {
  // given
  Message requestMessage = createMessage();
  requestMessage.getMessageProperties().setHeader(RabbitWithoutRabbitTemplateConfig.TestMessageListener.HEADER_SLEEP_MILLIS,
      RabbitWithRabbitTemplateConfig.RABBIT_TEMPLATE_REPLY_TIMEOUT_MILLIS + 500);

  // when
  Message response = rabbitTemplate.sendAndReceive(EXCHANGE, ROUTING_KEY, requestMessage, null);

  // then
  assertThat(response, nullValue()); // response is null in case of timeout

  List<MockSpan> nowFinishedSpans = tracer.finishedSpans();
  assertThat(nowFinishedSpans.size(), equalTo(1)); // only send span should be finished, consumer is still sleeping

  MockSpan sendSpan = nowFinishedSpans.get(0);
  assertSpanRabbitTags(sendSpan, RabbitMqTracingTags.SPAN_KIND_PRODUCER, ROUTING_KEY);

  assertErrorTag(sendSpan); // check that when response wasn't sent before timeout,
  // then error tag is added (so span of the trace could be highlighted in UI)

  MockSpan receiveSpan = awaitFinishedSpans().getReceiveSpan();
  assertThat(REASON, receiveSpan, notNullValue());
  assertRabbitConsumerSpan(receiveSpan, ROUTING_KEY);
}
 
Example #18
Source File: ErrorReportingTest.java    From opentracing-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleError() {
    Span span = tracer.buildSpan("one").start();
    try (Scope scope = tracer.activateSpan(span)) {
        throw new RuntimeException("Invalid state");
    } catch (Exception e) {
        Tags.ERROR.set(span, true);
    } finally {
        span.finish();
    }

    assertNull(tracer.scopeManager().activeSpan());

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(spans.size(), 1);
    assertEquals(spans.get(0).tags().get(Tags.ERROR.getKey()), true);
}
 
Example #19
Source File: TracingServerInterceptorTest.java    From java-grpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testTracedServerTwoInterceptors() {
  TracingServerInterceptor tracingInterceptor =
      TracingServerInterceptor.newBuilder().withTracer(serverTracer).build();
  SecondServerInterceptor secondServerInterceptor = new SecondServerInterceptor(serverTracer);
  TracedService.addGeeterService(
      grpcServer.getServiceRegistry(), secondServerInterceptor, tracingInterceptor);

  assertEquals("call should complete successfully", "Hello world", client.greet().getMessage());
  await().atMost(5, TimeUnit.SECONDS).until(reportedSpansSize(serverTracer), equalTo(1));
  assertEquals(
      "one span should have been created and finished for one client request",
      serverTracer.finishedSpans().size(),
      1);

  MockSpan span = serverTracer.finishedSpans().get(0);
  assertEquals(
      "span should have default name", span.operationName(), "helloworld.Greeter/SayHello");
  assertEquals("span should have no parents", span.parentId(), 0);
  assertTrue("span should have no logs", span.logEntries().isEmpty());
  Assertions.assertThat(span.tags())
      .as("span should have base server tags")
      .isEqualTo(BASE_SERVER_TAGS);
  assertFalse("span should have no baggage", span.context().baggageItems().iterator().hasNext());
}
 
Example #20
Source File: TracingKafkaUtilsTest.java    From java-kafka-client with Apache License 2.0 6 votes vote down vote up
@Test
public void inject_two_contexts_and_extract() {
  MockSpan span = mockTracer.buildSpan("first").start();
  Headers headers = new RecordHeaders();
  assertEquals(0, headers.toArray().length);

  // inject first
  TracingKafkaUtils.inject(span.context(), headers, mockTracer);
  int headersLength = headers.toArray().length;
  assertTrue(headersLength > 0);

  // inject second
  MockSpan span2 = mockTracer.buildSpan("second").asChildOf(span.context()).start();
  TracingKafkaUtils.inject(span2.context(), headers, mockTracer);
  assertTrue(headers.toArray().length > headersLength);

  // check first
  MockSpan.MockContext spanContext = (MockSpan.MockContext) TracingKafkaUtils
      .extractSpanContext(headers, mockTracer);
  assertEquals(span2.context().spanId(), spanContext.spanId());
  assertEquals(span2.context().traceId(), spanContext.traceId());
}
 
Example #21
Source File: AbstractTracingClientTest.java    From java-spring-web with Apache License 2.0 6 votes vote down vote up
@Test
public void testParentSpan() {
    {
        Span parent = mockTracer.buildSpan("parent").start();

        final String path = "/foo";
        final String url = wireMockRule.url(path);
        stubFor(get(urlPathEqualTo(path))
                .willReturn(ok()));
        try (Scope scope = mockTracer.activateSpan(parent)) {
            client.getForEntity(url, String.class);
        } finally {
            parent.finish();
        }
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(2, mockSpans.size());
    Assert.assertEquals(mockSpans.get(0).parentId(), mockSpans.get(1).context().spanId());
    Assert.assertEquals(mockSpans.get(0).context().traceId(), mockSpans.get(1).context().traceId());
}
 
Example #22
Source File: TracingKafkaTest.java    From java-kafka-client with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
  Producer<Integer, String> producer = createTracingProducer();

  // Send 1
  producer.send(new ProducerRecord<>("messages", 1, "test"));

  // Send 2
  producer.send(new ProducerRecord<>("messages", 1, "test"),
      (metadata, exception) -> assertEquals("messages", metadata.topic()));

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

  producer.close();

  List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(4, mockSpans.size());
  checkSpans(mockSpans);
  assertNull(mockTracer.activeSpan());
}
 
Example #23
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 #24
Source File: RabbitMQTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void basicGet(final MockTracer tracer) throws IOException {
  final String exchangeName = "basicGetExchange";
  final String queueName = "basicGetQueue";
  final String routingKey = "#";

  channel.exchangeDeclare(exchangeName, "direct", true);
  channel.queueDeclare(queueName, true, false, false, null);
  channel.queueBind(queueName, exchangeName, routingKey);

  final byte[] messageBodyBytes = "Hello, world!".getBytes();
  channel.basicPublish(exchangeName, routingKey, null, messageBodyBytes);

  final GetResponse response = channel.basicGet(queueName, false);
  assertNotNull(response.getBody());

  final List<MockSpan> finishedSpans = tracer.finishedSpans();
  assertEquals(2, finishedSpans.size());

  assertNull(tracer.activeSpan());
}
 
Example #25
Source File: TracedThreadPoolTaskSchedulerIntegrationTest.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void testExecute() {
  final Span span = mockTracer.buildSpan("5150").start();
  try (Scope scope = mockTracer.activateSpan(span)) {
    final CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
      mockTracer.buildSpan("child").start().finish();
      return "ok";
    }, threadPoolTaskScheduler);
    completableFuture.join();
  }
  span.finish();
  await().until(() -> mockTracer.finishedSpans().size() == 2);

  final List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(2, mockSpans.size());
  TestUtils.assertSameTraceId(mockSpans);
}
 
Example #26
Source File: ErrorReportingTest.java    From opentracing-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackError() {
    final Span span = tracer.buildSpan("one").start();
    executor.submit(new Runnable() {
        @Override
        public void run() {
            try (Scope scope = tracer.activateSpan(span)) {
                throw new RuntimeException("Invalid state");
            } catch (Exception exc) {
                Tags.ERROR.set(span, true);
            } finally {
                span.finish();
            }
        }
    });

    await().atMost(5, TimeUnit.SECONDS).until(finishedSpansSize(tracer), equalTo(1));

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(spans.size(), 1);
    assertEquals(spans.get(0).tags().get(Tags.ERROR.getKey()), true);
}
 
Example #27
Source File: JmsArtemisManualServerTest.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void testListenerSpans() throws JMSException {
  jmsTemplate.convertAndSend(QUEUE_NAME, "Hello!");

  await().atMost(10, TimeUnit.SECONDS).until(() -> {
    List<MockSpan> mockSpans = tracer.finishedSpans();
    return (mockSpans.size() == 2);
  });

  Assert.assertEquals("Hello!", ((TextMessage)msgListener.getMessage()).getText());

  List<MockSpan> spans = tracer.finishedSpans();
  // jms send, jms receive
  assertEquals(2, spans.size());
  TestUtils.assertSameTraceId(spans);
}
 
Example #28
Source File: TracedExecutorTest.java    From java-spring-cloud with Apache License 2.0 6 votes vote down vote up
private void testTracedExecutor(Executor executor) {
  Span span = mockTracer.buildSpan("foo").start();
  try (Scope scope = mockTracer.activateSpan(span)) {
    CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
      mockTracer.buildSpan("child").start().finish();
      return "ok";
    }, executor);
    completableFuture.join();
  }
  span.finish();
  await().until(() -> mockTracer.finishedSpans().size() == 2);

  List<MockSpan> mockSpans = mockTracer.finishedSpans();
  assertEquals(2, mockSpans.size());
  TestUtils.assertSameTraceId(mockSpans);
}
 
Example #29
Source File: TracingClientInterceptorTest.java    From java-grpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testTracedClientwithActiveSpanSource() {
  final MockSpan parentSpan = clientTracer.buildSpan("parent").start();
  ActiveSpanSource activeSpanSource =
      new ActiveSpanSource() {
        @Override
        public Span getActiveSpan() {
          return parentSpan;
        }
      };
  TracingClientInterceptor tracingInterceptor =
      TracingClientInterceptor.newBuilder()
          .withTracer(clientTracer)
          .withActiveSpanSource(activeSpanSource)
          .build();
  TracedClient client = new TracedClient(grpcServer.getChannel(), tracingInterceptor);

  assertEquals("call should complete successfully", "Hello world", client.greet().getMessage());
  await().atMost(5, TimeUnit.SECONDS).until(reportedSpansSize(clientTracer), equalTo(1));
  assertEquals(
      "one span should have been created and finished for one client request",
      clientTracer.finishedSpans().size(),
      1);

  MockSpan span = clientTracer.finishedSpans().get(0);
  assertEquals("span should have prefix", span.operationName(), "helloworld.Greeter/SayHello");
  assertEquals("span should have parent", span.parentId(), parentSpan.context().spanId());
  assertEquals("span should have no logs", span.logEntries().size(), 0);
  Assertions.assertThat(span.tags())
      .as("span should have base client tags")
      .isEqualTo(BASE_CLIENT_TAGS);
  assertFalse("span should have no baggage", span.context().baggageItems().iterator().hasNext());
}
 
Example #30
Source File: CustomConfigurationTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void renamesToLowerUnderscore() {
    tracer.buildSpan("MyTest").start().finish();

    final MockSpan span = getOnlyElement(mockTracer.finishedSpans());
    assertThat(span.operationName(), is("myTest"));
}