io.opentracing.mock.MockTracer Java Examples

The following examples show how to use io.opentracing.mock.MockTracer. 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: LettuceTest.java    From java-specialagent with Apache License 2.0 10 votes vote down vote up
@Test
public void testPubSub(final MockTracer tracer) {
  final StatefulRedisPubSubConnection<String,String> connection = client.connectPubSub();
  connection.addListener(new RedisPubSubAdapter<>());

  final RedisPubSubCommands<String,String> commands = connection.sync();
  commands.subscribe("channel");

  final RedisCommands<String,String> commands2 = client.connect().sync();
  commands2.publish("channel", "msg");

  await().atMost(15, TimeUnit.SECONDS).until(TestUtil.reportedSpansSize(tracer), equalTo(4));

  client.shutdown();

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(4, spans.size());
}
 
Example #2
Source File: ThreadTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoRunnable(final MockTracer tracer) throws InterruptedException {
  final AtomicBoolean foundSpan = new AtomicBoolean(false);
  final Thread thread = new Thread() {
    @Override
    public void run() {
      foundSpan.set(tracer.activeSpan() != null);
    }
  };

  try (final Scope scope = tracer.buildSpan("parent").startActive(true)) {
    thread.start();
  }

  thread.join(10_000);
  assertTrue(foundSpan.get());
  assertEquals(1, tracer.finishedSpans().size());
  assertNull(GlobalTracer.get().activeSpan());
}
 
Example #3
Source File: MicroProfileOpenTracingTCKDeploymentPackager.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public Archive<?> generateDeployment(final TestDeployment testDeployment,
                                     final Collection<ProtocolArchiveProcessor> processors) {

    final WebArchive webArchive = ShrinkWrap.create(WebArchive.class, "microprofile-opentracing.war")
                                            .merge(testDeployment.getApplicationArchive());

    // opentracing-api jar added by Geronimo Impl. Also added by TCK causes issues with same classes in different Classloaders
    final Map<ArchivePath, Node> content = webArchive.getContent(object -> object.get().matches(".*opentracing-api.*jar.*"));
    content.forEach((archivePath, node) -> webArchive.delete(archivePath));

    // TCK expects a MockTracer. Check org/eclipse/microprofile/opentracing/tck/application/TracerWebService.java:133
    webArchive.addAsLibrary(jarLocation(MockTracer.class));
    webArchive.addAsLibrary(jarLocation(ThreadLocalScopeManager.class));
    webArchive.addAsWebInfResource("META-INF/beans.xml");
    webArchive.addClass(MicroProfileOpenTracingTCKTracer.class);

    System.out.println(webArchive.toString(true));

    return super.generateDeployment(
            new TestDeployment(null, webArchive, testDeployment.getAuxiliaryArchives()), processors);
}
 
Example #4
Source File: MetricsTest.java    From java-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithStartTimestamp() throws InterruptedException {
    MetricsReporter reporter = Mockito.mock(MetricsReporter.class);
    MockTracer tracer = new MockTracer();
    Tracer metricsTracer = Metrics.decorate(tracer, reporter);

    long start = System.currentTimeMillis() * 687;
    Thread.sleep(100);
    Scope parent = metricsTracer.buildSpan("parent")
            .withStartTimestamp(start)
            .startActive(true);

    parent.close();

    List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(1, spans.size());
    MockSpan span = spans.get(0);
    long started = span.startMicros();
    assertEquals(start, started);
}
 
Example #5
Source File: Dubbo26AgentTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testErrorSpans(final MockTracer tracer) {
  GreeterServiceImpl.isThrowExecption = true;
  try {
    client.get().sayHello("jorge");
  }
  catch (final Exception e) {
    Assert.assertEquals(GreeterServiceImpl.errorMesg, e.getMessage());
  }

  final 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()));
}
 
Example #6
Source File: RxJava3Test.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void consumerTest3WithError(final MockTracer tracer) {
  final Observable<Integer> observable = createSequentialObservable(tracer, true);
  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(0, result.size());
  assertEquals(0, completeList.size());
  assertEquals(1, errorList.size());

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

  assertNull(tracer.scopeManager().active());
}
 
Example #7
Source File: RxJava2Test.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void consumerTest(final MockTracer tracer) {
  final Observable<Integer> observable = createSequentialObservable(tracer, false);
  final List<Integer> result = new ArrayList<>();
  final Consumer<Integer> onNext = consumer(result);

  final Disposable disposable = observable.subscribe(onNext);
  logger.fine(String.valueOf(disposable));

  assertEquals(5, result.size());

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

  assertNull(tracer.scopeManager().active());
}
 
Example #8
Source File: SpringJmsTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Before
public void before(final MockTracer tracer) throws Exception {
  tracer.reset();

  final HashSet<TransportConfiguration> transports = new HashSet<>();
  transports.add(new TransportConfiguration(InVMAcceptorFactory.class.getName()));

  final ConfigurationImpl configuration = new ConfigurationImpl();
  configuration.setAcceptorConfigurations(transports);
  configuration.setSecurityEnabled(false);

  final File targetDir = new File(new File("").getAbsoluteFile(), "target");
  configuration.setBrokerInstance(targetDir);

  server = new ActiveMQServerImpl(configuration);
  server.start();
}
 
Example #9
Source File: AwsTest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncClient(final MockTracer tracer) throws Exception {
  final AmazonDynamoDBAsync dbClient = buildAsyncClient();
  final Future<CreateTableResult> createTableResultFuture = createTableAsync(dbClient, "asyncRequest");
  try {
    final CreateTableResult result = createTableResultFuture.get(10, TimeUnit.SECONDS);
    // The following assertion is only relevant when a local instance of dynamodb is present.
    // If a local instance of dynamodb is NOT present, an exception is thrown.
    assertEquals("asyncRequest", result.getTableDescription().getTableName());
  }
  catch (final Exception e) {
    logger.log(Level.WARNING, e.getMessage());
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals("CreateTableRequest", spans.get(0).operationName());
}
 
Example #10
Source File: HazelcastTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void test(final HazelcastInstance instance, final MockTracer tracer) {
  final IMap<String,String> map = instance.getMap("map");
  map.put("key", "value");
  assertEquals("value", map.get("key"));
  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
}
 
Example #11
Source File: JfrTracerTest.java    From java-jfr-tracer with Apache License 2.0 5 votes vote down vote up
@Test
public void noJFR() throws IOException {
	// Setup tracers
	MockTracer mockTracer = new MockTracer();
	Tracer tracer = JfrTracerFactory.create(mockTracer);

	// Generate span
	tracer.buildSpan("test span").start().finish();

	// Validate span was created and recorded in JFR
	assertEquals(1, mockTracer.finishedSpans().size());
}
 
Example #12
Source File: CxfTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testRs(final MockTracer tracer) {
  System.setProperty(Configuration.INTERCEPTORS_CLIENT_IN, ClientSpanTagInterceptor.class.getName());
  System.setProperty(Configuration.INTERCEPTORS_SERVER_OUT, ServerSpanTagInterceptor.class.getName());
  final String msg = "hello";

  // prepare server
  final JAXRSServerFactoryBean serverFactory = new JAXRSServerFactoryBean();
  serverFactory.setAddress(BASE_URI);
  serverFactory.setServiceBean(new EchoImpl());
  final Server server = serverFactory.create();

  // prepare client
  final JAXRSClientFactoryBean clientFactory = new JAXRSClientFactoryBean();
  clientFactory.setServiceClass(Echo.class);
  clientFactory.setAddress(BASE_URI);
  final Echo echo = clientFactory.create(Echo.class);

  final String response = echo.echo(msg);

  assertEquals(msg, response);
  assertEquals(2, tracer.finishedSpans().size());

  final WebClient client = WebClient.create(BASE_URI);
  final String result = client.post(msg, String.class);

  assertEquals(msg, result);
  assertEquals(4, tracer.finishedSpans().size());

  final List<MockSpan> spans = tracer.finishedSpans();
  for (final MockSpan span : spans) {
    assertEquals(AbstractSpanTagInterceptor.SPAN_TAG_VALUE, span.tags().get(AbstractSpanTagInterceptor.SPAN_TAG_KEY));
  }

  server.destroy();
  serverFactory.getBus().shutdown(true);
}
 
Example #13
Source File: SkipPatternTest.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Test
public void noSpansForServletSpansMatchingSkipPattern() throws IOException {
    MockTracer tracer = MockTracerResolver.TRACER_INSTANCE;
    assertEquals(0, tracer.finishedSpans().size());
    hitEndpoint("http://localhost:8080/_opentracing/hello");
    assertEquals(2, tracer.finishedSpans().size());

    // no new *servlet* spans are to be created for this, but business spans are still created
    hitEndpoint("http://localhost:8080/_opentracing/health");
    assertEquals(3, tracer.finishedSpans().size());
}
 
Example #14
Source File: RenameTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@ParameterizedTest
@MethodSource("data")
void renamesOperationName(
        final String source,
        final CaseFormat targetFormat,
        final String target) {

    final MockTracer tracer = new MockTracer();
    final Tracer unit = new ProxyTracer(tracer)
            .with(new Rename(targetFormat));

    unit.buildSpan(source)
            .start().finish();

    final MockSpan span = getOnlyElement(tracer.finishedSpans());
    assertEquals(target, span.operationName());
}
 
Example #15
Source File: PulsarFunctionsTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testPulsarFunction(final MockTracer tracer) {
  try (final JavaInstance instance = new JavaInstance(null, new org.apache.pulsar.functions.api.Function<Object,Object>() {
    @Override
    public Object process(final Object o, final Context context) {
      return null;
    }
  })) {
    instance.handleMessage(null, null);
    verify(tracer);
  }
}
 
Example #16
Source File: ScheduledExecutorServiceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
@AgentRunner.TestConfig(verbose=false)
public void scheduleWithFixedDelayTestSilentWithParent(final MockTracer tracer) throws InterruptedException {
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  try (final Scope scope = tracer.buildSpan("parent").startActive(true)) {
    executorService.scheduleWithFixedDelay(new TestRunnable(tracer, countDownLatch), 0, 10_000, TimeUnit.MILLISECONDS);
  }

  countDownLatch.await();
  assertFalse(tracer.finishedSpans().isEmpty());
}
 
Example #17
Source File: SpanBuilderWrapperTest.java    From java-jfr-tracer with Apache License 2.0 5 votes vote down vote up
@Test
void asChildOfOnParentSpan() {
    MockTracer delegateTracer = new MockTracer();
    Span parentSpan = delegateTracer.buildSpan("parentSpan").start();
    TracerWrapper tracerWrapper = new TracerWrapper(delegateTracer);
    String operationName = "asChildOfOnParentSpan";
    SpanBuilderWrapper spanBuilderWrapper = new SpanBuilderWrapper(tracerWrapper, operationName,
            delegateTracer.buildSpan(operationName));

    SpanBuilder spanBuilder = spanBuilderWrapper.asChildOf(parentSpan);
    assertSame(spanBuilderWrapper, spanBuilder);
    assertNotNull(spanBuilderWrapper.parentId());
    assertEquals(parentSpan.context().toSpanId(), spanBuilderWrapper.parentId());
}
 
Example #18
Source File: ScheduledExecutorServiceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
@AgentRunner.TestConfig(verbose=true)
public void scheduleWithFixedDelayTestVerbose(final MockTracer tracer) throws InterruptedException {
  final CountDownLatch countDownLatch = new CountDownLatch(1);

  executorService.scheduleWithFixedDelay(new TestRunnable(tracer, countDownLatch), 0, 10_000, TimeUnit.MILLISECONDS);
  countDownLatch.await();
  assertFalse(tracer.finishedSpans().isEmpty());
}
 
Example #19
Source File: ScheduledExecutorServiceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
@AgentRunner.TestConfig(verbose=true)
public void scheduleRunnableTestVerbose(MockTracer tracer) throws InterruptedException {
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  executorService.schedule(new TestRunnable(tracer, countDownLatch), 0, TimeUnit.MILLISECONDS);
  countDownLatch.await();
  assertFalse(tracer.finishedSpans().isEmpty());
}
 
Example #20
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 #21
Source File: SpringRabbitMQTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void test(final MockTracer tracer) {
  try (final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(RabbitConfiguration.class)) {
    final AmqpTemplate template = context.getBean(AmqpTemplate.class);
    template.convertAndSend(QUEUE_NAME, "message");
    template.convertAndSend(QUEUE_NAME2, "message-2");

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

    assertEquals(2, counter.get());
    final List<MockSpan> spans = tracer.finishedSpans();
    assertEquals(2, spans.size());
  }
}
 
Example #22
Source File: JedisTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void test(final MockTracer tracer) {
  assertEquals("OK", jedis.set("key", "value"));
  assertEquals("value", jedis.get("key"));

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  checkSpans(spans);
  for (final MockSpan span : spans) {
    assertNull(span.tags().get(Tags.ERROR.getKey()));
  }
}
 
Example #23
Source File: ExecutorServiceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
@AgentRunner.TestConfig(verbose=false)
public void testSubmitCallableSilent(final MockTracer tracer) throws InterruptedException {
  final CountDownLatch countDownLatch = new CountDownLatch(1);

  executorService.submit(new TestCallable(tracer, countDownLatch));

  countDownLatch.await();
  assertFalse(tracer.finishedSpans().isEmpty());
}
 
Example #24
Source File: AwsTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncClient(final MockTracer tracer) {
  final AmazonDynamoDB dbClient = buildClient();
  try {
    createTable(dbClient, "table-1");
  }
  catch (final Exception e) {
    logger.log(Level.WARNING, e.getMessage());
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(1, spans.size());
  assertEquals("CreateTableRequest", spans.get(0).operationName());
}
 
Example #25
Source File: TraversalsTest.java    From spark-dependencies with Apache License 2.0 5 votes vote down vote up
@Test
public void testInorder() {
  Node<MockTracingWrapper> root = new Node<>(new MockTracingWrapper(new MockTracer(), "foo"), null);
  Node<MockTracingWrapper> child1 = new Node<>(new MockTracingWrapper(new MockTracer(), "child1"), root);
  Node<MockTracingWrapper> child2 = new Node<>(new MockTracingWrapper(new MockTracer(), "child2"), root);
  Node<MockTracingWrapper> child3 = new Node<>(new MockTracingWrapper(new MockTracer(), "child3"), root);

  List<Node> nodes = new ArrayList<>();
  Traversals.postOrder(root, (node, parent) -> {
    if (parent != null) {
      assertEquals(root, parent);
    } else {
      assertEquals(null, parent);
    }
    nodes.add(node);
  });
  assertEquals(new ArrayList<>(Arrays.asList(child1, child2, child3, root)), nodes);

  Node<MockTracingWrapper> child33 = new Node<>(new MockTracingWrapper(new MockTracer(), "child33"), child3);
  Node<MockTracingWrapper> child333 = new Node<>(new MockTracingWrapper(new MockTracer(), "child333"), child33);

  List<Node> nodes2 = new ArrayList<>();
  List<Node> parents2 = new ArrayList<>();
  Traversals.postOrder(root, (node, parent) -> {
    nodes2.add(node);
    parents2.add(parent);
  });
  assertEquals(new ArrayList<>(Arrays.asList(child1, child2, child333, child33, child3, root)), nodes2);
  assertEquals(new ArrayList<>(Arrays.asList(root, root, child33, child3, root, null)), parents2);
}
 
Example #26
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 #27
Source File: PulsarClientTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
private static void test(final MockTracer tracer, final boolean async) throws Exception {
  if (!isJdkSupported) {
    logger.warning("jdk" + System.getProperty("java.version") + " is not supported by Pulsar");
    return;
  }

  try (
    final PulsarClient client = PulsarClient.builder().serviceUrl(pulsarService.getBrokerServiceUrl()).build();
    final Consumer<byte[]> consumer = client.newConsumer().topic("my-topic").subscriptionName("my-subscription").subscribe();
    final Producer<byte[]> producer = client.newProducer().topic("my-topic").create();
  ) {
    if (async)
      producer.sendAsync("My message".getBytes()).get(15, TimeUnit.SECONDS);
    else
      producer.send("My message".getBytes());

    final Message<byte[]> message;
    if (async)
      message = consumer.receiveAsync().get(15, TimeUnit.SECONDS);
    else
      message = consumer.receive();

    System.out.println("Message received: " + new String(message.getData()));
    consumer.acknowledge(message);
  }

  final List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  assertNull(tracer.activeSpan());
  for (final MockSpan span : spans)
    assertEquals(PulsarClientAgentIntercept.COMPONENT_NAME, span.tags().get(Tags.COMPONENT.getKey()));

  assertEquals(spans.get(0).context().traceId(), spans.get(1).context().traceId());
}
 
Example #28
Source File: ScheduledExecutorServiceTest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Test
@AgentRunner.TestConfig(verbose=false)
public void scheduleCallableTestSilentWithParent(final MockTracer tracer) throws InterruptedException {
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  try (final Scope scope = tracer.buildSpan("parent").startActive(true)) {
    executorService.schedule(new TestCallable(tracer, countDownLatch), 0, TimeUnit.MILLISECONDS);
  }

  countDownLatch.await();
  assertFalse(tracer.finishedSpans().isEmpty());
}
 
Example #29
Source File: TagListenerTest.java    From opentracing-toolbox with MIT License 5 votes vote down vote up
@Test
void multipleListenersAreChained() {
    final Tracer unit = new ProxyTracer(new MockTracer())
            .with(listener)
            .with(listener);

    final Tracer.SpanBuilder builder = unit.buildSpan("test")
            .withTag("k1", "v");

    final Span span = builder
            .start()
            .setTag("k2", "v");

    verify(listener, times(2)).onTag(eq(builder), tag("k1"), eq("v"));
    verify(listener, times(2)).onTag(eq(span), tag("k2"), eq("v"));
}
 
Example #30
Source File: AbstractJettyTest.java    From java-web-servlet-filter with Apache License 2.0 5 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Check mock tracer is available in servlet context
    response.setStatus(getServletContext().getAttribute(Tracer.class.getName()) instanceof MockTracer ?
            HttpServletResponse.SC_ACCEPTED : HttpServletResponse.SC_EXPECTATION_FAILED);
}