@Test public void testRequestsReuseSameConnectionIfThereIsNoError() throws Exception { when(clientFactory.newClient(Matchers.<EurekaEndpoint>anyVararg())).thenReturn(clusterDelegates.get(0)); when(requestExecutor.execute(clusterDelegates.get(0))).thenReturn(EurekaHttpResponse.status(200)); // First request creates delegate, second reuses it for (int i = 0; i < 3; i++) { EurekaHttpResponse<Void> httpResponse = retryableClient.execute(requestExecutor); assertThat(httpResponse.getStatusCode(), is(equalTo(200))); } verify(clientFactory, times(1)).newClient(Matchers.<EurekaEndpoint>anyVararg()); verify(requestExecutor, times(3)).execute(clusterDelegates.get(0)); }
@Test public void withScopeResolver() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ComponentScanWithScopeResolver.class); // custom scope annotation makes the bean prototype scoped. subsequent calls // to getBean should return distinct instances. assertThat(ctx.getBean(CustomScopeAnnotationBean.class), not(sameInstance(ctx.getBean(CustomScopeAnnotationBean.class)))); assertThat(ctx.containsBean("scannedComponent"), is(false)); }
/** * Evaluate the JSON path expression against the supplied {@code content} * and assert that the resulting value is a {@link Boolean}. * @param content the JSON content * @since 4.2.1 */ public void assertValueIsBoolean(String content) { Object value = assertExistsAndReturn(content); MatcherAssert.assertThat(failureReason("a boolean", value), value, CoreMatchers.instanceOf(Boolean.class)); }
@After public void verifyCustomRequestAttributesAreRestored() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); assertThat(requestAttributes, instanceOf(ServletRequestAttributes.class)); HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); assertThat(request.getAttribute(FROM_CUSTOM_MOCK), is(FROM_CUSTOM_MOCK)); assertThat(request.getAttribute(FROM_MVC_TEST_DEFAULT), is(nullValue())); assertThat(request.getAttribute(FROM_MVC_TEST_MOCK), is(nullValue())); RequestContextHolder.resetRequestAttributes(); this.wac.close(); }
@Test void invalidExpressionEvaluationType() { String methodName = "nonBooleanOrStringExpression"; IllegalStateException exception = assertThrows(IllegalStateException.class, () -> condition.evaluateExecutionCondition(buildExtensionContext(methodName))); Method method = ReflectionUtils.findMethod(getClass(), methodName); assertThat(exception.getMessage(), is(equalTo("@DisabledIf(\"#{6 * 7}\") on " + method + " must evaluate to a String or a Boolean, not java.lang.Integer"))); }
@Test public void shouldFailOnECDSA384SigningWhenProvidedPrivateKeyIsNull() throws Exception { exception.expect(SignatureGenerationException.class); exception.expectMessage("The Token's Signature couldn't be generated when signing using the Algorithm: SHA384withECDSA"); exception.expectCause(isA(IllegalStateException.class)); exception.expectCause(hasMessage(is("The given Private Key is null."))); ECDSAKeyProvider provider = mock(ECDSAKeyProvider.class); when(provider.getPrivateKey()).thenReturn(null); Algorithm algorithm = Algorithm.ECDSA384(provider); algorithm.sign(new byte[0], new byte[0]); }
@Test public void testMultiClasses() { Class expectedClass1 = TestZuulFilter.class; Class expectedClass2 = TestZuulFilter2.class; when(configuration.getStringArray(eq("zuul.filters.classes"))).thenReturn(new String[]{"com.netflix.zuul.init.TestZuulFilter", "com.netflix.zuul.init2.TestZuulFilter2"}); when(configuration.getStringArray(eq("zuul.filters.packages"))).thenReturn(new String[0]); String[] classNames = module.findClassNames(configuration); assertThat(classNames.length, equalTo(2)); assertThat(classNames[0], equalTo(expectedClass1.getCanonicalName())); assertThat(classNames[1], equalTo(expectedClass2.getCanonicalName())); }
@Test public void shouldNotLeakTransactionOnSecurityContextFreezeFailure() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); LoginContext loginContext = mock( LoginContext.class ); when( loginContext.authorize( any(), any() ) ).thenThrow( new AuthorizationExpiredException( "Freeze failed." ) ); assertException(() -> kernelTransactions.newInstance(KernelTransaction.Type.explicit, loginContext, 0L), AuthorizationExpiredException.class, "Freeze failed."); assertThat("We should not have any transaction", kernelTransactions.activeTransactions(), is(empty())); }
@Test public void testGetVariablesWithNullValue() { when(caseServiceMock.getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true)).thenReturn(EXAMPLE_VARIABLES_WITH_NULL_VALUE); Response response = given().pathParam("id", MockProvider.EXAMPLE_CASE_INSTANCE_ID) .then().expect().statusCode(Status.OK.getStatusCode()) .body(EXAMPLE_ANOTHER_VARIABLE_KEY, notNullValue()) .body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".value", nullValue()) .body(EXAMPLE_ANOTHER_VARIABLE_KEY + ".type", equalTo("Null")) .when().get(CASE_INSTANCE_VARIABLES_URL); Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); verify(caseServiceMock).getVariablesTyped(MockProvider.EXAMPLE_CASE_INSTANCE_ID, true); }
@Test public void testGetLocalVariables() { when(taskServiceMock.getVariablesLocalTyped(EXAMPLE_TASK_ID, true)).thenReturn(EXAMPLE_VARIABLES); Response response = given().pathParam("id", EXAMPLE_TASK_ID) .header("accept", MediaType.APPLICATION_JSON) .then().expect().statusCode(Status.OK.getStatusCode()) .body(EXAMPLE_VARIABLE_KEY, notNullValue()) .body(EXAMPLE_VARIABLE_KEY + ".value", equalTo(EXAMPLE_VARIABLE_VALUE.getValue())) .body(EXAMPLE_VARIABLE_KEY + ".type", equalTo(VariableTypeHelper.toExpectedValueTypeName(EXAMPLE_VARIABLE_VALUE.getType()))) .when().get(SINGLE_TASK_VARIABLES_URL); Assert.assertEquals("Should return exactly one variable", 1, response.jsonPath().getMap("").size()); }
@Test public void allowedOptionsIncludesPatchMethod() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "OPTIONS", "/foo"); MockHttpServletResponse response = spy(new MockHttpServletResponse()); DispatcherServlet servlet = new DispatcherServlet(); servlet.setDispatchOptionsRequest(false); servlet.service(request, response); verify(response, never()).getHeader(anyString()); // SPR-10341 assertThat(response.getHeader("Allow"), equalTo("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH")); }
@Test public void proxyingWorksIfInfoReturnsNullEntityManagerInterface() { EntityManagerFactory emf = mock(EntityManagerFactory.class, withSettings().extraInterfaces(EntityManagerFactoryInfo.class)); // EntityManagerFactoryInfo.getEntityManagerInterface returns null assertThat(SharedEntityManagerCreator.createSharedEntityManager(emf), is(notNullValue())); }
@Test public void testGetNonExistingSingleDeployment() { when(mockDeploymentQuery.deploymentId(NON_EXISTING_DEPLOYMENT_ID)).thenReturn(mockDeploymentQuery); when(mockDeploymentQuery.singleResult()).thenReturn(null); given().pathParam("id", NON_EXISTING_DEPLOYMENT_ID) .then().expect().statusCode(Status.NOT_FOUND.getStatusCode()) .body(containsString("Deployment with id '" + NON_EXISTING_DEPLOYMENT_ID + "' does not exist")) .when().get(DEPLOYMENT_URL); }
@Test public void testMissingAuthorization() { String message = "not authorized"; when(historicProcessInstanceReport.list()).thenThrow(new AuthorizationException(message)); given() .then().expect() .statusCode(Status.FORBIDDEN.getStatusCode()) .contentType(ContentType.JSON) .body("type", equalTo(AuthorizationException.class.getSimpleName())) .body("message", equalTo(message)) .when().get(HISTORIC_REPORT_URL); }
@Test public void shouldReturnNullSigningKeyIdIfCreatedWithDefaultProvider() throws Exception { ECPublicKey publicKey = mock(ECPublicKey.class); ECPrivateKey privateKey = mock(ECPrivateKey.class); ECDSAKeyProvider provider = ECDSAAlgorithm.providerForKeys(publicKey, privateKey); Algorithm algorithm = new ECDSAAlgorithm("some-alg", "some-algorithm", 32, provider); assertThat(algorithm.getSigningKeyId(), is(nullValue())); }
@Test public void shouldRespondWithMetadataToDiscardAll() throws Throwable { // When negotiateBoltV3(); connection.send( util.chunk( new RunMessage( "UNWIND [1,2,3] AS a RETURN a, a * a AS a_squared" ), DiscardAllMessage.INSTANCE ) ); // Then Matcher<Map<? extends String,?>> entryTypeMatcher = hasEntry( is( "type" ), equalTo( "r" ) ); Matcher<Map<? extends String,?>> entryFieldsMatcher = hasEntry( is( "fields" ), equalTo( asList( "a", "a_squared" ) ) ); assertThat( connection, util.eventuallyReceives( msgSuccess( allOf( entryFieldsMatcher, hasKey( "t_first" ) ) ), msgSuccess( allOf( entryTypeMatcher, hasKey( "t_last" ), hasKey( "bookmark" ) ) ) ) ); }
@Test public void testGetNonExistingForm() { when(formServiceMock.getTaskFormData(anyString())).thenThrow(new ProcessEngineException("Expected exception: task does not exist.")); given().pathParam("id", NON_EXISTING_ID) .header("accept", MediaType.APPLICATION_JSON) .then().expect().statusCode(Status.BAD_REQUEST.getStatusCode()).contentType(ContentType.JSON) .body("type", equalTo(RestException.class.getSimpleName())) .body("message", equalTo("Cannot get form for task " + NON_EXISTING_ID)) .when().get(TASK_FORM_URL); }
@Test public void renderSimpleBeanWithFilters() throws Exception { TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered(); bean.setProperty1("value"); bean.setProperty2("value"); Map<String, Object> model = new HashMap<>(); model.put("bindingResult", mock(BindingResult.class, "binding_result")); model.put("foo", bean); FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter", SimpleBeanPropertyFilter.serializeAllExcept("property2")); model.put(FilterProvider.class.getName(), filters); view.setUpdateContentLength(true); view.render(model, request, response); String content = response.getContentAsString(); assertTrue(content.length() > 0); assertEquals(content.length(), response.getContentLength()); assertThat(content, containsString("\"property1\":\"value\"")); assertThat(content, not(containsString("\"property2\":\"value\""))); assertFalse(content.contains(FilterProvider.class.getName())); }
@Test public void withOptionArgsOnly() { CommandLinePropertySource<?> ps = new SimpleCommandLinePropertySource("--o1=v1", "--o2"); assertThat(ps.containsProperty("o1"), is(true)); assertThat(ps.containsProperty("o2"), is(true)); assertThat(ps.containsProperty("o3"), is(false)); assertThat(ps.getProperty("o1"), equalTo("v1")); assertThat(ps.getProperty("o2"), equalTo("")); assertThat(ps.getProperty("o3"), nullValue()); }
private void assertBeanPropertyValueOf(String propertyName, String expected, DefaultListableBeanFactory factory) { BeanDefinition bean = factory.getBeanDefinition(expected); PropertyValue value = bean.getPropertyValues().getPropertyValue(propertyName); assertThat(value, is(notNullValue())); assertThat(value.getValue().toString(), is(expected)); }