From cf3cb1818802aba0678bc4ff1aa732be785a4a2b Mon Sep 17 00:00:00 2001 From: slfan1989 Date: Sun, 20 Apr 2025 13:13:08 +0800 Subject: [PATCH 1/2] HADOOP-19414. [JDK17] Upgrade JUnit from 4 to 5 in hadoop-auth. --- hadoop-common-project/hadoop-auth/pom.xml | 5 + .../client/AuthenticatorTestCase.java | 25 +- .../client/TestAuthenticatedURL.java | 71 ++- .../client/TestPseudoAuthenticator.java | 16 +- .../server/TestAuthenticationFilter.java | 556 +++++++++--------- .../server/TestAuthenticationToken.java | 19 +- .../TestPseudoAuthenticationHandler.java | 40 +- .../authentication/util/TestAuthToken.java | 58 +- .../util/TestCertificateUtil.java | 10 +- .../util/TestFileSignerSecretProvider.java | 23 +- .../util/TestJaasConfiguration.java | 30 +- .../authentication/util/TestKerberosName.java | 46 +- .../authentication/util/TestKerberosUtil.java | 72 ++- .../util/TestRandomSignerSecretProvider.java | 30 +- .../TestRolloverSignerSecretProvider.java | 31 +- .../authentication/util/TestSigner.java | 43 +- .../util/TestStringSignerSecretProvider.java | 12 +- .../util/TestZKSignerSecretProvider.java | 137 ++--- 18 files changed, 641 insertions(+), 583 deletions(-) diff --git a/hadoop-common-project/hadoop-auth/pom.xml b/hadoop-common-project/hadoop-auth/pom.xml index c96383ae291ab..98173c16f7e79 100644 --- a/hadoop-common-project/hadoop-auth/pom.xml +++ b/hadoop-common-project/hadoop-auth/pom.xml @@ -205,6 +205,11 @@ guava test + + org.assertj + assertj-core + test + diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/AuthenticatorTestCase.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/AuthenticatorTestCase.java index 969cd7b6864e4..14538b873c803 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/AuthenticatorTestCase.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/AuthenticatorTestCase.java @@ -13,6 +13,11 @@ */ package org.apache.hadoop.security.authentication.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.hadoop.security.authentication.server.AuthenticationFilter; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; @@ -55,8 +60,6 @@ import java.util.EnumSet; import java.util.Properties; -import org.junit.Assert; - public class AuthenticatorTestCase { private Server server; private String host = null; @@ -170,11 +173,11 @@ protected void _testAuthentication(Authenticator authenticator, boolean doPost) try { URL url = new URL(getBaseURL()); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); - Assert.assertFalse(token.isSet()); + assertFalse(token.isSet()); TestConnectionConfigurator connConf = new TestConnectionConfigurator(); AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf); HttpURLConnection conn = aUrl.openConnection(url, token); - Assert.assertTrue(connConf.invoked); + assertTrue(connConf.invoked); String tokenStr = token.toString(); if (doPost) { conn.setRequestMethod("POST"); @@ -186,18 +189,18 @@ protected void _testAuthentication(Authenticator authenticator, boolean doPost) writer.write(POST); writer.close(); } - Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); + assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); if (doPost) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String echo = reader.readLine(); - Assert.assertEquals(POST, echo); - Assert.assertNull(reader.readLine()); + assertEquals(POST, echo); + assertNull(reader.readLine()); } aUrl = new AuthenticatedURL(); conn = aUrl.openConnection(url, token); conn.connect(); - Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); - Assert.assertEquals(tokenStr, token.toString()); + assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); + assertEquals(tokenStr, token.toString()); } finally { stop(); } @@ -233,7 +236,7 @@ private void doHttpClientRequest(HttpClient httpClient, HttpUriRequest request) try { response = httpClient.execute(request); final int httpStatus = response.getStatusLine().getStatusCode(); - Assert.assertEquals(HttpURLConnection.HTTP_OK, httpStatus); + assertEquals(HttpURLConnection.HTTP_OK, httpStatus); } finally { if (response != null) EntityUtils.consumeQuietly(response.getEntity()); } @@ -255,7 +258,7 @@ protected void _testAuthenticationHttpClient(Authenticator authenticator, boolea // Important that the entity is not repeatable -- this means if // we have to renegotiate (e.g. b/c the cookie wasn't handled properly) // the test will fail. - Assert.assertFalse(entity.isRepeatable()); + assertFalse(entity.isRepeatable()); post.setEntity(entity); doHttpClientRequest(httpClient, post); } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestAuthenticatedURL.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestAuthenticatedURL.java index 5b3de5208f49a..ea95481a64011 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestAuthenticatedURL.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestAuthenticatedURL.java @@ -13,8 +13,17 @@ */ package org.apache.hadoop.security.authentication.client; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.net.HttpURLConnection; @@ -29,112 +38,112 @@ public class TestAuthenticatedURL { @Test public void testToken() throws Exception { AuthenticatedURL.Token token = new AuthenticatedURL.Token(); - Assert.assertFalse(token.isSet()); + assertFalse(token.isSet()); token = new AuthenticatedURL.Token("foo"); - Assert.assertTrue(token.isSet()); - Assert.assertEquals("foo", token.toString()); + assertTrue(token.isSet()); + assertEquals("foo", token.toString()); } @Test public void testInjectToken() throws Exception { - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); + HttpURLConnection conn = mock(HttpURLConnection.class); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); token.set("foo"); AuthenticatedURL.injectToken(conn, token); - Mockito.verify(conn).addRequestProperty(Mockito.eq("Cookie"), Mockito.anyString()); + verify(conn).addRequestProperty(eq("Cookie"), anyString()); } @Test public void testExtractTokenOK() throws Exception { - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); + HttpURLConnection conn = mock(HttpURLConnection.class); - Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map> headers = new HashMap>(); List cookies = new ArrayList(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); - Mockito.when(conn.getHeaderFields()).thenReturn(headers); + when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.extractToken(conn, token); - Assert.assertEquals(tokenStr, token.toString()); + assertEquals(tokenStr, token.toString()); } @Test public void testExtractTokenFail() throws Exception { - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); + HttpURLConnection conn = mock(HttpURLConnection.class); - Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED); + when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED); String tokenStr = "foo"; Map> headers = new HashMap>(); List cookies = new ArrayList(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); - Mockito.when(conn.getHeaderFields()).thenReturn(headers); + when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); token.set("bar"); try { AuthenticatedURL.extractToken(conn, token); - Assert.fail(); + fail(); } catch (AuthenticationException ex) { // Expected - Assert.assertFalse(token.isSet()); + assertFalse(token.isSet()); } catch (Exception ex) { - Assert.fail(); + fail(); } } @Test public void testExtractTokenCookieHeader() throws Exception { - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); + HttpURLConnection conn = mock(HttpURLConnection.class); - Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map> headers = new HashMap<>(); List cookies = new ArrayList<>(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("Set-Cookie", cookies); - Mockito.when(conn.getHeaderFields()).thenReturn(headers); + when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.extractToken(conn, token); - Assert.assertTrue(token.isSet()); + assertTrue(token.isSet()); } @Test public void testExtractTokenLowerCaseCookieHeader() throws Exception { - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); + HttpURLConnection conn = mock(HttpURLConnection.class); - Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); String tokenStr = "foo"; Map> headers = new HashMap<>(); List cookies = new ArrayList<>(); cookies.add(AuthenticatedURL.AUTH_COOKIE + "=" + tokenStr); headers.put("set-cookie", cookies); - Mockito.when(conn.getHeaderFields()).thenReturn(headers); + when(conn.getHeaderFields()).thenReturn(headers); AuthenticatedURL.Token token = new AuthenticatedURL.Token(); AuthenticatedURL.extractToken(conn, token); - Assert.assertTrue(token.isSet()); + assertTrue(token.isSet()); } @Test public void testConnectionConfigurator() throws Exception { - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); - Mockito.when(conn.getResponseCode()). + HttpURLConnection conn = mock(HttpURLConnection.class); + when(conn.getResponseCode()). thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED); ConnectionConfigurator connConf = - Mockito.mock(ConnectionConfigurator.class); + mock(ConnectionConfigurator.class); Mockito.when(connConf.configure(Mockito.any())). thenReturn(conn); @@ -142,15 +151,15 @@ public void testConnectionConfigurator() throws Exception { AuthenticatedURL aURL = new AuthenticatedURL(authenticator, connConf); aURL.openConnection(new URL("http://foo"), new AuthenticatedURL.Token()); - Mockito.verify(connConf).configure(Mockito.any()); + verify(connConf).configure(Mockito.any()); } @Test public void testGetAuthenticator() throws Exception { - Authenticator authenticator = Mockito.mock(Authenticator.class); + Authenticator authenticator = mock(Authenticator.class); AuthenticatedURL aURL = new AuthenticatedURL(authenticator); - Assert.assertEquals(authenticator, aURL.getAuthenticator()); + assertEquals(authenticator, aURL.getAuthenticator()); } } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestPseudoAuthenticator.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestPseudoAuthenticator.java index 3a5764b6ca447..43f38f2594e26 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestPseudoAuthenticator.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/client/TestPseudoAuthenticator.java @@ -13,10 +13,12 @@ */ package org.apache.hadoop.security.authentication.client; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import org.apache.hadoop.security.authentication.server.AuthenticationFilter; import org.apache.hadoop.security.authentication.server.PseudoAuthenticationHandler; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.net.HttpURLConnection; import java.net.URL; @@ -34,7 +36,7 @@ private Properties getAuthenticationHandlerConfiguration(boolean anonymousAllowe @Test public void testGetUserName() throws Exception { PseudoAuthenticator authenticator = new PseudoAuthenticator(); - Assert.assertEquals(System.getProperty("user.name"), authenticator.getUserName()); + assertEquals(System.getProperty("user.name"), authenticator.getUserName()); } @Test @@ -47,7 +49,7 @@ public void testAnonymousAllowed() throws Exception { URL url = new URL(auth.getBaseURL()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); - Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); + assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode()); } finally { auth.stop(); } @@ -63,9 +65,9 @@ public void testAnonymousDisallowed() throws Exception { URL url = new URL(auth.getBaseURL()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); - Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); - Assert.assertTrue(conn.getHeaderFields().containsKey("WWW-Authenticate")); - Assert.assertEquals("Authentication required", conn.getResponseMessage()); + assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode()); + assertTrue(conn.getHeaderFields().containsKey("WWW-Authenticate")); + assertEquals("Authentication required", conn.getResponseMessage()); } finally { auth.stop(); } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationFilter.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationFilter.java index b0066abbdd3cf..e2d68b307a108 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationFilter.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationFilter.java @@ -39,15 +39,27 @@ import org.apache.hadoop.security.authentication.util.Signer; import org.apache.hadoop.security.authentication.util.SignerSecretProvider; import org.apache.hadoop.security.authentication.util.StringSignerSecretProviderCreator; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; +import org.junit.jupiter.api.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.reset; public class TestAuthenticationFilter { @@ -57,35 +69,37 @@ public class TestAuthenticationFilter { @Test public void testGetConfiguration() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn(""); - Mockito.when(config.getInitParameter("a")).thenReturn("A"); - Mockito.when(config.getInitParameterNames()).thenReturn(new Vector(Arrays.asList("a")).elements()); + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn(""); + when(config.getInitParameter("a")).thenReturn("A"); + when(config.getInitParameterNames()).thenReturn( + new Vector(Arrays.asList("a")).elements()); Properties props = filter.getConfiguration("", config); - Assert.assertEquals("A", props.getProperty("a")); + assertEquals("A", props.getProperty("a")); - config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("foo"); - Mockito.when(config.getInitParameter("foo.a")).thenReturn("A"); - Mockito.when(config.getInitParameterNames()).thenReturn(new Vector(Arrays.asList("foo.a")).elements()); + config = mock(FilterConfig.class); + when(config.getInitParameter(AuthenticationFilter.CONFIG_PREFIX)).thenReturn("foo"); + when(config.getInitParameter("foo.a")).thenReturn("A"); + when(config.getInitParameterNames()).thenReturn( + new Vector(Arrays.asList("foo.a")).elements()); props = filter.getConfiguration("foo.", config); - Assert.assertEquals("A", props.getProperty("a")); + assertEquals("A", props.getProperty("a")); } @Test public void testInitEmpty() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameterNames()).thenReturn(new Vector().elements()); + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameterNames()).thenReturn(new Vector().elements()); filter.init(config); - Assert.fail(); + fail(); } catch (ServletException ex) { // Expected - Assert.assertEquals("Authentication type must be specified: simple|kerberos|", + assertEquals("Authentication type must be specified: simple|kerberos|", ex.getMessage()); } catch (Exception ex) { - Assert.fail(); + fail(); } finally { filter.destroy(); } @@ -157,25 +171,25 @@ public void testFallbackToRandomSecretProvider() throws Exception { // minimal configuration & simple auth handler (Pseudo) AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); - Mockito.when(config.getInitParameter( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); + when(config.getInitParameter( AuthenticationFilter.AUTH_TOKEN_VALIDITY)).thenReturn( (new Long(TOKEN_VALIDITY_SEC)).toString()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector<>(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.AUTH_TOKEN_VALIDITY)).elements()); - ServletContext context = Mockito.mock(ServletContext.class); - Mockito.when(context.getAttribute(AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) + ServletContext context = mock(ServletContext.class); + when(context.getAttribute(AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(null); - Mockito.when(config.getServletContext()).thenReturn(context); + when(config.getServletContext()).thenReturn(context); filter.init(config); - Assert.assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass()); - Assert.assertTrue(filter.isRandomSecret()); - Assert.assertFalse(filter.isCustomSignerSecretProvider()); - Assert.assertNull(filter.getCookieDomain()); - Assert.assertNull(filter.getCookiePath()); - Assert.assertEquals(TOKEN_VALIDITY_SEC, filter.getValidity()); + assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass()); + assertTrue(filter.isRandomSecret()); + assertFalse(filter.isCustomSignerSecretProvider()); + assertNull(filter.getCookieDomain()); + assertNull(filter.getCookiePath()); + assertEquals(TOKEN_VALIDITY_SEC, filter.getValidity()); } finally { filter.destroy(); } @@ -185,13 +199,13 @@ public void testInit() throws Exception { // custom secret as inline AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); - Mockito.when(config.getInitParameterNames()).thenReturn( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); + when(config.getInitParameterNames()).thenReturn( new Vector<>(Arrays.asList(AuthenticationFilter.AUTH_TYPE)) .elements()); - ServletContext context = Mockito.mock(ServletContext.class); - Mockito.when(context.getAttribute( + ServletContext context = mock(ServletContext.class); + when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)).thenReturn( new SignerSecretProvider() { @Override @@ -207,10 +221,10 @@ public byte[][] getAllSecrets() { return null; } }); - Mockito.when(config.getServletContext()).thenReturn(context); + when(config.getServletContext()).thenReturn(context); filter.init(config); - Assert.assertFalse(filter.isRandomSecret()); - Assert.assertTrue(filter.isCustomSignerSecretProvider()); + assertFalse(filter.isRandomSecret()); + assertTrue(filter.isCustomSignerSecretProvider()); } finally { filter.destroy(); } @@ -227,23 +241,23 @@ public byte[][] getAllSecrets() { filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter( AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); - Mockito.when(config.getInitParameter( + when(config.getInitParameter( AuthenticationFilter.SIGNATURE_SECRET_FILE)) .thenReturn(secretFile.getAbsolutePath()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET_FILE)).elements()); - ServletContext context = Mockito.mock(ServletContext.class); - Mockito.when(context.getAttribute( + ServletContext context = mock(ServletContext.class); + when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(null); - Mockito.when(config.getServletContext()).thenReturn(context); + when(config.getServletContext()).thenReturn(context); filter.init(config); - Assert.assertFalse(filter.isRandomSecret()); - Assert.assertFalse(filter.isCustomSignerSecretProvider()); + assertFalse(filter.isRandomSecret()); + assertFalse(filter.isCustomSignerSecretProvider()); } finally { filter.destroy(); } @@ -251,18 +265,18 @@ public byte[][] getAllSecrets() { // custom cookie domain and cookie path filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); - Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_DOMAIN)).thenReturn(".foo.com"); - Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)).thenReturn("/bar"); - Mockito.when(config.getInitParameterNames()).thenReturn( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); + when(config.getInitParameter(AuthenticationFilter.COOKIE_DOMAIN)).thenReturn(".foo.com"); + when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)).thenReturn("/bar"); + when(config.getInitParameterNames()).thenReturn( new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.COOKIE_DOMAIN, AuthenticationFilter.COOKIE_PATH)).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - Assert.assertEquals(".foo.com", filter.getCookieDomain()); - Assert.assertEquals("/bar", filter.getCookiePath()); + assertEquals(".foo.com", filter.getCookieDomain()); + assertEquals("/bar", filter.getCookiePath()); } finally { filter.destroy(); } @@ -271,37 +285,38 @@ public byte[][] getAllSecrets() { DummyAuthenticationHandler.reset(); filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - Assert.assertTrue(DummyAuthenticationHandler.init); + assertTrue(DummyAuthenticationHandler.init); } finally { filter.destroy(); - Assert.assertTrue(DummyAuthenticationHandler.destroy); + assertTrue(DummyAuthenticationHandler.destroy); } // kerberos auth handler filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - ServletContext sc = Mockito.mock(ServletContext.class); - Mockito.when(config.getServletContext()).thenReturn(sc); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("kerberos"); - Mockito.when(config.getInitParameterNames()).thenReturn( + FilterConfig config = mock(FilterConfig.class); + ServletContext sc = mock(ServletContext.class); + when(config.getServletContext()).thenReturn(sc); + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("kerberos"); + when(config.getInitParameterNames()).thenReturn( new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements()); filter.init(config); } catch (ServletException ex) { // Expected } finally { - Assert.assertEquals(KerberosAuthenticationHandler.class, filter.getAuthenticationHandler().getClass()); + assertEquals(KerberosAuthenticationHandler.class, + filter.getAuthenticationHandler().getClass()); filter.destroy(); } } @@ -310,25 +325,25 @@ public byte[][] getAllSecrets() { public void testEmptySecretFileFallbacksToRandomSecret() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter( AuthenticationFilter.AUTH_TYPE)).thenReturn("simple"); File secretFile = File.createTempFile("test_empty_secret", ".txt"); secretFile.deleteOnExit(); - Assert.assertTrue(secretFile.exists()); - Mockito.when(config.getInitParameter( + assertTrue(secretFile.exists()); + when(config.getInitParameter( AuthenticationFilter.SIGNATURE_SECRET_FILE)) .thenReturn(secretFile.getAbsolutePath()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector<>(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET_FILE)).elements()); - ServletContext context = Mockito.mock(ServletContext.class); - Mockito.when(context.getAttribute( + ServletContext context = mock(ServletContext.class); + when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(null); - Mockito.when(config.getServletContext()).thenReturn(context); + when(config.getServletContext()).thenReturn(context); filter.init(config); - Assert.assertTrue(filter.isRandomSecret()); + assertTrue(filter.isRandomSecret()); } finally { filter.destroy(); } @@ -339,17 +354,17 @@ public void testInitCaseSensitivity() throws Exception { // minimal configuration & simple auth handler (Pseudo) AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("SimPle"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TOKEN_VALIDITY)).thenReturn( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn("SimPle"); + when(config.getInitParameter(AuthenticationFilter.AUTH_TOKEN_VALIDITY)).thenReturn( (new Long(TOKEN_VALIDITY_SEC)).toString()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.AUTH_TOKEN_VALIDITY)).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - Assert.assertEquals(PseudoAuthenticationHandler.class, + assertEquals(PseudoAuthenticationHandler.class, filter.getAuthenticationHandler().getClass()); } finally { filter.destroy(); @@ -360,23 +375,23 @@ public void testInitCaseSensitivity() throws Exception { public void testGetRequestURL() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); - Mockito.when(request.getQueryString()).thenReturn("a=A&b=B"); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + when(request.getQueryString()).thenReturn("a=A&b=B"); - Assert.assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request)); + assertEquals("http://foo:8080/bar?a=A&b=B", filter.getRequestURL(request)); } finally { filter.destroy(); } @@ -387,13 +402,13 @@ public void testGetToken() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, @@ -409,12 +424,12 @@ public void testGetToken() throws Exception { String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); AuthenticationToken newToken = filter.getToken(request); - Assert.assertEquals(token.toString(), newToken.toString()); + assertEquals(token.toString(), newToken.toString()); } finally { filter.destroy(); } @@ -424,12 +439,12 @@ public void testGetToken() throws Exception { public void testGetTokenExpired() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")).thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")).thenReturn("true"); + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, @@ -450,17 +465,17 @@ public void testGetTokenExpired() throws Exception { String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); boolean failed = false; try { filter.getToken(request); } catch (AuthenticationException ex) { - Assert.assertEquals("AuthenticationToken expired", ex.getMessage()); + assertEquals("AuthenticationToken expired", ex.getMessage()); failed = true; } finally { - Assert.assertTrue("token not expired", failed); + assertTrue(failed, "token not expired"); } } finally { filter.destroy(); @@ -471,13 +486,13 @@ public void testGetTokenExpired() throws Exception { public void testGetTokenInvalidType() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn("secret"); + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, @@ -497,17 +512,17 @@ public void testGetTokenInvalidType() throws Exception { String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); boolean failed = false; try { filter.getToken(request); } catch (AuthenticationException ex) { - Assert.assertEquals("Invalid AuthenticationToken type", ex.getMessage()); + assertEquals("Invalid AuthenticationToken type", ex.getMessage()); failed = true; } finally { - Assert.assertTrue("token not invalid type", failed); + assertTrue(failed, "token not invalid type"); } } finally { filter.destroy(); @@ -523,11 +538,11 @@ private static SignerSecretProvider getMockedServletContextWithStringSigner( StringSignerSecretProviderCreator.newStringSignerSecretProvider(); secretProvider.init(secretProviderProps, null, TOKEN_VALIDITY_SEC); - ServletContext context = Mockito.mock(ServletContext.class); - Mockito.when(context.getAttribute( + ServletContext context = mock(ServletContext.class); + when(context.getAttribute( AuthenticationFilter.SIGNER_SECRET_PROVIDER_ATTRIBUTE)) .thenReturn(secretProvider); - Mockito.when(config.getServletContext()).thenReturn(context); + when(config.getServletContext()).thenReturn(context); return secretProvider; } @@ -535,39 +550,39 @@ private static SignerSecretProvider getMockedServletContextWithStringSigner( public void testDoFilterNotAuthenticated() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletResponse response = mock(HttpServletResponse.class); - FilterChain chain = Mockito.mock(FilterChain.class); + FilterChain chain = mock(FilterChain.class); - Mockito.doAnswer( + doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { - Assert.fail(); + fail(); return null; } } ).when(chain).doFilter(any(), any()); - Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true); + when(response.containsHeader("WWW-Authenticate")).thenReturn(true); filter.doFilter(request, response, chain); - Mockito.verify(response).sendError( + verify(response).sendError( HttpServletResponse.SC_UNAUTHORIZED, "Authentication required"); } finally { filter.destroy(); @@ -578,34 +593,34 @@ public Object answer(InvocationOnMock invocation) throws Throwable { public void testDoFilterNotAuthenticatedLowerCase() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector<>( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletResponse response = mock(HttpServletResponse.class); - FilterChain chain = Mockito.mock(FilterChain.class); + FilterChain chain = mock(FilterChain.class); - Mockito.doAnswer((Answer) invocation -> { - Assert.fail(); + doAnswer((Answer) invocation -> { + fail(); return null; }).when(chain).doFilter(any(), any()); - Mockito.when(response.containsHeader("www-authenticate")).thenReturn(true); + when(response.containsHeader("www-authenticate")).thenReturn(true); filter.doFilter(request, response, chain); - Mockito.verify(response).sendError( + verify(response).sendError( HttpServletResponse.SC_UNAUTHORIZED, "Authentication required"); } finally { filter.destroy(); @@ -616,18 +631,18 @@ private void _testDoFilterAuthentication(boolean withDomainPath, boolean invalidToken, boolean expired) throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter("expired.token")). + when(config.getInitParameter("expired.token")). thenReturn(Boolean.toString(expired)); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)) + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)) .thenReturn(DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter(AuthenticationFilter + when(config.getInitParameter(AuthenticationFilter .AUTH_TOKEN_VALIDITY)).thenReturn(new Long(TOKEN_VALIDITY_SEC).toString()); - Mockito.when(config.getInitParameter(AuthenticationFilter + when(config.getInitParameter(AuthenticationFilter .SIGNATURE_SECRET)).thenReturn("secret"); - Mockito.when(config.getInitParameterNames()).thenReturn(new + when(config.getInitParameterNames()).thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.AUTH_TOKEN_VALIDITY, AuthenticationFilter.SIGNATURE_SECRET, "management.operation" + @@ -635,11 +650,11 @@ private void _testDoFilterAuthentication(boolean withDomainPath, getMockedServletContextWithStringSigner(config); if (withDomainPath) { - Mockito.when(config.getInitParameter(AuthenticationFilter + when(config.getInitParameter(AuthenticationFilter .COOKIE_DOMAIN)).thenReturn(".foo.com"); - Mockito.when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)) + when(config.getInitParameter(AuthenticationFilter.COOKIE_PATH)) .thenReturn("/bar"); - Mockito.when(config.getInitParameterNames()).thenReturn(new + when(config.getInitParameterNames()).thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.AUTH_TOKEN_VALIDITY, AuthenticationFilter.SIGNATURE_SECRET, @@ -647,43 +662,42 @@ private void _testDoFilterAuthentication(boolean withDomainPath, .COOKIE_PATH, "management.operation.return")).elements()); } - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getParameter("authenticated")).thenReturn("true"); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getParameter("authenticated")).thenReturn("true"); + when(request.getRequestURL()).thenReturn(new StringBuffer ("http://foo:8080/bar")); - Mockito.when(request.getQueryString()).thenReturn("authenticated=true"); + when(request.getQueryString()).thenReturn("authenticated=true"); if (invalidToken) { - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{new Cookie + when(request.getCookies()).thenReturn(new Cookie[]{new Cookie (AuthenticatedURL.AUTH_COOKIE, "foo")}); } - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - FilterChain chain = Mockito.mock(FilterChain.class); + HttpServletResponse response = mock(HttpServletResponse.class); + FilterChain chain = mock(FilterChain.class); final Map cookieMap = new HashMap(); - Mockito.doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String cookieHeader = (String)invocation.getArguments()[1]; parseCookieMap(cookieHeader, cookieMap); return null; } - }).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString()); + }).when(response).addHeader(eq("Set-Cookie"), anyString()); try { filter.init(config); filter.doFilter(request, response, chain); if (expired) { - Mockito.verify(response, Mockito.never()). - addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString()); + verify(response, never()).addHeader(eq("Set-Cookie"), anyString()); } else { String v = cookieMap.get(AuthenticatedURL.AUTH_COOKIE); - Assert.assertNotNull("cookie missing", v); - Assert.assertTrue(v.contains("u=") && v.contains("p=") && v.contains + assertNotNull(v, "cookie missing"); + assertTrue(v.contains("u=") && v.contains("p=") && v.contains ("t=") && v.contains("e=") && v.contains("s=")); - Mockito.verify(chain).doFilter(any(ServletRequest.class), + verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); SignerSecretProvider secretProvider = @@ -695,14 +709,14 @@ public Object answer(InvocationOnMock invocation) throws Throwable { Signer signer = new Signer(secretProvider); String value = signer.verifyAndExtract(v); AuthenticationToken token = AuthenticationToken.parse(value); - assertThat(token.getExpires(), not(0L)); + assertThat(token.getExpires()).isNotEqualTo(0L); if (withDomainPath) { - Assert.assertEquals(".foo.com", cookieMap.get("Domain")); - Assert.assertEquals("/bar", cookieMap.get("Path")); + assertEquals(".foo.com", cookieMap.get("Domain")); + assertEquals("/bar", cookieMap.get("Path")); } else { - Assert.assertFalse(cookieMap.containsKey("Domain")); - Assert.assertFalse(cookieMap.containsKey("Path")); + assertFalse(cookieMap.containsKey("Domain")); + assertFalse(cookieMap.containsKey("Path")); } } } finally { @@ -750,20 +764,20 @@ public void testDoFilterAuthenticationWithDomainPath() throws Exception { public void testDoFilterAuthenticated() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u", "p", "t"); token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC); @@ -777,20 +791,20 @@ public void testDoFilterAuthenticated() throws Exception { String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletResponse response = mock(HttpServletResponse.class); - FilterChain chain = Mockito.mock(FilterChain.class); + FilterChain chain = mock(FilterChain.class); - Mockito.doAnswer( + doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); HttpServletRequest request = (HttpServletRequest) args[0]; - Assert.assertEquals("u", request.getRemoteUser()); - Assert.assertEquals("p", request.getUserPrincipal().getName()); + assertEquals("u", request.getRemoteUser()); + assertEquals("p", request.getUserPrincipal().getName()); return null; } } @@ -807,28 +821,28 @@ public Object answer(InvocationOnMock invocation) throws Throwable { public void testDoFilterAuthenticationFailure() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{}); - Mockito.when(request.getHeader("WWW-Authenticate")).thenReturn("dummyauth"); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + when(request.getCookies()).thenReturn(new Cookie[]{}); + when(request.getHeader("WWW-Authenticate")).thenReturn("dummyauth"); + HttpServletResponse response = mock(HttpServletResponse.class); - FilterChain chain = Mockito.mock(FilterChain.class); + FilterChain chain = mock(FilterChain.class); final Map cookieMap = new HashMap(); - Mockito.doAnswer( + doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { @@ -837,13 +851,13 @@ public Object answer(InvocationOnMock invocation) throws Throwable { return null; } } - ).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString()); + ).when(response).addHeader(eq("Set-Cookie"), anyString()); - Mockito.doAnswer( + doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { - Assert.fail("shouldn't get here"); + fail("shouldn't get here"); return null; } } @@ -851,13 +865,13 @@ public Object answer(InvocationOnMock invocation) throws Throwable { filter.doFilter(request, response, chain); - Mockito.verify(response).sendError( + verify(response).sendError( HttpServletResponse.SC_FORBIDDEN, "AUTH FAILED"); - Mockito.verify(response, Mockito.never()).setHeader(Mockito.eq("WWW-Authenticate"), Mockito.anyString()); + verify(response, never()).setHeader(eq("WWW-Authenticate"), anyString()); String value = cookieMap.get(AuthenticatedURL.AUTH_COOKIE); - Assert.assertNotNull("cookie missing", value); - Assert.assertEquals("", value); + assertNotNull(value, "cookie missing"); + assertEquals("", value); } finally { filter.destroy(); } @@ -868,14 +882,14 @@ public void testDoFilterAuthenticatedExpired() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, @@ -883,8 +897,8 @@ public void testDoFilterAuthenticatedExpired() throws Exception { getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u", "p", DummyAuthenticationHandler.TYPE); token.setExpires(System.currentTimeMillis() - TOKEN_VALIDITY_SEC); @@ -898,11 +912,11 @@ public void testDoFilterAuthenticatedExpired() throws Exception { String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true); - FilterChain chain = Mockito.mock(FilterChain.class); + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.containsHeader("WWW-Authenticate")).thenReturn(true); + FilterChain chain = mock(FilterChain.class); verifyUnauthorized(filter, request, response, chain); } finally { @@ -1077,18 +1091,18 @@ public void testTokenWithNoActivityIntervals() String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter( + when(config.getInitParameter( AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter( + when(config.getInitParameter( AuthenticationFilter.SIGNATURE_SECRET)).thenReturn(secret); - Mockito.when(config.getInitParameter( + when(config.getInitParameter( AuthenticationFilter.AUTH_TOKEN_MAX_INACTIVE_INTERVAL)).thenReturn( Long.toString(maxInactivesOnServer)); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, @@ -1097,8 +1111,8 @@ public void testTokenWithNoActivityIntervals() getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn( + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn( new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u", "p", @@ -1116,11 +1130,11 @@ public void testTokenWithNoActivityIntervals() String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Mockito.when(response.containsHeader("WWW-Authenticate")) + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.containsHeader("WWW-Authenticate")) .thenReturn(true); - FilterChain chain = Mockito.mock(FilterChain.class); + FilterChain chain = mock(FilterChain.class); if (authorized) { verifyAuthorized(filter, request, response, chain, newCookie); @@ -1139,25 +1153,25 @@ private static void verifyAuthorized(AuthenticationFilter filter, boolean newCookie) throws Exception { final Map cookieMap = new HashMap<>(); - Mockito.doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String cookieHeader = (String) invocation.getArguments()[1]; parseCookieMap(cookieHeader, cookieMap); return null; } - }).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString()); + }).when(response).addHeader(eq("Set-Cookie"), anyString()); filter.doFilter(request, response, chain); if (newCookie) { // a new cookie should be dropped when maxInactiveInterval is enabled String v = cookieMap.get(AuthenticatedURL.AUTH_COOKIE); - Assert.assertNotNull("cookie missing", v); - Assert.assertTrue(v.contains("u=") && v.contains("p=") && v.contains + assertNotNull(v, "cookie missing"); + assertTrue(v.contains("u=") && v.contains("p=") && v.contains ("t=") && v.contains("i=") && v.contains("e=") && v.contains("s=")); - Mockito.verify(chain).doFilter(any(ServletRequest.class), + verify(chain).doFilter(any(ServletRequest.class), any(ServletResponse.class)); SignerSecretProvider secretProvider = @@ -1169,14 +1183,14 @@ public Object answer(InvocationOnMock invocation) throws Throwable { Signer signer = new Signer(secretProvider); String value = signer.verifyAndExtract(v); AuthenticationToken token = AuthenticationToken.parse(value); - assertThat(token.getMaxInactives(), not(0L)); - assertThat(token.getExpires(), not(0L)); - Assert.assertFalse("Token is expired.", token.isExpired()); + assertThat(token.getMaxInactives()).isNotEqualTo(0L); + assertThat(token.getExpires()).isNotEqualTo(0L); + assertFalse(token.isExpired(), "Token is expired."); } else { //make sure that no auth cookie is dropped. //For unauthorized response, auth cookie is dropped with empty value - Assert.assertTrue("cookie is present", - !cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE)); + assertTrue( + !cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE), "cookie is present"); } } @@ -1188,25 +1202,25 @@ private static void verifyUnauthorized(AuthenticationFilter filter, ServletException { //For unauthorized response, a cookie is dropped with empty string as value final Map cookieMap = new HashMap(); - Mockito.doAnswer(new Answer() { + doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String cookieHeader = (String) invocation.getArguments()[1]; parseCookieMap(cookieHeader, cookieMap); return null; } - }).when(response).addHeader(Mockito.eq("Set-Cookie"), Mockito.anyString()); + }).when(response).addHeader(eq("Set-Cookie"), anyString()); filter.doFilter(request, response, chain); - Mockito.verify(response).sendError(Mockito.eq(HttpServletResponse - .SC_UNAUTHORIZED), Mockito.anyString()); - Mockito.verify(chain, Mockito.never()).doFilter( + verify(response).sendError(eq(HttpServletResponse + .SC_UNAUTHORIZED), anyString()); + verify(chain, never()).doFilter( any(ServletRequest.class), any(ServletResponse.class)); - Assert.assertTrue("cookie is missing", - cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE)); - Assert.assertEquals("", cookieMap.get(AuthenticatedURL.AUTH_COOKIE)); + assertTrue( + cookieMap.containsKey(AuthenticatedURL.AUTH_COOKIE), "cookie is missing"); + assertEquals("", cookieMap.get(AuthenticatedURL.AUTH_COOKIE)); } @Test @@ -1214,14 +1228,14 @@ public void testDoFilterAuthenticatedInvalidType() throws Exception { String secret = "secret"; AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("true"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)).thenReturn( DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( + when(config.getInitParameter(AuthenticationFilter.SIGNATURE_SECRET)).thenReturn( secret); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, AuthenticationFilter.SIGNATURE_SECRET, @@ -1229,8 +1243,8 @@ public void testDoFilterAuthenticatedInvalidType() throws Exception { getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u", "p", "invalidtype"); token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC); @@ -1244,11 +1258,11 @@ public void testDoFilterAuthenticatedInvalidType() throws Exception { String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Mockito.when(response.containsHeader("WWW-Authenticate")).thenReturn(true); - FilterChain chain = Mockito.mock(FilterChain.class); + HttpServletResponse response = mock(HttpServletResponse.class); + when(response.containsHeader("WWW-Authenticate")).thenReturn(true); + FilterChain chain = mock(FilterChain.class); verifyUnauthorized(filter, request, response, chain); } finally { @@ -1260,32 +1274,32 @@ public void testDoFilterAuthenticatedInvalidType() throws Exception { public void testManagementOperation() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { - FilterConfig config = Mockito.mock(FilterConfig.class); - Mockito.when(config.getInitParameter("management.operation.return")). + FilterConfig config = mock(FilterConfig.class); + when(config.getInitParameter("management.operation.return")). thenReturn("false"); - Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)). + when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)). thenReturn(DummyAuthenticationHandler.class.getName()); - Mockito.when(config.getInitParameterNames()).thenReturn( + when(config.getInitParameterNames()).thenReturn( new Vector( Arrays.asList(AuthenticationFilter.AUTH_TYPE, "management.operation.return")).elements()); getMockedServletContextWithStringSigner(config); filter.init(config); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - Mockito.when(request.getRequestURL()). + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getRequestURL()). thenReturn(new StringBuffer("http://foo:8080/bar")); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletResponse response = mock(HttpServletResponse.class); - FilterChain chain = Mockito.mock(FilterChain.class); + FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); - Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); - Mockito.verifyNoMoreInteractions(response); + verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); + verifyNoMoreInteractions(response); - Mockito.reset(request); - Mockito.reset(response); + reset(request); + reset(response); AuthenticationToken token = new AuthenticationToken("u", "p", "t"); token.setExpires(System.currentTimeMillis() + TOKEN_VALIDITY_SEC); @@ -1298,13 +1312,13 @@ public void testManagementOperation() throws Exception { Signer signer = new Signer(secretProvider); String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); - Mockito.when(request.getCookies()).thenReturn(new Cookie[]{cookie}); - Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer()); + when(request.getCookies()).thenReturn(new Cookie[]{cookie}); + when(request.getRequestURL()).thenReturn(new StringBuffer()); filter.doFilter(request, response, chain); - Mockito.verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); - Mockito.verifyNoMoreInteractions(response); + verify(response).setStatus(HttpServletResponse.SC_ACCEPTED); + verifyNoMoreInteractions(response); } finally { filter.destroy(); diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationToken.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationToken.java index 6727def596dd3..aac445c56bd6d 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationToken.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestAuthenticationToken.java @@ -13,18 +13,21 @@ */ package org.apache.hadoop.security.authentication.server; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; public class TestAuthenticationToken { @Test public void testAnonymous() { - Assert.assertNotNull(AuthenticationToken.ANONYMOUS); - Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getUserName()); - Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getName()); - Assert.assertEquals(null, AuthenticationToken.ANONYMOUS.getType()); - Assert.assertEquals(-1, AuthenticationToken.ANONYMOUS.getExpires()); - Assert.assertFalse(AuthenticationToken.ANONYMOUS.isExpired()); + assertNotNull(AuthenticationToken.ANONYMOUS); + assertEquals(null, AuthenticationToken.ANONYMOUS.getUserName()); + assertEquals(null, AuthenticationToken.ANONYMOUS.getName()); + assertEquals(null, AuthenticationToken.ANONYMOUS.getType()); + assertEquals(-1, AuthenticationToken.ANONYMOUS.getExpires()); + assertFalse(AuthenticationToken.ANONYMOUS.isExpired()); } } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestPseudoAuthenticationHandler.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestPseudoAuthenticationHandler.java index ac6221d642a6f..e623901213aca 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestPseudoAuthenticationHandler.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestPseudoAuthenticationHandler.java @@ -13,10 +13,14 @@ */ package org.apache.hadoop.security.authentication.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import org.apache.hadoop.security.authentication.client.PseudoAuthenticator; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Mockito; +import org.junit.jupiter.api.Test; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -32,7 +36,7 @@ public void testInit() throws Exception { Properties props = new Properties(); props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false"); handler.init(props); - Assert.assertEquals(false, handler.getAcceptAnonymous()); + assertEquals(false, handler.getAcceptAnonymous()); } finally { handler.destroy(); } @@ -41,7 +45,7 @@ public void testInit() throws Exception { @Test public void testType() throws Exception { PseudoAuthenticationHandler handler = new PseudoAuthenticationHandler(); - Assert.assertEquals(PseudoAuthenticationHandler.TYPE, handler.getType()); + assertEquals(PseudoAuthenticationHandler.TYPE, handler.getType()); } @Test @@ -52,12 +56,12 @@ public void testAnonymousOn() throws Exception { props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "true"); handler.init(props); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); AuthenticationToken token = handler.authenticate(request, response); - Assert.assertEquals(AuthenticationToken.ANONYMOUS, token); + assertEquals(AuthenticationToken.ANONYMOUS, token); } finally { handler.destroy(); } @@ -71,11 +75,11 @@ public void testAnonymousOff() throws Exception { props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, "false"); handler.init(props); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); AuthenticationToken token = handler.authenticate(request, response); - Assert.assertNull(token); + assertNull(token); } finally { handler.destroy(); } @@ -88,16 +92,16 @@ private void _testUserName(boolean anonymous) throws Exception { props.setProperty(PseudoAuthenticationHandler.ANONYMOUS_ALLOWED, Boolean.toString(anonymous)); handler.init(props); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); - Mockito.when(request.getQueryString()).thenReturn(PseudoAuthenticator.USER_NAME + "=" + "user"); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + when(request.getQueryString()).thenReturn(PseudoAuthenticator.USER_NAME + "=" + "user"); AuthenticationToken token = handler.authenticate(request, response); - Assert.assertNotNull(token); - Assert.assertEquals("user", token.getUserName()); - Assert.assertEquals("user", token.getName()); - Assert.assertEquals(PseudoAuthenticationHandler.TYPE, token.getType()); + assertNotNull(token); + assertEquals("user", token.getUserName()); + assertEquals("user", token.getName()); + assertEquals(PseudoAuthenticationHandler.TYPE, token.getType()); } finally { handler.destroy(); } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestAuthToken.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestAuthToken.java index 1cb9bf3326d2b..715293ceda87c 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestAuthToken.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestAuthToken.java @@ -13,9 +13,13 @@ */ package org.apache.hadoop.security.authentication.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + import org.apache.hadoop.security.authentication.client.AuthenticationException; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestAuthToken { @@ -23,51 +27,51 @@ public class TestAuthToken { public void testConstructor() throws Exception { try { new AuthToken(null, "p", "t"); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } try { new AuthToken("", "p", "t"); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } try { new AuthToken("u", null, "t"); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } try { new AuthToken("u", "", "t"); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } try { new AuthToken("u", "p", null); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } try { new AuthToken("u", "p", ""); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } new AuthToken("u", "p", "t"); } @@ -77,13 +81,13 @@ public void testGetters() throws Exception { long expires = System.currentTimeMillis() + 50; AuthToken token = new AuthToken("u", "p", "t"); token.setExpires(expires); - Assert.assertEquals("u", token.getUserName()); - Assert.assertEquals("p", token.getName()); - Assert.assertEquals("t", token.getType()); - Assert.assertEquals(expires, token.getExpires()); - Assert.assertFalse(token.isExpired()); + assertEquals("u", token.getUserName()); + assertEquals("p", token.getName()); + assertEquals("t", token.getType()); + assertEquals(expires, token.getExpires()); + assertFalse(token.isExpired()); Thread.sleep(70); // +20 msec fuzz for timer granularity. - Assert.assertTrue(token.isExpired()); + assertTrue(token.isExpired()); } @Test @@ -93,12 +97,12 @@ public void testToStringAndParse() throws Exception { token.setExpires(expires); String str = token.toString(); token = AuthToken.parse(str); - Assert.assertEquals("p", token.getName()); - Assert.assertEquals("t", token.getType()); - Assert.assertEquals(expires, token.getExpires()); - Assert.assertFalse(token.isExpired()); + assertEquals("p", token.getName()); + assertEquals("t", token.getType()); + assertEquals(expires, token.getExpires()); + assertFalse(token.isExpired()); Thread.sleep(70); // +20 msec fuzz for timer granularity. - Assert.assertTrue(token.isExpired()); + assertTrue(token.isExpired()); } @Test @@ -117,11 +121,11 @@ public void testParseValidAndInvalid() throws Exception { String str = ostr.substring(0, ostr.indexOf("e=")); try { AuthToken.parse(str); - Assert.fail(); + fail(); } catch (AuthenticationException ex) { // Expected } catch (Exception ex) { - Assert.fail(); + fail(); } } } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestCertificateUtil.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestCertificateUtil.java index 5794eb609b718..0580bac9053be 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestCertificateUtil.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestCertificateUtil.java @@ -17,16 +17,16 @@ */ package org.apache.hadoop.security.authentication.util; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.security.interfaces.RSAPublicKey; import javax.servlet.ServletException; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestCertificateUtil { diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestFileSignerSecretProvider.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestFileSignerSecretProvider.java index 5d4aabfc7c7a3..ff5596ab8cdf9 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestFileSignerSecretProvider.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestFileSignerSecretProvider.java @@ -14,17 +14,17 @@ package org.apache.hadoop.security.authentication.util; import org.apache.hadoop.security.authentication.server.AuthenticationFilter; -import org.junit.Assert; -import org.junit.Test; -import org.junit.function.ThrowingRunnable; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.util.Properties; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class TestFileSignerSecretProvider { @@ -46,11 +46,11 @@ public void testGetSecrets() throws Exception { AuthenticationFilter.SIGNATURE_SECRET_FILE, secretFile.getAbsolutePath()); secretProvider.init(secretProviderProps, null, -1); - Assert.assertArrayEquals(secretValue.getBytes(), + assertArrayEquals(secretValue.getBytes(), secretProvider.getCurrentSecret()); byte[][] allSecrets = secretProvider.getAllSecrets(); - Assert.assertEquals(1, allSecrets.length); - Assert.assertArrayEquals(secretValue.getBytes(), allSecrets[0]); + assertEquals(1, allSecrets.length); + assertArrayEquals(secretValue.getBytes(), allSecrets[0]); } @Test @@ -66,11 +66,8 @@ public void testEmptySecretFileThrows() throws Exception { secretFile.getAbsolutePath()); Exception exception = - assertThrows(RuntimeException.class, new ThrowingRunnable() { - @Override - public void run() throws Throwable { - secretProvider.init(secretProviderProps, null, -1); - } + assertThrows(RuntimeException.class, () -> { + secretProvider.init(secretProviderProps, null, -1); }); assertTrue(exception.getMessage().startsWith( "No secret in signature secret file:")); diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestJaasConfiguration.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestJaasConfiguration.java index 5de4122471f50..d5f6c402ba46c 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestJaasConfiguration.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestJaasConfiguration.java @@ -13,10 +13,12 @@ */ package org.apache.hadoop.security.authentication.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + import java.util.Map; import javax.security.auth.login.AppConfigurationEntry; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestJaasConfiguration { @@ -36,20 +38,20 @@ public void test() throws Exception { new JaasConfiguration("foo", "foo/localhost", "/some/location/foo.keytab"); AppConfigurationEntry[] entries = jConf.getAppConfigurationEntry("bar"); - Assert.assertNull(entries); + assertNull(entries); entries = jConf.getAppConfigurationEntry("foo"); - Assert.assertEquals(1, entries.length); + assertEquals(1, entries.length); AppConfigurationEntry entry = entries[0]; - Assert.assertEquals(AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, - entry.getControlFlag()); - Assert.assertEquals(krb5LoginModuleName, entry.getLoginModuleName()); + assertEquals(AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, + entry.getControlFlag()); + assertEquals(krb5LoginModuleName, entry.getLoginModuleName()); Map options = entry.getOptions(); - Assert.assertEquals("/some/location/foo.keytab", options.get("keyTab")); - Assert.assertEquals("foo/localhost", options.get("principal")); - Assert.assertEquals("true", options.get("useKeyTab")); - Assert.assertEquals("true", options.get("storeKey")); - Assert.assertEquals("false", options.get("useTicketCache")); - Assert.assertEquals("true", options.get("refreshKrb5Config")); - Assert.assertEquals(6, options.size()); + assertEquals("/some/location/foo.keytab", options.get("keyTab")); + assertEquals("foo/localhost", options.get("principal")); + assertEquals("true", options.get("useKeyTab")); + assertEquals("true", options.get("storeKey")); + assertEquals("false", options.get("useTicketCache")); + assertEquals("true", options.get("refreshKrb5Config")); + assertEquals(6, options.size()); } } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosName.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosName.java index 105fa11424ee6..ae5a9295bdef7 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosName.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosName.java @@ -18,18 +18,20 @@ package org.apache.hadoop.security.authentication.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.IOException; import org.apache.hadoop.security.authentication.KerberosTestUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.junit.Assert; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class TestKerberosName { - @Before + @BeforeEach public void setUp() throws Exception { System.setProperty("java.security.krb5.realm", KerberosTestUtils.getRealm()); System.setProperty("java.security.krb5.kdc", "localhost:88"); @@ -50,7 +52,7 @@ private void checkTranslation(String from, String to) throws Exception { KerberosName nm = new KerberosName(from); String simple = nm.getShortName(); System.out.println("to " + simple); - Assert.assertEquals("short name incorrect", to, simple); + assertEquals(to, simple, "short name incorrect"); } @Test @@ -67,7 +69,7 @@ private void checkBadName(String name) { System.out.println("Checking " + name + " to ensure it is bad."); try { new KerberosName(name); - Assert.fail("didn't get exception for " + name); + fail("didn't get exception for " + name); } catch (IllegalArgumentException iae) { // PASS } @@ -78,7 +80,7 @@ private void checkBadTranslation(String from) { KerberosName nm = new KerberosName(from); try { nm.getShortName(); - Assert.fail("didn't get exception for " + from); + fail("didn't get exception for " + from); } catch (IOException ie) { // PASS } @@ -105,19 +107,19 @@ public void testParsing() throws Exception { final String principalNameWoHost = "HTTP@EXAMPLE.COM"; final KerberosName kerbNameFull = new KerberosName(principalNameFull); - Assert.assertEquals("HTTP", kerbNameFull.getServiceName()); - Assert.assertEquals("abc.com", kerbNameFull.getHostName()); - Assert.assertEquals("EXAMPLE.COM", kerbNameFull.getRealm()); + assertEquals("HTTP", kerbNameFull.getServiceName()); + assertEquals("abc.com", kerbNameFull.getHostName()); + assertEquals("EXAMPLE.COM", kerbNameFull.getRealm()); final KerberosName kerbNamewoRealm = new KerberosName(principalNameWoRealm); - Assert.assertEquals("HTTP", kerbNamewoRealm.getServiceName()); - Assert.assertEquals("abc.com", kerbNamewoRealm.getHostName()); - Assert.assertEquals(null, kerbNamewoRealm.getRealm()); + assertEquals("HTTP", kerbNamewoRealm.getServiceName()); + assertEquals("abc.com", kerbNamewoRealm.getHostName()); + assertEquals(null, kerbNamewoRealm.getRealm()); final KerberosName kerbNameWoHost = new KerberosName(principalNameWoHost); - Assert.assertEquals("HTTP", kerbNameWoHost.getServiceName()); - Assert.assertEquals(null, kerbNameWoHost.getHostName()); - Assert.assertEquals("EXAMPLE.COM", kerbNameWoHost.getRealm()); + assertEquals("HTTP", kerbNameWoHost.getServiceName()); + assertEquals(null, kerbNameWoHost.getHostName()); + assertEquals("EXAMPLE.COM", kerbNameWoHost.getRealm()); } @Test @@ -136,12 +138,14 @@ public void testToLowerCase() throws Exception { checkTranslation("Joe/guestguest@FOO.COM", "joe"); } - @Test(expected = IllegalArgumentException.class) + @Test public void testInvalidRuleMechanism() throws Exception { - KerberosName.setRuleMechanism("INVALID_MECHANISM"); + assertThrows(IllegalArgumentException.class, () -> { + KerberosName.setRuleMechanism("INVALID_MECHANISM"); + }); } - @After + @AfterEach public void clear() { System.clearProperty("java.security.krb5.realm"); System.clearProperty("java.security.krb5.kdc"); diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosUtil.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosUtil.java index 9999eb2546fcd..0fdaaf4a75a9d 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosUtil.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestKerberosUtil.java @@ -16,7 +16,10 @@ */ package org.apache.hadoop.security.authentication.util; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; import java.io.IOException; @@ -34,9 +37,8 @@ import org.apache.kerby.kerberos.kerb.type.base.EncryptionKey; import org.apache.kerby.kerberos.kerb.type.base.EncryptionType; import org.apache.kerby.kerberos.kerb.type.base.PrincipalName; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; public class TestKerberosUtil { static String testKeytab = "test.keytab"; @@ -48,7 +50,7 @@ public class TestKerberosUtil { "HTTP/testhostanother@testRealm" }; - @After + @AfterEach public void deleteKeytab() { File keytabFile = new File(testKeytab); if (keytabFile.exists()){ @@ -71,41 +73,38 @@ public void testGetServerPrincipal() atDefaultRealm = "@" + defaultRealm; } // check that the test environment is as expected - Assert.assertEquals("testGetServerPrincipal assumes localhost realm is default", - KerberosUtil.getDomainRealm(service + "/" + localHostname.toLowerCase(Locale.US)), - defaultRealm); - Assert.assertEquals("testGetServerPrincipal assumes realm of testHost 'FooBar' is default", - KerberosUtil.getDomainRealm(service + "/" + testHost.toLowerCase(Locale.US)), - defaultRealm); + assertEquals(KerberosUtil.getDomainRealm(service + "/" + localHostname.toLowerCase(Locale.US)), + defaultRealm, "testGetServerPrincipal assumes localhost realm is default"); + assertEquals(KerberosUtil.getDomainRealm(service + "/" + testHost.toLowerCase(Locale.US)), + defaultRealm, "testGetServerPrincipal assumes realm of testHost 'FooBar' is default"); // send null hostname - Assert.assertEquals("When no hostname is sent", - service + "/" + localHostname.toLowerCase(Locale.US) + atDefaultRealm, - KerberosUtil.getServicePrincipal(service, null)); + assertEquals(service + "/" + localHostname.toLowerCase(Locale.US) + atDefaultRealm, + KerberosUtil.getServicePrincipal(service, null), + "When no hostname is sent"); // send empty hostname - Assert.assertEquals("When empty hostname is sent", - service + "/" + localHostname.toLowerCase(Locale.US) + atDefaultRealm, - KerberosUtil.getServicePrincipal(service, "")); + assertEquals(service + "/" + localHostname.toLowerCase(Locale.US) + atDefaultRealm, + KerberosUtil.getServicePrincipal(service, ""), + "When empty hostname is sent"); // send 0.0.0.0 hostname - Assert.assertEquals("When 0.0.0.0 hostname is sent", - service + "/" + localHostname.toLowerCase(Locale.US) + atDefaultRealm, - KerberosUtil.getServicePrincipal(service, "0.0.0.0")); + assertEquals(service + "/" + localHostname.toLowerCase(Locale.US) + atDefaultRealm, + KerberosUtil.getServicePrincipal(service, "0.0.0.0"), + "When 0.0.0.0 hostname is sent"); // send uppercase hostname - Assert.assertEquals("When uppercase hostname is sent", - service + "/" + testHost.toLowerCase(Locale.US) + atDefaultRealm, - KerberosUtil.getServicePrincipal(service, testHost)); + assertEquals(service + "/" + testHost.toLowerCase(Locale.US) + atDefaultRealm, + KerberosUtil.getServicePrincipal(service, testHost), + "When uppercase hostname is sent"); // send lowercase hostname - Assert.assertEquals("When lowercase hostname is sent", - service + "/" + testHost.toLowerCase(Locale.US) + atDefaultRealm, - KerberosUtil.getServicePrincipal( - service, testHost.toLowerCase(Locale.US))); + assertEquals(service + "/" + testHost.toLowerCase(Locale.US) + atDefaultRealm, + KerberosUtil.getServicePrincipal(service, testHost.toLowerCase(Locale.US)), + "When lowercase hostname is sent"); } @Test public void testGetPrincipalNamesMissingKeytab() { try { KerberosUtil.getPrincipalNames(testKeytab); - Assert.fail("Exception should have been thrown"); + fail("Exception should have been thrown"); } catch (IllegalArgumentException e) { //expects exception } catch (IOException e) { @@ -117,7 +116,7 @@ public void testGetPrincipalNamesMissingPattern() throws IOException { createKeyTab(testKeytab, new String[]{"test/testhost@testRealm"}); try { KerberosUtil.getPrincipalNames(testKeytab, null); - Assert.fail("Exception should have been thrown"); + fail("Exception should have been thrown"); } catch (Exception e) { //expects exception } @@ -128,16 +127,15 @@ public void testGetPrincipalNamesFromKeytab() throws IOException { createKeyTab(testKeytab, testPrincipals); // read all principals in the keytab file String[] principals = KerberosUtil.getPrincipalNames(testKeytab); - Assert.assertNotNull("principals cannot be null", principals); + assertNotNull(principals, "principals cannot be null"); int expectedSize = 0; List principalList = Arrays.asList(principals); for (String principal : testPrincipals) { - Assert.assertTrue("missing principal "+principal, - principalList.contains(principal)); + assertTrue(principalList.contains(principal), "missing principal "+principal); expectedSize++; } - Assert.assertEquals(expectedSize, principals.length); + assertEquals(expectedSize, principals.length); } @Test @@ -148,18 +146,18 @@ public void testGetPrincipalNamesFromKeytabWithPattern() throws IOException { Pattern httpPattern = Pattern.compile("HTTP/.*"); String[] httpPrincipals = KerberosUtil.getPrincipalNames(testKeytab, httpPattern); - Assert.assertNotNull("principals cannot be null", httpPrincipals); + assertNotNull(httpPrincipals, "principals cannot be null"); int expectedSize = 0; List httpPrincipalList = Arrays.asList(httpPrincipals); for (String principal : testPrincipals) { if (httpPattern.matcher(principal).matches()) { - Assert.assertTrue("missing principal "+principal, - httpPrincipalList.contains(principal)); + assertTrue(httpPrincipalList.contains(principal), + "missing principal "+principal); expectedSize++; } } - Assert.assertEquals(expectedSize, httpPrincipals.length); + assertEquals(expectedSize, httpPrincipals.length); } private void createKeyTab(String fileName, String[] principalNames) diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRandomSignerSecretProvider.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRandomSignerSecretProvider.java index f9c922caac847..cb9141648a533 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRandomSignerSecretProvider.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRandomSignerSecretProvider.java @@ -17,9 +17,11 @@ import org.apache.log4j.Level; import org.apache.log4j.LogManager; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; @@ -50,28 +52,28 @@ public void testGetAndRollSecrets() throws Exception { byte[] currentSecret = secretProvider.getCurrentSecret(); byte[][] allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret1, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret1, allSecrets[0]); - Assert.assertNull(allSecrets[1]); + assertArrayEquals(secret1, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret1, allSecrets[0]); + assertNull(allSecrets[1]); verify(secretProvider, timeout(timeout).atLeastOnce()).rollSecret(); secretProvider.realRollSecret(); currentSecret = secretProvider.getCurrentSecret(); allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret2, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret2, allSecrets[0]); - Assert.assertArrayEquals(secret1, allSecrets[1]); + assertArrayEquals(secret2, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret2, allSecrets[0]); + assertArrayEquals(secret1, allSecrets[1]); verify(secretProvider, timeout(timeout).atLeast(2)).rollSecret(); secretProvider.realRollSecret(); currentSecret = secretProvider.getCurrentSecret(); allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret3, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret3, allSecrets[0]); - Assert.assertArrayEquals(secret2, allSecrets[1]); + assertArrayEquals(secret3, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret3, allSecrets[0]); + assertArrayEquals(secret2, allSecrets[1]); verify(secretProvider, timeout(timeout).atLeast(3)).rollSecret(); secretProvider.realRollSecret(); } finally { diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRolloverSignerSecretProvider.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRolloverSignerSecretProvider.java index 1e40c42326277..cafd2187ca143 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRolloverSignerSecretProvider.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestRolloverSignerSecretProvider.java @@ -13,8 +13,11 @@ */ package org.apache.hadoop.security.authentication.util; -import org.junit.Assert; -import org.junit.Test; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; public class TestRolloverSignerSecretProvider { @@ -32,26 +35,26 @@ public void testGetAndRollSecrets() throws Exception { byte[] currentSecret = secretProvider.getCurrentSecret(); byte[][] allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret1, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret1, allSecrets[0]); - Assert.assertNull(allSecrets[1]); + assertArrayEquals(secret1, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret1, allSecrets[0]); + assertNull(allSecrets[1]); Thread.sleep(rolloverFrequency + 2000); currentSecret = secretProvider.getCurrentSecret(); allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret2, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret2, allSecrets[0]); - Assert.assertArrayEquals(secret1, allSecrets[1]); + assertArrayEquals(secret2, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret2, allSecrets[0]); + assertArrayEquals(secret1, allSecrets[1]); Thread.sleep(rolloverFrequency + 2000); currentSecret = secretProvider.getCurrentSecret(); allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret3, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret3, allSecrets[0]); - Assert.assertArrayEquals(secret2, allSecrets[1]); + assertArrayEquals(secret3, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret3, allSecrets[0]); + assertArrayEquals(secret2, allSecrets[1]); Thread.sleep(rolloverFrequency + 2000); } finally { secretProvider.destroy(); diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestSigner.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestSigner.java index c6a771057155e..e846a25ae4ebc 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestSigner.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestSigner.java @@ -13,11 +13,14 @@ */ package org.apache.hadoop.security.authentication.util; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.util.Properties; import javax.servlet.ServletContext; import org.apache.hadoop.security.authentication.server.AuthenticationFilter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestSigner { @@ -26,19 +29,19 @@ public void testNullAndEmptyString() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); try { signer.sign(null); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } try { signer.sign(""); - Assert.fail(); + fail(); } catch (IllegalArgumentException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } } @@ -48,8 +51,8 @@ public void testSignature() throws Exception { String s1 = signer.sign("ok"); String s2 = signer.sign("ok"); String s3 = signer.sign("wrong"); - Assert.assertEquals(s1, s2); - Assert.assertNotEquals(s1, s3); + assertEquals(s1, s2); + assertNotEquals(s1, s3); } @Test @@ -58,7 +61,7 @@ public void testVerify() throws Exception { String t = "test"; String s = signer.sign(t); String e = signer.verifyAndExtract(s); - Assert.assertEquals(t, e); + assertEquals(t, e); } @Test @@ -66,11 +69,11 @@ public void testInvalidSignedText() throws Exception { Signer signer = new Signer(createStringSignerSecretProvider()); try { signer.verifyAndExtract("test"); - Assert.fail(); + fail(); } catch (SignerException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } } @@ -82,11 +85,11 @@ public void testTampering() throws Exception { s += "x"; try { signer.verifyAndExtract(s); - Assert.fail(); + fail(); } catch (SignerException ex) { // Expected } catch (Throwable ex) { - Assert.fail(); + fail(); } } @@ -106,27 +109,27 @@ public void testMultipleSecrets() throws Exception { String t1 = "test"; String s1 = signer.sign(t1); String e1 = signer.verifyAndExtract(s1); - Assert.assertEquals(t1, e1); + assertEquals(t1, e1); secretProvider.setPreviousSecret("secretA"); String t2 = "test"; String s2 = signer.sign(t2); String e2 = signer.verifyAndExtract(s2); - Assert.assertEquals(t2, e2); - Assert.assertEquals(s1, s2); //check is using current secret for signing + assertEquals(t2, e2); + assertEquals(s1, s2); //check is using current secret for signing secretProvider.setCurrentSecret("secretC"); secretProvider.setPreviousSecret("secretB"); String t3 = "test"; String s3 = signer.sign(t3); String e3 = signer.verifyAndExtract(s3); - Assert.assertEquals(t3, e3); - Assert.assertNotEquals(s1, s3); //check not using current secret for signing + assertEquals(t3, e3); + assertNotEquals(s1, s3); //check not using current secret for signing String e1b = signer.verifyAndExtract(s1); - Assert.assertEquals(t1, e1b); // previous secret still valid + assertEquals(t1, e1b); // previous secret still valid secretProvider.setCurrentSecret("secretD"); secretProvider.setPreviousSecret("secretC"); try { signer.verifyAndExtract(s1); // previous secret no longer valid - Assert.fail(); + fail(); } catch (SignerException ex) { // Expected } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestStringSignerSecretProvider.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestStringSignerSecretProvider.java index d8b044dcd27f3..8dd7351eab173 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestStringSignerSecretProvider.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestStringSignerSecretProvider.java @@ -13,10 +13,12 @@ */ package org.apache.hadoop.security.authentication.util; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + import java.util.Properties; import org.apache.hadoop.security.authentication.server.AuthenticationFilter; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class TestStringSignerSecretProvider { @@ -30,9 +32,9 @@ public void testGetSecrets() throws Exception { AuthenticationFilter.SIGNATURE_SECRET, "secret"); secretProvider.init(secretProviderProps, null, -1); byte[] secretBytes = secretStr.getBytes(); - Assert.assertArrayEquals(secretBytes, secretProvider.getCurrentSecret()); + assertArrayEquals(secretBytes, secretProvider.getCurrentSecret()); byte[][] allSecrets = secretProvider.getAllSecrets(); - Assert.assertEquals(1, allSecrets.length); - Assert.assertArrayEquals(secretBytes, allSecrets[0]); + assertEquals(1, allSecrets.length); + assertArrayEquals(secretBytes, allSecrets[0]); } } diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestZKSignerSecretProvider.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestZKSignerSecretProvider.java index 4f090c234eece..d378b09b40b01 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestZKSignerSecretProvider.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/TestZKSignerSecretProvider.java @@ -21,10 +21,13 @@ import org.apache.curator.test.TestingServer; import org.apache.log4j.Level; import org.apache.log4j.LogManager; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.timeout; @@ -44,12 +47,12 @@ public class TestZKSignerSecretProvider { RolloverSignerSecretProvider.LOG.getName()).setLevel(Level.DEBUG); } - @Before + @BeforeEach public void setup() throws Exception { zkServer = new TestingServer(); } - @After + @AfterEach public void teardown() throws Exception { if (zkServer != null) { zkServer.stop(); @@ -80,28 +83,28 @@ public void testOne() throws Exception { byte[] currentSecret = secretProvider.getCurrentSecret(); byte[][] allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret1, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret1, allSecrets[0]); - Assert.assertNull(allSecrets[1]); + assertArrayEquals(secret1, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret1, allSecrets[0]); + assertNull(allSecrets[1]); verify(secretProvider, timeout(timeout).atLeastOnce()).rollSecret(); secretProvider.realRollSecret(); currentSecret = secretProvider.getCurrentSecret(); allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret2, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret2, allSecrets[0]); - Assert.assertArrayEquals(secret1, allSecrets[1]); + assertArrayEquals(secret2, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret2, allSecrets[0]); + assertArrayEquals(secret1, allSecrets[1]); verify(secretProvider, timeout(timeout).atLeast(2)).rollSecret(); secretProvider.realRollSecret(); currentSecret = secretProvider.getCurrentSecret(); allSecrets = secretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret3, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret3, allSecrets[0]); - Assert.assertArrayEquals(secret2, allSecrets[1]); + assertArrayEquals(secret3, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret3, allSecrets[0]); + assertArrayEquals(secret2, allSecrets[1]); verify(secretProvider, timeout(timeout).atLeast(3)).rollSecret(); secretProvider.realRollSecret(); } finally { @@ -167,18 +170,18 @@ public void testUpgradeChangeSecretLength() throws Exception { byte[] currentSecret = oldSecretProvider.getCurrentSecret(); byte[][] allSecrets = oldSecretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret1, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret1, allSecrets[0]); - Assert.assertNull(allSecrets[1]); + assertArrayEquals(secret1, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret1, allSecrets[0]); + assertNull(allSecrets[1]); oldSecretProvider.realRollSecret(); currentSecret = oldSecretProvider.getCurrentSecret(); allSecrets = oldSecretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret2, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret2, allSecrets[0]); - Assert.assertArrayEquals(secret1, allSecrets[1]); + assertArrayEquals(secret2, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret2, allSecrets[0]); + assertArrayEquals(secret1, allSecrets[1]); } finally { oldSecretProvider.destroy(); } @@ -191,34 +194,34 @@ public void testUpgradeChangeSecretLength() throws Exception { byte[] currentSecret = newSecretProvider.getCurrentSecret(); byte[][] allSecrets = newSecretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret2, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret2, allSecrets[0]); - Assert.assertArrayEquals(secret1, allSecrets[1]); + assertArrayEquals(secret2, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret2, allSecrets[0]); + assertArrayEquals(secret1, allSecrets[1]); newSecretProvider.realRollSecret(); currentSecret = newSecretProvider.getCurrentSecret(); allSecrets = newSecretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret3, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret3, allSecrets[0]); - Assert.assertArrayEquals(secret2, allSecrets[1]); + assertArrayEquals(secret3, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret3, allSecrets[0]); + assertArrayEquals(secret2, allSecrets[1]); newSecretProvider.realRollSecret(); currentSecret = newSecretProvider.getCurrentSecret(); allSecrets = newSecretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret6, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret6, allSecrets[0]); - Assert.assertArrayEquals(secret3, allSecrets[1]); + assertArrayEquals(secret6, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret6, allSecrets[0]); + assertArrayEquals(secret3, allSecrets[1]); newSecretProvider.realRollSecret(); currentSecret = newSecretProvider.getCurrentSecret(); allSecrets = newSecretProvider.getAllSecrets(); - Assert.assertArrayEquals(secret7, currentSecret); - Assert.assertEquals(2, allSecrets.length); - Assert.assertArrayEquals(secret7, allSecrets[0]); - Assert.assertArrayEquals(secret6, allSecrets[1]); + assertArrayEquals(secret7, currentSecret); + assertEquals(2, allSecrets.length); + assertArrayEquals(secret7, allSecrets[0]); + assertArrayEquals(secret6, allSecrets[1]); } finally { newSecretProvider.destroy(); } @@ -290,14 +293,14 @@ public void testMultiple(int order) throws Exception { byte[][] allSecretsA = secretProviderA.getAllSecrets(); byte[] currentSecretB = secretProviderB.getCurrentSecret(); byte[][] allSecretsB = secretProviderB.getAllSecrets(); - Assert.assertArrayEquals(secretA1, currentSecretA); - Assert.assertArrayEquals(secretA1, currentSecretB); - Assert.assertEquals(2, allSecretsA.length); - Assert.assertEquals(2, allSecretsB.length); - Assert.assertArrayEquals(secretA1, allSecretsA[0]); - Assert.assertArrayEquals(secretA1, allSecretsB[0]); - Assert.assertNull(allSecretsA[1]); - Assert.assertNull(allSecretsB[1]); + assertArrayEquals(secretA1, currentSecretA); + assertArrayEquals(secretA1, currentSecretB); + assertEquals(2, allSecretsA.length); + assertEquals(2, allSecretsB.length); + assertArrayEquals(secretA1, allSecretsA[0]); + assertArrayEquals(secretA1, allSecretsB[0]); + assertNull(allSecretsA[1]); + assertNull(allSecretsB[1]); verify(secretProviderA, timeout(timeout).atLeastOnce()).rollSecret(); verify(secretProviderB, timeout(timeout).atLeastOnce()).rollSecret(); secretProviderA.realRollSecret(); @@ -305,17 +308,17 @@ public void testMultiple(int order) throws Exception { currentSecretA = secretProviderA.getCurrentSecret(); allSecretsA = secretProviderA.getAllSecrets(); - Assert.assertArrayEquals(secretA2, currentSecretA); - Assert.assertEquals(2, allSecretsA.length); - Assert.assertArrayEquals(secretA2, allSecretsA[0]); - Assert.assertArrayEquals(secretA1, allSecretsA[1]); + assertArrayEquals(secretA2, currentSecretA); + assertEquals(2, allSecretsA.length); + assertArrayEquals(secretA2, allSecretsA[0]); + assertArrayEquals(secretA1, allSecretsA[1]); currentSecretB = secretProviderB.getCurrentSecret(); allSecretsB = secretProviderB.getAllSecrets(); - Assert.assertArrayEquals(secretA2, currentSecretB); - Assert.assertEquals(2, allSecretsA.length); - Assert.assertArrayEquals(secretA2, allSecretsB[0]); - Assert.assertArrayEquals(secretA1, allSecretsB[1]); + assertArrayEquals(secretA2, currentSecretB); + assertEquals(2, allSecretsA.length); + assertArrayEquals(secretA2, allSecretsB[0]); + assertArrayEquals(secretA1, allSecretsB[1]); verify(secretProviderA, timeout(timeout).atLeast(2)).rollSecret(); verify(secretProviderB, timeout(timeout).atLeastOnce()).rollSecret(); @@ -340,18 +343,18 @@ public void testMultiple(int order) throws Exception { allSecretsA = secretProviderA.getAllSecrets(); currentSecretB = secretProviderB.getCurrentSecret(); allSecretsB = secretProviderB.getAllSecrets(); - Assert.assertArrayEquals(currentSecretA, currentSecretB); - Assert.assertEquals(2, allSecretsA.length); - Assert.assertEquals(2, allSecretsB.length); - Assert.assertArrayEquals(allSecretsA[0], allSecretsB[0]); - Assert.assertArrayEquals(allSecretsA[1], allSecretsB[1]); + assertArrayEquals(currentSecretA, currentSecretB); + assertEquals(2, allSecretsA.length); + assertEquals(2, allSecretsB.length); + assertArrayEquals(allSecretsA[0], allSecretsB[0]); + assertArrayEquals(allSecretsA[1], allSecretsB[1]); switch (order) { case 1: - Assert.assertArrayEquals(secretA4, allSecretsA[0]); - break; + assertArrayEquals(secretA4, allSecretsA[0]); + break; case 2: - Assert.assertArrayEquals(secretB4, allSecretsA[0]); - break; + assertArrayEquals(secretB4, allSecretsA[0]); + break; } } finally { secretProviderB.destroy(); From c42b4f3f87f2f07b2dfdb3bf0a1829a773fa057f Mon Sep 17 00:00:00 2001 From: slfan1989 Date: Wed, 30 Apr 2025 19:15:42 +0800 Subject: [PATCH 2/2] HADOOP-19414. Fix CheckStyle Issue. --- .../server/TestLdapAuthenticationHandler.java | 66 ++++++++++--------- .../TestMultiSchemeAuthenticationHandler.java | 61 +++++++++-------- 2 files changed, 69 insertions(+), 58 deletions(-) diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestLdapAuthenticationHandler.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestLdapAuthenticationHandler.java index 2a9a26e61dac0..7273f5511eee9 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestLdapAuthenticationHandler.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestLdapAuthenticationHandler.java @@ -13,6 +13,14 @@ */ package org.apache.hadoop.security.authentication.server; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import java.util.Properties; import java.util.concurrent.TimeUnit; @@ -32,12 +40,10 @@ import org.apache.directory.server.core.integ.AbstractLdapTestUnit; import org.apache.directory.server.core.integ.ApacheDSTestExtension; import org.apache.hadoop.security.authentication.client.AuthenticationException; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; /** * This unit test verifies the functionality of LDAP authentication handler. @@ -89,78 +95,78 @@ protected Properties getDefaultProperties() { @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithoutAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); - Assertions.assertNull(handler.authenticate(request, response)); - Mockito.verify(response).setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC); - Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + assertNull(handler.authenticate(request, response)); + verify(response).setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC); + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithInvalidAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); final Base64 base64 = new Base64(0); String credentials = "bjones:invalidpassword"; - Mockito.when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) + when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) .thenReturn(base64.encodeToString(credentials.getBytes())); - Assertions.assertNull(handler.authenticate(request, response)); - Mockito.verify(response).setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC); - Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + assertNull(handler.authenticate(request, response)); + verify(response).setHeader(WWW_AUTHENTICATE, HttpConstants.BASIC); + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithIncompleteAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); - Mockito.when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) + when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) .thenReturn(HttpConstants.BASIC); - Assertions.assertNull(handler.authenticate(request, response)); + assertNull(handler.authenticate(request, response)); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); final Base64 base64 = new Base64(0); String credentials = base64.encodeToString("bjones:p@ssw0rd".getBytes()); String authHeader = HttpConstants.BASIC + " " + credentials; - Mockito.when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) + when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) .thenReturn(authHeader); AuthenticationToken token = handler.authenticate(request, response); - Assertions.assertNotNull(token); - Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); - Assertions.assertEquals(token.getType(), TYPE); - Assertions.assertEquals(token.getUserName(), "bjones"); - Assertions.assertEquals(token.getName(), "bjones"); + assertNotNull(token); + verify(response).setStatus(HttpServletResponse.SC_OK); + assertEquals(token.getType(), TYPE); + assertEquals(token.getUserName(), "bjones"); + assertEquals(token.getName(), "bjones"); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithWrongCredentials() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); final Base64 base64 = new Base64(0); String credentials = base64.encodeToString("bjones:foo123".getBytes()); String authHeader = HttpConstants.BASIC + " " + credentials; - Mockito.when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) + when(request.getHeader(HttpConstants.AUTHORIZATION_HEADER)) .thenReturn(authHeader); try { handler.authenticate(request, response); - Assertions.fail(); + fail(); } catch (AuthenticationException ex) { // Expected } catch (Exception ex) { - Assertions.fail(); + fail(); } } } \ No newline at end of file diff --git a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestMultiSchemeAuthenticationHandler.java b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestMultiSchemeAuthenticationHandler.java index 77e560b4455e3..9a5eab77d33ad 100644 --- a/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestMultiSchemeAuthenticationHandler.java +++ b/hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/server/TestMultiSchemeAuthenticationHandler.java @@ -23,6 +23,13 @@ import static org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.NAME_RULES; import static org.apache.hadoop.security.authentication.server.LdapConstants.*; import static org.apache.hadoop.security.authentication.server.HttpConstants.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.io.File; import java.util.Properties; @@ -44,12 +51,10 @@ import org.apache.hadoop.security.authentication.KerberosTestUtils; import org.apache.hadoop.security.authentication.client.AuthenticationException; import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mockito; /** * This unit test verifies the functionality of "multi-scheme" auth handler. @@ -127,48 +132,48 @@ private Properties getDefaultProperties() { @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithoutAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); - Assertions.assertNull(handler.authenticate(request, response)); - Mockito.verify(response).addHeader(WWW_AUTHENTICATE_HEADER, BASIC); - Mockito.verify(response).addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE); - Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + assertNull(handler.authenticate(request, response)); + verify(response).addHeader(WWW_AUTHENTICATE_HEADER, BASIC); + verify(response).addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE); + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithInvalidAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); final Base64 base64 = new Base64(0); String credentials = "bjones:invalidpassword"; - Mockito.when(request.getHeader(AUTHORIZATION_HEADER)) + when(request.getHeader(AUTHORIZATION_HEADER)) .thenReturn(base64.encodeToString(credentials.getBytes())); - Assertions.assertNull(handler.authenticate(request, response)); - Mockito.verify(response).addHeader(WWW_AUTHENTICATE_HEADER, BASIC); - Mockito.verify(response).addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE); - Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + assertNull(handler.authenticate(request, response)); + verify(response).addHeader(WWW_AUTHENTICATE_HEADER, BASIC); + verify(response).addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE); + verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } @Test @Timeout(value = 60, unit = TimeUnit.SECONDS) public void testRequestWithLdapAuthorization() throws Exception { - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); final Base64 base64 = new Base64(0); String credentials = base64.encodeToString("bjones:p@ssw0rd".getBytes()); String authHeader = BASIC + " " + credentials; - Mockito.when(request.getHeader(AUTHORIZATION_HEADER)) + when(request.getHeader(AUTHORIZATION_HEADER)) .thenReturn(authHeader); AuthenticationToken token = handler.authenticate(request, response); - Assertions.assertNotNull(token); - Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); - Assertions.assertEquals(TYPE, token.getType()); - Assertions.assertEquals(token.getUserName(), "bjones"); - Assertions.assertEquals(token.getName(), "bjones"); + assertNotNull(token); + verify(response).setStatus(HttpServletResponse.SC_OK); + assertEquals(TYPE, token.getType()); + assertEquals(token.getUserName(), "bjones"); + assertEquals(token.getName(), "bjones"); } @Test @@ -176,19 +181,19 @@ public void testRequestWithLdapAuthorization() throws Exception { public void testRequestWithInvalidKerberosAuthorization() throws Exception { String token = new Base64(0).encodeToString(new byte[]{0, 1, 2}); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - HttpServletResponse response = Mockito.mock(HttpServletResponse.class); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); - Mockito.when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn( + when(request.getHeader(AUTHORIZATION_HEADER)).thenReturn( NEGOTIATE + token); try { handler.authenticate(request, response); - Assertions.fail(); + fail(); } catch (AuthenticationException ex) { // Expected } catch (Exception ex) { - Assertions.fail("Wrong exception :"+ex); + fail("Wrong exception :"+ex); } }