@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()); }
@Test public void testNoURLMapping() { { getRestTemplate().getForEntity("/nouUrlMapping", 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(404, span.tags().get(Tags.HTTP_STATUS.getKey())); assertLogEvents(span.logEntries(), Collections.<String>emptyList()); }
@Test public void testControllerMappedException() throws Exception { { getRestTemplate().getForEntity("/mappedException", 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("mappedException", 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("/mappedException"), span.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(409, span.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey())); assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion")); }
@Test public void testSyncWithStandardTags() throws Exception { { getRestTemplate().getForEntity("/sync", 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("sync", 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("/sync"), span.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(200, span.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey())); assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion")); }
@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")); }
@Test public void testContextPropagation() throws Exception { { HttpHeaders headers = new HttpHeaders(); headers.set("spanid", "1"); headers.set("traceid", "345"); HttpEntity<String> entity = new HttpEntity<>(headers); getRestTemplate().exchange("/sync", HttpMethod.GET, entity, 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(1, span.parentId()); Assert.assertEquals(345, span.context().traceId()); Assert.assertEquals("sync", span.operationName()); }
@Test public void testNoURLMapping() { { getRestTemplate().getForEntity("/nouUrlMapping", String.class); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2)); } List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans(); Assert.assertEquals(2, mockSpans.size()); assertOnErrors(mockSpans); MockSpan span = mockSpans.get(0); Assert.assertEquals("GET", span.operationName()); Assert.assertEquals(404, span.tags().get(Tags.HTTP_STATUS.getKey())); assertLogEvents(span.logEntries(), Collections.<String>emptyList()); span = mockSpans.get(1); Assert.assertEquals(0, span.tags().size()); Assert.assertEquals(mockSpans.get(0).context().spanId(), span.parentId()); Assert.assertEquals(0, span.tags().size()); assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion")); Assert.assertEquals("BasicErrorController", span.logEntries().get(0).fields().get("handler.class_simple_name")); }
@Test public void testSecuredURLAuthorized() throws Exception { { getRestTemplate().withBasicAuth("user", "password").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("secured", 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(200, span.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey())); assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion")); }
@Test public void testForward() { { getRestTemplate().getForEntity("/forward", String.class); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("sync", mockSpan.operationName()); assertLogEvents(mockSpan.logEntries(), Arrays.asList("preHandle", "preHandle", "afterCompletion", "afterCompletion")); Assert.assertEquals("forward", mockSpan.logEntries().get(0).fields().get(HandlerInterceptorSpanDecorator.HandlerUtils.HANDLER_METHOD_NAME)); Assert.assertEquals("sync", mockSpan.logEntries().get(1).fields().get(HandlerInterceptorSpanDecorator.HandlerUtils.HANDLER_METHOD_NAME)); Assert.assertTrue(mockSpan.logEntries().get(2).fields().get(HandlerInterceptorSpanDecorator.HandlerUtils.HANDLER) .toString().contains("sync")); Assert.assertTrue(mockSpan.logEntries().get(3).fields().get(HandlerInterceptorSpanDecorator.HandlerUtils.HANDLER) .toString().contains("forward")); }
@Test public void testLocalSpan() { { getRestTemplate().getForEntity("/localSpan", String.class); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2)); } List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans(); Assert.assertEquals(2, mockSpans.size()); assertOnErrors(mockSpans); MockSpan childSpan = mockSpans.get(0); MockSpan parentSpan = mockSpans.get(1); Assert.assertEquals("localSpan", parentSpan.operationName()); Assert.assertEquals(childSpan.context().traceId(), parentSpan.context().traceId()); Assert.assertEquals(childSpan.parentId(), parentSpan.context().spanId()); }
@Test public void testView() { { getRestTemplate().getForEntity("/view", String.class); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = TracingBeansConfiguration.mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan span = mockSpans.get(0); Assert.assertEquals("view", span.operationName()); Assert.assertEquals(5, span.tags().size()); Assert.assertEquals(Tags.SPAN_KIND_SERVER, span.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", span.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(getUrl("/view"), span.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(200, span.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey())); assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion")); }
@Test public void testControllerView() { { getRestTemplate().getForEntity("/controllerView", 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("/controllerView"), span.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(200, span.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertNotNull(span.tags().get(Tags.COMPONENT.getKey())); assertLogEvents(span.logEntries(), Arrays.asList("preHandle", "afterCompletion")); }
@Test public void testHelloRequest() throws IOException { { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(localRequestUrl("/hello")) .build(); client.newCall(request).execute(); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(Tags.SPAN_KIND_SERVER, mockSpan.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(localRequestUrl("/hello"), mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(202, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("java-web-servlet", mockSpan.tags().get(Tags.COMPONENT.getKey())); }
@Test public void testLocalSpan() throws IOException { { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(localRequestUrl("/localSpan")) .build(); client.newCall(request).execute(); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(2, mockSpans.size()); assertOnErrors(mockSpans); Assert.assertEquals(mockSpans.get(0).context().traceId(), mockSpans.get(1).context().traceId()); Assert.assertEquals(mockSpans.get(0).parentId(), mockSpans.get(1).context().spanId()); }
@Test public void testNotExistingUrl() throws IOException { { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(localRequestUrl("/doesNotExist")) .build(); client.newCall(request).execute(); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(Tags.SPAN_KIND_SERVER, mockSpan.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(localRequestUrl("/doesNotExist"), mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(404, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("java-web-servlet", mockSpan.tags().get(Tags.COMPONENT.getKey())); }
@Test public void testSpanContextPropagation() throws IOException { MockSpan foo = (MockSpan) mockTracer.buildSpan("foo").startManual(); { Map<String, String> injectMap = new HashMap<>(); mockTracer.inject(foo.context(), Format.Builtin.HTTP_HEADERS, new TextMapInjectAdapter(injectMap)); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(localRequestUrl("/hello")) .headers(Headers.of(injectMap)) .build(); client.newCall(request).execute(); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals(foo.context().spanId(), mockSpan.parentId()); Assert.assertEquals(foo.context().traceId(), mockSpan.context().traceId()); }
@Test public void testAsyncImmediateExit() throws IOException { { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(localRequestUrl("/asyncImmediateExit")) .build(); client.newCall(request).execute(); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(Tags.SPAN_KIND_SERVER, mockSpan.tags().get(Tags.SPAN_KIND.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals(localRequestUrl("/asyncImmediateExit"), mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(204, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("java-web-servlet", mockSpan.tags().get(Tags.COMPONENT.getKey())); }
@Test public void testCurrentSpanRequest() throws IOException { { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(localRequestUrl("/currentSpan")) .build(); client.newCall(request).execute(); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); assertOnErrors(mockSpans); MockSpan mockSpan = mockSpans.get(0); Assert.assertTrue((boolean)mockSpan.tags().get("CurrentSpan")); }
@Test public void afterSessionStart_initThrowsRevisionGeneratorException() throws MavenExecutionException, RevisionGeneratorException { RevisionGeneratorException exception = new RevisionGeneratorException("msg", new RuntimeException("dummy sub cause")); exceptions.expect(MavenExecutionException.class); exceptions.expectMessage(exception.getMessage()); exceptions.expectCause(IsEqual.equalTo(exception)); doThrow(exception).when(revisionGenerator).init(eq(session), any(Logger.class)); try { item.afterSessionStart(session); } finally { verify(revisionGenerator).init(eq(session), any(Logger.class)); } }
@Test public void afterSessionStart_initThrowsRuntimeException() throws MavenExecutionException, RevisionGeneratorException { RuntimeException exception = new RuntimeException("random exception"); exceptions.expect(MavenExecutionException.class); exceptions.expectMessage("Unexpected Exception during RevisionGenerator Initialisation"); exceptions.expectCause(IsEqual.equalTo(exception)); doThrow(exception).when(revisionGenerator).init(eq(session), any(Logger.class)); try { item.afterSessionStart(session); } finally { verify(revisionGenerator).init(eq(session), any(Logger.class)); } }
@Test public void testParentSpanFromSpanManager() throws InterruptedException { { Scope scope = mockTracer.buildSpan("parent") .startActive(true); mockWebServer.enqueue(new MockResponse() .setResponseCode(200)); StringEntityRequest entity = feign.<StringEntityRequest>newInstance(new Target.HardCodedTarget(StringEntityRequest.class, mockWebServer.url("/foo").toString())); entity.get(); scope.close(); } 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()); }
@Test public void testNoURLMapping() throws Exception { { request("/noUrlMapping", HttpMethod.GET, 404); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(404, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/noUrlMapping", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(0, mockSpan.logEntries().size()); }
@Test public void testLocalSpan() throws Exception { { router.route("/localSpan").handler(routingContext -> { SpanContext serverSpanContext = TracingHandler.serverSpanContext(routingContext); io.opentracing.Tracer.SpanBuilder spanBuilder = mockTracer.buildSpan("localSpan"); spanBuilder.asChildOf(serverSpanContext) .startManual() .finish(); routingContext.response() .setStatusCode(202) .end(); }); request("/localSpan", HttpMethod.GET, 202); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(2)); } 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()); }
@Test public void testFailRoutingContext() throws Exception { { router.route("/fail").handler(routingContext -> { routingContext.fail(501); }); request("/fail", HttpMethod.GET, 501); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(6, mockSpan.tags().size()); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(501, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/fail", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(0, mockSpan.logEntries().size()); }
@Test public void testExceptionInHandler() throws Exception { { router.route("/exception").handler(routingContext -> { throw new IllegalArgumentException("msg"); }); request("/exception", HttpMethod.GET,500); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(6, mockSpan.tags().size()); Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey())); Assert.assertEquals(500, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/exception", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(1, mockSpan.logEntries().size()); Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size()); Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event")); Assert.assertTrue(mockSpan.logEntries().get(0).fields().get("error.object") instanceof Throwable); }
@Test public void testBodyEndHandler() throws Exception { { router.route("/bodyEnd").handler(routingContext -> { routingContext.addBodyEndHandler(event -> { // noop }); routingContext.response().end(); }); request("/bodyEnd", HttpMethod.GET, 200); Awaitility.await().until(reportedSpansSize(), IsEqual.equalTo(1)); } List<MockSpan> mockSpans = mockTracer.finishedSpans(); Assert.assertEquals(1, mockSpans.size()); MockSpan mockSpan = mockSpans.get(0); Assert.assertEquals("GET", mockSpan.operationName()); Assert.assertEquals(5, mockSpan.tags().size()); Assert.assertEquals(200, mockSpan.tags().get(Tags.HTTP_STATUS.getKey())); Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey())); Assert.assertEquals("http://localhost:8080/bodyEnd", mockSpan.tags().get(Tags.HTTP_URL.getKey())); Assert.assertEquals(0, mockSpan.logEntries().size()); }
@Test public void when_gradle_installation_dir_is_set_but_it_contains_not_a_file_called_gradle_a_validation_exception_is_thrown() throws Exception { /* prepare */ File userHome = new File(System.getProperty("user.home")); File gradleFake = new File(userHome, "gradle"); assertFalse("Test execution not possible - in user home there is a gradle file existing!?!", gradleFake.exists()); when(mockedGradleConfiguration.getGradleBinDirectory()) .thenReturn(gradleFake.getParentFile().getAbsolutePath()); thrown.expect(new IsEqual<>( new ValidationException(GradleConfigurationValidator.GRADLE_INSTALLATION_DIR_CONTAINS_NO_GRADLE))); /* test + execute */ validatorToTest.validate(mockedGradleConfiguration); }
@Test public void when_shell_command_is_set_but_cannot_be_executed_standalone_a_validation_exception_is_thrown() throws Exception { /* prepare */ thrown.expect( new IsEqual<>(new ValidationException(GradleConfigurationValidator.SHELL_NOT_EXECUTABLE_STANDALONE))); when(mockedGradleConfiguration.getShellType()).thenReturn(EGradleShellType.BASH); when(mockedProcessExecutor.execute(any(), any(), any(),eq("bash"), eq("--version"))) .thenThrow(new IOException("bash call standalone does always fail inside this test")); /* execute +test */ validatorToTest.validate(mockedGradleConfiguration); /* only for debugging - if no exception occurred...*/ verify(mockedProcessExecutor).execute(any(), any(), any(),eq("bash"), eq("--version")); }
@Test public void when_a_gradle_call_with_version_throws_an_ioexception_a_validation_exception_is_thrown() throws Exception { /* prepare */ thrown.expect( new IsEqual<>(new ValidationException(GradleConfigurationValidator.GRADLE_VERSON_NOT_CALLABLE))); when(mockedGradleConfiguration.getShellType()).thenReturn(EGradleShellType.BASH); when(mockedGradleConfiguration.getGradleCommandFullPath()).thenReturn("gradlew"); when(mockedProcessExecutor.execute(any(), any(), any(), eq("bash"), eq("gradlew"), eq("--version"))) .thenThrow(new IOException("the simple --version call must fail inside this test")); /* execute +test */ validatorToTest.validate(mockedGradleConfiguration); /* normally dead code, but when no validation exception occured this is googd for debuging:*/ verify(mockedProcessExecutor).execute(any(), any(), any(), eq("bash"), eq("gradlew"), eq("--version")); }
@Test public void refreshError() throws Exception { PublishSubject<Reddit> subject = PublishSubject.create(); Mockito.doReturn(subject.asObservable().toList()) .when(mRepository) .getReddits(Mockito.anyString()); mViewModel.refresh(); Mockito.verify(mRepository).getReddits("test"); Assert.assertThat(mViewModel.errorText.get(), IsNull.nullValue()); Assert.assertThat(mViewModel.isLoading.get(), Is.is(true)); subject.onError(new Exception("error text")); Assert.assertThat(mViewModel.isLoading.get(), Is.is(false)); Assert.assertThat(mViewModel.errorText.get(), IsEqual.equalTo("error text")); }
/** * Tests swiping to change tabs */ public void testTabSwiping() { final Matcher<View> mealsTab = withText(R.string.meals); final Matcher<View> recipesTab = withText(R.string.recipes); final Matcher<View> mealList = withTagKey(R.id.test_tag_meal_list, Is.<Object>is("Meal List")); final Matcher<View> recipeList = withTagKey(R.id.test_tag_recipe_list, Is.<Object>is("Recipe List")); final Matcher<View> pager = withClassName(IsEqual.equalTo(ViewPager.class.getName())); onView(pager).perform(swipeLeft()); SystemClock.sleep(SWITCH_DELAY_MS); onView(recipesTab).check(matches(isSelected())); onView(pager).perform(swipeRight()); SystemClock.sleep(SWITCH_DELAY_MS); onView(mealsTab).check(matches(isSelected())); }
@Test public void testCombiner() throws Exception { org.junit.Assume.assumeThat(mode, new IsEqual<TestExecutionMode>(TestExecutionMode.CLUSTER)); final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple2<IntWritable, IntWritable>> ds = HadoopTestData.getKVPairDataSet(env). map(new Mapper3()); DataSet<Tuple2<IntWritable, IntWritable>> counts = ds. groupBy(0). reduceGroup(new HadoopReduceCombineFunction<IntWritable, IntWritable, IntWritable, IntWritable>( new SumReducer(), new KeyChangingReducer())); String resultPath = tempFolder.newFile().toURI().toString(); counts.writeAsText(resultPath); env.execute(); String expected = "(0,5)\n" + "(1,6)\n" + "(2,5)\n" + "(3,5)\n"; compareResultsByLinesInMemory(expected, resultPath); }
@Test public void testCombiner() throws Exception { org.junit.Assume.assumeThat(mode, new IsEqual<TestExecutionMode>(TestExecutionMode.CLUSTER)); final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple2<IntWritable, IntWritable>> ds = HadoopTestData.getKVPairDataSet(env). map(new Mapper3()); DataSet<Tuple2<IntWritable, IntWritable>> counts = ds. groupBy(0). reduceGroup(new HadoopReduceCombineFunction<IntWritable, IntWritable, IntWritable, IntWritable>( new SumReducer(), new KeyChangingReducer())); String resultPath = tempFolder.newFile().toURI().toString(); counts.writeAsText(resultPath); env.execute(); String expected = "(0,5)\n"+ "(1,6)\n" + "(2,5)\n" + "(3,5)\n"; compareResultsByLinesInMemory(expected, resultPath); }
@Test public void getAccessControlList_delegatesToDataService() { when(permissionCheckingService.hasPermission(USER_NAME, CREDENTIAL_NAME, PermissionOperation.READ_ACL)) .thenReturn(false); List<PermissionEntry> expectedPermissionEntries = newArrayList(); when(permissionDataService.getPermissions(expectedCredential)) .thenReturn(expectedPermissionEntries); try { subject.getPermissions(expectedCredentialVersion, auditRecordParameters, CREDENTIAL_NAME); } catch (EntryNotFoundException e) { assertThat(e.getMessage(), IsEqual.equalTo("error.credential.invalid_access")); assertThat(auditRecordParameters.size(), IsEqual.equalTo(1)); assertThat(auditRecordParameters.get(0).getCredentialName(), IsEqual.equalTo(CREDENTIAL_NAME)); assertThat(auditRecordParameters.get(0).getAuditingOperationCode(), IsEqual.equalTo(ACL_ACCESS)); } }
@Test public void deleteAccessControlEntry_whenTheUserLacksPermission_throwsAnException() { when(permissionCheckingService.hasPermission(userContext.getActor(), CREDENTIAL_NAME, PermissionOperation.WRITE_ACL)) .thenReturn(false); when(permissionDataService.deletePermissions(CREDENTIAL_NAME, "other-actor")) .thenReturn(true); try { subject.deletePermissions(CREDENTIAL_NAME, "other-actor", auditRecordParameters); fail("should throw"); } catch (EntryNotFoundException e) { assertThat(e.getMessage(), IsEqual.equalTo("error.credential.invalid_access")); assertThat(auditRecordParameters.size(), equalTo(1)); assertThat(auditRecordParameters.get(0).getCredentialName(), equalTo(CREDENTIAL_NAME)); assertThat(auditRecordParameters.get(0).getAuditingOperationCode(), equalTo(ACL_DELETE)); } }
@Test public void deleteAccessControlEntry_whenTheUserIsTheSameAsActor_throwsAnException() { when(permissionCheckingService.hasPermission(userContext.getActor(), CREDENTIAL_NAME, PermissionOperation.WRITE_ACL)) .thenReturn(true); when(permissionDataService.deletePermissions(CREDENTIAL_NAME, userContext.getActor())) .thenReturn(true); try { subject.deletePermissions(CREDENTIAL_NAME, userContext.getActor(), auditRecordParameters); fail("should throw"); } catch (InvalidPermissionOperationException iaoe) { assertThat(iaoe.getMessage(), IsEqual.equalTo("error.permission.invalid_update_operation")); assertThat(auditRecordParameters.size(), equalTo(1)); assertThat(auditRecordParameters.get(0).getCredentialName(), equalTo(CREDENTIAL_NAME)); assertThat(auditRecordParameters.get(0).getAuditingOperationCode(), equalTo(ACL_DELETE)); } }
@Test public void verifyReturnsFalseIfPublicKeyIsZeroArray() { // Arrange: final CryptoEngine engine = this.getCryptoEngine(); final KeyPair kp = KeyPair.random(engine); final DsaSigner dsaSigner = this.getDsaSigner(kp); final byte[] input = org.nem.core.test.Utils.generateRandomBytes(); final Signature signature = dsaSigner.sign(input); final Ed25519DsaSigner dsaSignerWithZeroArrayPublicKey = Mockito.mock(Ed25519DsaSigner.class); final KeyPair keyPairWithZeroArrayPublicKey = Mockito.mock(KeyPair.class); Mockito.when(dsaSignerWithZeroArrayPublicKey.getKeyPair()) .thenReturn(keyPairWithZeroArrayPublicKey); Mockito.when(keyPairWithZeroArrayPublicKey.getPublicKey()) .thenReturn(new PublicKey(new byte[32])); Mockito.when(dsaSignerWithZeroArrayPublicKey.verify(input, signature)).thenCallRealMethod(); Mockito.when(dsaSignerWithZeroArrayPublicKey.isCanonicalSignature(signature)).thenReturn(true); // Act: final boolean result = dsaSignerWithZeroArrayPublicKey.verify(input, signature); // Assert (getKeyPair() would be called more than once if it got beyond the second check): Assert.assertThat(result, IsEqual.equalTo(false)); Mockito.verify(dsaSignerWithZeroArrayPublicKey, Mockito.times(1)).isCanonicalSignature(signature); Mockito.verify(dsaSignerWithZeroArrayPublicKey, Mockito.times(1)).getKeyPair(); }
@Test public void isCompatibleOnlyReturnsTrueForCompatibleAddresses() { // Arrange: final Map<String, Address> descToAddressMap = new HashMap<String, Address>() { { this.put("NON_BASE32_CHARS", Address.fromEncoded("TAAAAAAAAAA1BBBBBBBBBCCCCCCCCCCDDDDDDDDD")); this.put("UNKNOWN_NETWORK", Address.fromEncoded("YAAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDD")); this.put("COMPATIBLE", Address.fromEncoded("ZAAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDD")); this.put("NON_COMPATIBLE", Address.fromEncoded("NAAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDD")); } }; final NetworkInfo info = new NetworkInfo((byte)0xC8, 'Z', createNemesisBlockInfo()); // Assert: Assert.assertThat(info.isCompatible(descToAddressMap.get("NON_BASE32_CHARS")), IsEqual.equalTo(false)); Assert.assertThat(info.isCompatible(descToAddressMap.get("UNKNOWN_NETWORK")), IsEqual.equalTo(false)); Assert.assertThat(info.isCompatible(descToAddressMap.get("COMPATIBLE")), IsEqual.equalTo(true)); Assert.assertThat(info.isCompatible(descToAddressMap.get("NON_COMPATIBLE")), IsEqual.equalTo(false)); }
private static void assertValidNemVendorName(final String name) throws IOException { // Arrange: final Manifest manifest = new Manifest(); final Attributes attributes = manifest.getMainAttributes(); attributes.putValue("Manifest-Version", "1.0"); attributes.putValue("Implementation-Vendor", name); attributes.putValue("Implementation-Version", "test-version"); attributes.putValue("Implementation-Title", "test-title"); final byte[] bytes = MetaDataTestUtils.createJarBytes(manifest); try (final InputStream inputStream = new ByteArrayInputStream(bytes)) { final URL url = MetaDataTestUtils.createMockUrl("file://path/nem.jar", inputStream); final JarFacade facade = new JarFacade(url); // Assert: Assert.assertThat(facade.getName(), IsEqual.equalTo("nem.jar")); Assert.assertThat(facade.isWebStart(), IsEqual.equalTo(false)); Assert.assertThat(facade.getVersion(), IsEqual.equalTo("test-version")); Assert.assertThat(facade.getTitle(), IsEqual.equalTo("test-title")); } }
@Test public void initialDelayIsRespected() throws InterruptedException { // Arrange: final CountableFuture cf = new CountableFuture(); try (final AsyncTimer timer = createTimer(cf, TIME_UNIT, 10 * TIME_UNIT)) { // Arrange: Thread.sleep(TIME_HALF_UNIT); // Assert: Assert.assertThat(cf.getNumCalls(), IsEqual.equalTo(0)); // Arrange: Thread.sleep(3 * TIME_HALF_UNIT); // Assert: Assert.assertThat(cf.getNumCalls(), IsEqual.equalTo(1)); Assert.assertThat(timer.isStopped(), IsEqual.equalTo(false)); } }