@Override protected void succeeded(Description description) { try { assertThat(spans.poll(100, TimeUnit.MILLISECONDS)) .withFailMessage("Span remaining in queue. Check for redundant reporting") .isNull(); } catch (InterruptedException e) { e.printStackTrace(); } } };
/** Call this to block until a span was reported */ protected Span takeSpan() throws InterruptedException { Span result = spans.poll(3, TimeUnit.SECONDS); assertThat(result) .withFailMessage("Span was not reported") .isNotNull(); assertThat(result.annotations()) .extracting(Annotation::value) .doesNotContain(CONTEXT_LEAK); return result; }
/** Runs the type in a new classloader that recreates brave classes */ public static void assertRunIsUnloadable(Class<? extends Runnable> runnable, ClassLoader parent) { // We can't use log4j2's log manager. More importantly, we want to make sure loggers don't hold // our test classloader from being collected. System.setProperty("java.util.logging.manager", LogManager.class.getName()); assertThat(LogManager.getLogManager().getClass()).isSameAs(LogManager.class); WeakReference<ClassLoader> loader; try { loader = invokeRunFromNewClassLoader(runnable, parent); } catch (Exception e) { throw new AssertionError(e); } blockOnGC(); assertThat(loader.get()) .withFailMessage(runnable + " includes state that couldn't be garbage collected") .isNull(); }
@Test public void testContextIsResetEvenIfExceptionOccurs() throws Exception { // Setup client-side context Authentication clientSideAuthentication = new UsernamePasswordAuthenticationToken( "rod", "koala"); SecurityContextHolder.getContext().setAuthentication(clientSideAuthentication); ContextPropagatingRemoteInvocation remoteInvocation = getRemoteInvocation(); try { // Set up the wrong arguments. remoteInvocation.setArguments(new Object[] {}); remoteInvocation.invoke(TargetObject.class.newInstance()); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } assertThat( SecurityContextHolder.getContext().getAuthentication()).withFailMessage( "Authentication must be null").isNull(); }
@Test public void testFull() throws Exception { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "user", "password", AuthorityUtils.createAuthorityList("ROLE_ONE")); assertThat(jaasProvider.supports(UsernamePasswordAuthenticationToken.class)).isTrue(); Authentication auth = jaasProvider.authenticate(token); assertThat(jaasProvider.getAuthorityGranters()).isNotNull(); assertThat(jaasProvider.getCallbackHandlers()).isNotNull(); assertThat(jaasProvider.getLoginConfig()).isNotNull(); assertThat(jaasProvider.getLoginContextName()).isNotNull(); Collection<? extends GrantedAuthority> list = auth.getAuthorities(); Set<String> set = AuthorityUtils.authorityListToSet(list); assertThat(set.contains("ROLE_ONE")).withFailMessage("GrantedAuthorities should not contain ROLE_ONE").isFalse(); assertThat(set.contains("ROLE_TEST1")).withFailMessage("GrantedAuthorities should contain ROLE_TEST1").isTrue(); assertThat(set.contains("ROLE_TEST2")).withFailMessage("GrantedAuthorities should contain ROLE_TEST2").isTrue(); boolean foundit = false; for (GrantedAuthority a : list) { if (a instanceof JaasGrantedAuthority) { JaasGrantedAuthority grant = (JaasGrantedAuthority) a; assertThat(grant.getPrincipal()).withFailMessage("Principal was null on JaasGrantedAuthority").isNotNull(); foundit = true; } } assertThat(foundit).as("Could not find a JaasGrantedAuthority").isTrue(); assertThat(eventCheck.successEvent).as("Success event should be fired").isNotNull(); assertThat(eventCheck.successEvent.getAuthentication()).withFailMessage("Auth objects should be equal").isEqualTo(auth); assertThat(eventCheck.failedEvent).as("Failure event should not be fired").isNull(); }
@Test public void cacheIsInjectedIntoAuthenticationProvider() { setContext("<authentication-manager>" + " <authentication-provider>" + " <jdbc-user-service cache-ref='userCache' data-source-ref='dataSource'/>" + " </authentication-provider>" + "</authentication-manager>" + DATA_SOURCE + USER_CACHE_XML); ProviderManager mgr = (ProviderManager) appContext .getBean(BeanIds.AUTHENTICATION_MANAGER); DaoAuthenticationProvider provider = (DaoAuthenticationProvider) mgr .getProviders().get(0); assertThat(appContext.getBean("userCache")).isSameAs(provider.getUserCache()); provider.authenticate(new UsernamePasswordAuthenticationToken("rod", "koala")); assertThat(provider .getUserCache().getUserFromCache("rod")).isNotNull().withFailMessage("Cache should contain user after authentication"); }
@Test public void requestWhenConnectMessageAndUsingSockJsThenUsesCsrfTokenHandshakeInterceptor() throws Exception { this.spring.configLocations(xml("SyncSockJsConfig")).autowire(); WebApplicationContext context = (WebApplicationContext) this.spring.getContext(); MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build(); String csrfAttributeName = CsrfToken.class.getName(); String customAttributeName = this.getClass().getName(); MvcResult result = mvc.perform(get("/app/289/tpyx6mde/websocket") .requestAttr(csrfAttributeName, this.token) .sessionAttr(customAttributeName, "attributeValue")) .andReturn(); CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName); String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName); String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName); assertThat(handshakeToken).isEqualTo(this.token) .withFailMessage("CsrfToken is populated"); assertThat(handshakeValue).isEqualTo(sessionValue) .withFailMessage("Explicitly listed session variables are not overridden"); }
@Test public void requestWhenConnectMessageThenUsesCsrfTokenHandshakeInterceptor() throws Exception { this.spring.configLocations(xml("SyncConfig")).autowire(); WebApplicationContext context = (WebApplicationContext) this.spring.getContext(); MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build(); String csrfAttributeName = CsrfToken.class.getName(); String customAttributeName = this.getClass().getName(); MvcResult result = mvc.perform(get("/app") .requestAttr(csrfAttributeName, this.token) .sessionAttr(customAttributeName, "attributeValue")) .andReturn(); CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName); String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName); String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName); assertThat(handshakeToken).isEqualTo(this.token) .withFailMessage("CsrfToken is populated"); assertThat(handshakeValue).isEqualTo(sessionValue) .withFailMessage("Explicitly listed session variables are not overridden"); }
.getContext().getAuthentication()).isNotNull().withFailMessage("Authentication should not be null"); verify(chain).doFilter(request, response); verifyZeroInteractions(successHandler);
@Override protected void succeeded(Description description) { try { assertThat(spans.poll(100, TimeUnit.MILLISECONDS)) .withFailMessage("Span remaining in queue. Check for redundant reporting") .isNull(); } catch (InterruptedException e) { e.printStackTrace(); } } };
/** Call this to block until a span was reported */ protected Span takeSpan() throws InterruptedException { Span result = spans.poll(3, TimeUnit.SECONDS); assertThat(result) .withFailMessage("Span was not reported") .isNotNull(); assertThat(result.annotations()) .extracting(Annotation::value) .doesNotContain(CONTEXT_LEAK); return result; }
@Test public void testRejectInvalidHeloAuthUser() throws Exception { MailAddress mailAddress = new MailAddress("test@localhost"); SMTPSession session = setupMockSession(INVALID_HOST,false,true,"valid@user",mailAddress); ResolvableEhloHeloHandler handler = createHandler(); handler.doHelo(session, INVALID_HOST); assertThat(session.getAttachment(BAD_EHLO_HELO, Transaction)).withFailMessage("Value stored").isNotNull(); HookReturnCode result = handler.doRcpt(session,null, mailAddress).getResult(); assertThat(HookReturnCode.deny()).describedAs("Reject").isEqualTo(result); }
@Test public void testRejectInvalidHelo() throws Exception { MailAddress mailAddress = new MailAddress("test@localhost"); SMTPSession session = setupMockSession(INVALID_HOST,false,false,null,mailAddress); ResolvableEhloHeloHandler handler = createHandler(); handler.doHelo(session, INVALID_HOST); assertThat(session.getAttachment(BAD_EHLO_HELO, Transaction)).withFailMessage("Invalid HELO").isNotNull(); HookReturnCode result = handler.doRcpt(session, MaybeSender.nullSender(), mailAddress).getResult(); assertThat(HookReturnCode.deny()).describedAs("Reject").isEqualTo(result); }
@Test public void testBlackListedTextPresent() throws Exception { DNSRBLHandler rbl = createHandler(); setupMockedSMTPSession(new MailAddress("any@domain")); rbl.setBlacklist(new String[] { "bl.spamcop.net." }); rbl.setGetDetail(true); rbl.doRcpt(mockedSMTPSession, MaybeSender.nullSender(), new MailAddress("test@localhost")); assertThat(mockedSMTPSession.getAttachment(RBL_DETAIL_MAIL_ATTRIBUTE_NAME, State.Connection)).describedAs("Details").isEqualTo("Blocked - see http://www.spamcop.net/bl.shtml?127.0.0.2"); assertThat(mockedSMTPSession.getAttachment(RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME, Connection)).withFailMessage("Blocked").isNotNull(); }
@Test public void testRelayAllowed() throws Exception { DNSRBLHandler rbl = createHandler(); setRelayingAllowed(true); setupMockedSMTPSession(new MailAddress("any@domain")); rbl.setBlacklist(new String[] { "bl.spamcop.net." }); rbl.setGetDetail(true); rbl.doRcpt(mockedSMTPSession, MaybeSender.nullSender(), new MailAddress("test@localhost")); assertThat(mockedSMTPSession.getAttachment(RBL_DETAIL_MAIL_ATTRIBUTE_NAME, Connection)).withFailMessage("No details").isNull(); assertThat(mockedSMTPSession.getAttachment(RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME, Connection)).withFailMessage("Not blocked").isNull(); }
@Test public void testNotRejectValidHelo() throws Exception { MailAddress mailAddress = new MailAddress("test@localhost"); SMTPSession session = setupMockSession(VALID_HOST,false,false,null,mailAddress); ResolvableEhloHeloHandler handler = createHandler(); handler.doHelo(session, VALID_HOST); assertThat(session.getAttachment(BAD_EHLO_HELO, Transaction)).withFailMessage("Valid HELO").isNull(); HookReturnCode result = handler.doRcpt(session,null, mailAddress).getResult(); assertThat(HookReturnCode.declined()).describedAs("Not reject").isEqualTo(result); }
@Test public void testNotBlackListed() throws Exception { DNSRBLHandler rbl = createHandler(); setRemoteIp("192.168.0.1"); setupMockedSMTPSession(new MailAddress("any@domain")); rbl.setBlacklist(new String[] { "bl.spamcop.net." }); rbl.setGetDetail(true); rbl.doRcpt(mockedSMTPSession, MaybeSender.nullSender(), new MailAddress("test@localhost")); assertThat(mockedSMTPSession.getAttachment(RBL_DETAIL_MAIL_ATTRIBUTE_NAME, Connection)).withFailMessage("No details").isNull(); assertThat(mockedSMTPSession.getAttachment(RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME, Connection)).withFailMessage("Not blocked").isNull(); }
@Test public void testSpam() throws Exception { SMTPSession session = setupMockedSMTPSession(setupMockedMail(setupMockedMimeMessage(MockSpamd.GTUBE))); SpamAssassinHandler handler = new SpamAssassinHandler(new NoopMetricFactory()); handler.setSpamdHost(SPAMD_HOST); handler.setSpamdPort(spamd.getPort()); handler.setSpamdRejectionHits(2000.0); HookResult response = handler.onMessage(session, mockedMail); assertThat(HookReturnCode.declined()).describedAs("Email was not rejected").isEqualTo(response.getResult()); assertThat("YES").describedAs("email was spam").isEqualTo(mockedMail.getAttribute(SpamAssassinResult.FLAG_MAIL_ATTRIBUTE_NAME)); assertThat(mockedMail.getAttribute(STATUS_MAIL_ATTRIBUTE_NAME)).withFailMessage("spam hits").isNotNull(); }
@Test public void testNonSpam() throws Exception { SMTPSession session = setupMockedSMTPSession(setupMockedMail(setupMockedMimeMessage("test"))); SpamAssassinHandler handler = new SpamAssassinHandler(new NoopMetricFactory()); handler.setSpamdHost(SPAMD_HOST); handler.setSpamdPort(spamd.getPort()); handler.setSpamdRejectionHits(200.0); HookResult response = handler.onMessage(session, mockedMail); assertThat(HookReturnCode.declined()).describedAs("Email was not rejected").isEqualTo(response.getResult()); assertThat("NO").describedAs("email was not spam").isEqualTo(mockedMail.getAttribute(SpamAssassinResult.FLAG_MAIL_ATTRIBUTE_NAME)); assertThat(mockedMail.getAttribute(STATUS_MAIL_ATTRIBUTE_NAME)).withFailMessage("spam hits").isNotNull(); }
@Test public void testWhiteListed() throws Exception { DNSRBLHandler rbl = createHandler(); setRemoteIp("127.0.0.2"); setupMockedSMTPSession(new MailAddress("any@domain")); rbl.setWhitelist(new String[] { "bl.spamcop.net." }); rbl.setGetDetail(true); rbl.doRcpt(mockedSMTPSession, null, new MailAddress("test@localhost")); assertThat(mockedSMTPSession.getAttachment(RBL_DETAIL_MAIL_ATTRIBUTE_NAME, Connection)).isNull(); assertThat(mockedSMTPSession.getAttachment(RBL_BLOCKLISTED_MAIL_ATTRIBUTE_NAME, Connection)).withFailMessage("Not blocked").isNull(); }