diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java index 9f3ae4b8546..718b6204f32 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultCAServer.java @@ -36,14 +36,13 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.pkcs.PKCS10CertificationRequest; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.IOException; import java.math.BigInteger; +import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -61,7 +60,6 @@ import java.util.concurrent.Future; import java.util.function.Consumer; -import static junit.framework.TestCase.assertTrue; import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS; import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.NodeType.OM; import static org.apache.hadoop.hdds.protocol.proto.HddsProtos.NodeType.SCM; @@ -69,22 +67,22 @@ import static org.apache.hadoop.hdds.security.x509.certificate.authority.CertificateServer.CAType.SELF_SIGNED_CA; import static org.apache.hadoop.ozone.OzoneConsts.SCM_CA_CERT_STORAGE_DIR; import static org.apache.hadoop.ozone.OzoneConsts.SCM_CA_PATH; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests the Default CA Server. */ public class TestDefaultCAServer { private static OzoneConfiguration conf = new OzoneConfiguration(); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); private MockCAStore caStore; - @Before - public void init() throws IOException { - conf.set(OZONE_METADATA_DIRS, temporaryFolder.newFolder().toString()); + @BeforeEach + public void init(@TempDir Path tempDir) throws IOException { + conf.set(OZONE_METADATA_DIRS, tempDir.toString()); caStore = new MockCAStore(); } @@ -331,16 +329,16 @@ public void testRequestCertificateWithInvalidSubjectFailure() }); } - @Test(expected = IllegalStateException.class) - public void testIntermediaryCAWithEmpty() - throws Exception { + @Test + public void testIntermediaryCAWithEmpty() { CertificateServer scmCA = new DefaultCAServer("testCA", RandomStringUtils.randomAlphabetic(4), RandomStringUtils.randomAlphabetic(4), caStore, new DefaultProfile(), Paths.get("scm").toString()); - scmCA.init(new SecurityConfig(conf), INTERMEDIARY_CA); + assertThrows(IllegalStateException.class, + () -> scmCA.init(new SecurityConfig(conf), INTERMEDIARY_CA)); } @Test @@ -362,7 +360,7 @@ clusterId, scmId, caStore, new DefaultProfile(), new SCMCertificateClient(new SecurityConfig(conf)); CertificateClient.InitResponse response = scmCertificateClient.init(); - Assert.assertEquals(CertificateClient.InitResponse.GETCERT, response); + assertEquals(CertificateClient.InitResponse.GETCERT, response); // Generate cert KeyPair keyPair = @@ -378,12 +376,12 @@ clusterId, scmId, caStore, new DefaultProfile(), Future holder = rootCA.requestCertificate(csr, CertificateApprover.ApprovalType.TESTING_AUTOMATIC, SCM); - Assert.assertTrue(holder.isDone()); + assertTrue(holder.isDone()); X509CertificateHolder certificateHolder = holder.get(); - Assert.assertNotNull(certificateHolder); + assertNotNull(certificateHolder); LocalDate invalidAfterDate = certificateHolder.getNotAfter().toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java index aecd91fe023..d2186069f05 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/authority/TestDefaultProfile.java @@ -43,38 +43,34 @@ import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder; import org.bouncycastle.pkcs.PKCSException; import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.IOException; +import java.nio.file.Path; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for the default PKI Profile. */ public class TestDefaultProfile { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - private OzoneConfiguration configuration; private SecurityConfig securityConfig; private DefaultProfile defaultProfile; private MockApprover testApprover; private KeyPair keyPair; - @Before - public void setUp() throws Exception { + @BeforeEach + public void setUp(@TempDir Path tempDir) throws Exception { configuration = new OzoneConfiguration(); - configuration.set(OZONE_METADATA_DIRS, - temporaryFolder.newFolder().toString()); + configuration.set(OZONE_METADATA_DIRS, tempDir.toString()); securityConfig = new SecurityConfig(configuration); defaultProfile = new DefaultProfile(); testApprover = new MockApprover(defaultProfile, diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCRLCodec.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCRLCodec.java index d6df77fc307..43e2e45c86d 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCRLCodec.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCRLCodec.java @@ -21,9 +21,9 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +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 java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -33,6 +33,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; +import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -60,12 +61,9 @@ import org.bouncycastle.cert.X509v2CRLBuilder; import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * Tests for the CRLCodec. @@ -79,8 +77,6 @@ public class TestCRLCodec { private KeyPair keyPair; private static final String TMP_CERT_FILE_NAME = "pemcertificate.crt"; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); private File basePath; private static final String TMP_CRL_ENTRY = "-----BEGIN X509 CRL-----\n" + @@ -95,12 +91,12 @@ public class TestCRLCodec { "tPiRCAUQLW9BACm17xc=\n" + "-----END X509 CRL-----\n"; - @Before - public void init() throws NoSuchProviderException, + @BeforeEach + public void init(@TempDir Path tempDir) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, CertificateException, OperatorCreationException { - conf.set(OZONE_METADATA_DIRS, temporaryFolder.newFolder().toString()); + conf.set(OZONE_METADATA_DIRS, tempDir.toString()); securityConfig = new SecurityConfig(conf); writeTempCert(); x509CertificateHolder = readTempCert(); @@ -272,7 +268,7 @@ private void writeTempCert() throws NoSuchProviderException, securityConfig.getCertificateLocation("scm"))); if (!basePath.exists()) { - Assert.assertTrue(basePath.mkdirs()); + assertTrue(basePath.mkdirs()); } codec.writeCertificate(basePath.toPath(), TMP_CERT_FILE_NAME, pemString, false); diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCertificateCodec.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCertificateCodec.java index ded52068395..9746913950d 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCertificateCodec.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificate/utils/TestCertificateCodec.java @@ -26,14 +26,12 @@ import org.apache.hadoop.hdds.security.x509.certificates.utils.SelfSignedCertificate; import org.apache.hadoop.hdds.security.x509.keys.HDDSKeyGenerator; import org.bouncycastle.cert.X509CertificateHolder; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import java.io.File; import java.io.IOException; +import java.nio.file.Path; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.cert.CertificateException; @@ -42,9 +40,9 @@ import java.time.temporal.ChronoUnit; import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests the Certificate codecs. @@ -53,12 +51,10 @@ public class TestCertificateCodec { private static OzoneConfiguration conf = new OzoneConfiguration(); private static final String COMPONENT = "test"; private SecurityConfig securityConfig; - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); - @Before - public void init() throws IOException { - conf.set(OZONE_METADATA_DIRS, temporaryFolder.newFolder().toString()); + @BeforeEach + public void init(@TempDir Path tempDir) { + conf.set(OZONE_METADATA_DIRS, tempDir.toString()); securityConfig = new SecurityConfig(conf); } @@ -118,9 +114,9 @@ public void testGetPEMEncodedString() * @throws CertificateException - on Error. */ @Test - public void testwriteCertificate() throws NoSuchProviderException, - NoSuchAlgorithmException, IOException, SCMSecurityException, - CertificateException { + public void testWriteCertificate(@TempDir Path basePath) + throws NoSuchProviderException, NoSuchAlgorithmException, + IOException, SCMSecurityException, CertificateException { HDDSKeyGenerator keyGenerator = new HDDSKeyGenerator(conf); X509CertificateHolder cert = @@ -137,16 +133,13 @@ public void testwriteCertificate() throws NoSuchProviderException, .build(); CertificateCodec codec = new CertificateCodec(securityConfig, COMPONENT); String pemString = codec.getPEMEncodedString(cert); - File basePath = temporaryFolder.newFolder(); - if (!basePath.exists()) { - Assert.assertTrue(basePath.mkdirs()); - } - codec.writeCertificate(basePath.toPath(), "pemcertificate.crt", + codec.writeCertificate(basePath, "pemcertificate.crt", pemString, false); X509CertificateHolder certHolder = - codec.readCertificate(basePath.toPath(), "pemcertificate.crt"); + codec.readCertificate(basePath, "pemcertificate.crt"); assertNotNull(certHolder); - assertEquals(cert.getSerialNumber(), certHolder.getSerialNumber()); + assertEquals(cert.getSerialNumber(), + certHolder.getSerialNumber()); } /** diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestCertificateSignRequest.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestCertificateSignRequest.java index 1aab7a5de47..430345707e1 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestCertificateSignRequest.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestCertificateSignRequest.java @@ -39,13 +39,13 @@ import org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.pkcs.PKCSException; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.IOException; +import java.nio.file.Path; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; @@ -60,13 +60,11 @@ public class TestCertificateSignRequest { private static OzoneConfiguration conf = new OzoneConfiguration(); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); private SecurityConfig securityConfig; - @Before - public void init() throws IOException { - conf.set(OZONE_METADATA_DIRS, temporaryFolder.newFolder().toString()); + @BeforeEach + public void init(@TempDir Path tempDir) throws IOException { + conf.set(OZONE_METADATA_DIRS, tempDir.toString()); securityConfig = new SecurityConfig(conf); } @@ -93,33 +91,33 @@ public void testGenerateCSR() throws NoSuchProviderException, // Check the Subject Name is in the expected format. String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(), subject, scmID, clusterID); - Assert.assertEquals(csr.getSubject().toString(), dnName); + Assertions.assertEquals(dnName, csr.getSubject().toString()); // Verify the public key info match byte[] encoded = keyPair.getPublic().getEncoded(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded)); SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo(); - Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo); + Assertions.assertEquals(subjectPublicKeyInfo, csrPublicKeyInfo); // Verify CSR with attribute for extensions - Assert.assertEquals(1, csr.getAttributes().length); + Assertions.assertEquals(1, csr.getAttributes().length); Extensions extensions = SecurityUtil.getPkcs9Extensions(csr); // Verify key usage extension Extension keyUsageExt = extensions.getExtension(Extension.keyUsage); - Assert.assertEquals(true, keyUsageExt.isCritical()); + Assertions.assertTrue(keyUsageExt.isCritical()); // Verify San extension not set - Assert.assertEquals(null, + Assertions.assertNull( extensions.getExtension(Extension.subjectAlternativeName)); // Verify signature in CSR ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider(securityConfig .getProvider()).build(csr.getSubjectPublicKeyInfo()); - Assert.assertEquals(true, csr.isSignatureValid(verifierProvider)); + Assertions.assertTrue(csr.isSignatureValid(verifierProvider)); } @Test @@ -153,22 +151,22 @@ public void testGenerateCSRwithSan() throws NoSuchProviderException, // Check the Subject Name is in the expected format. String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(), subject, scmID, clusterID); - Assert.assertEquals(csr.getSubject().toString(), dnName); + Assertions.assertEquals(dnName, csr.getSubject().toString()); // Verify the public key info match byte[] encoded = keyPair.getPublic().getEncoded(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded)); SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo(); - Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo); + Assertions.assertEquals(subjectPublicKeyInfo, csrPublicKeyInfo); // Verify CSR with attribute for extensions - Assert.assertEquals(1, csr.getAttributes().length); + Assertions.assertEquals(1, csr.getAttributes().length); Extensions extensions = SecurityUtil.getPkcs9Extensions(csr); // Verify key usage extension Extension sanExt = extensions.getExtension(Extension.keyUsage); - Assert.assertEquals(true, sanExt.isCritical()); + Assertions.assertTrue(sanExt.isCritical()); verifyServiceId(extensions); @@ -176,7 +174,7 @@ public void testGenerateCSRwithSan() throws NoSuchProviderException, ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().setProvider(securityConfig .getProvider()).build(csr.getSubjectPublicKeyInfo()); - Assert.assertEquals(true, csr.isSignatureValid(verifierProvider)); + Assertions.assertTrue(csr.isSignatureValid(verifierProvider)); } @Test @@ -200,7 +198,7 @@ public void testGenerateCSRWithInvalidParams() throws NoSuchProviderException, try { builder.setKey(null); builder.build(); - Assert.fail("Null Key should have failed."); + Assertions.fail("Null Key should have failed."); } catch (NullPointerException | IllegalArgumentException e) { builder.setKey(keyPair); } @@ -209,7 +207,7 @@ public void testGenerateCSRWithInvalidParams() throws NoSuchProviderException, try { builder.setSubject(null); builder.build(); - Assert.fail("Null/Blank Subject should have thrown."); + Assertions.fail("Null/Blank Subject should have thrown."); } catch (IllegalArgumentException e) { builder.setSubject(subject); } @@ -217,7 +215,7 @@ public void testGenerateCSRWithInvalidParams() throws NoSuchProviderException, try { builder.setSubject(""); builder.build(); - Assert.fail("Null/Blank Subject should have thrown."); + Assertions.fail("Null/Blank Subject should have thrown."); } catch (IllegalArgumentException e) { builder.setSubject(subject); } @@ -226,7 +224,7 @@ public void testGenerateCSRWithInvalidParams() throws NoSuchProviderException, try { builder.addIpAddress("255.255.255.*"); builder.build(); - Assert.fail("Invalid ip address"); + Assertions.fail("Invalid ip address"); } catch (IllegalArgumentException e) { } @@ -235,17 +233,17 @@ public void testGenerateCSRWithInvalidParams() throws NoSuchProviderException, // Check the Subject Name is in the expected format. String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(), subject, scmID, clusterID); - Assert.assertEquals(csr.getSubject().toString(), dnName); + Assertions.assertEquals(dnName, csr.getSubject().toString()); // Verify the public key info match byte[] encoded = keyPair.getPublic().getEncoded(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded)); SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo(); - Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo); + Assertions.assertEquals(subjectPublicKeyInfo, csrPublicKeyInfo); // Verify CSR with attribute for extensions - Assert.assertEquals(1, csr.getAttributes().length); + Assertions.assertEquals(1, csr.getAttributes().length); } @Test @@ -271,7 +269,7 @@ public void testCsrSerialization() throws NoSuchProviderException, // Verify de-serialized CSR matches with the original CSR PKCS10CertificationRequest dsCsr = new PKCS10CertificationRequest(csrBytes); - Assert.assertEquals(csr, dsCsr); + Assertions.assertEquals(csr, dsCsr); } private void verifyServiceId(Extensions extensions) { @@ -287,11 +285,11 @@ private void verifyServiceId(Extensions extensions) { Object o = iterator.next(); if (o instanceof ASN1ObjectIdentifier) { String oid = o.toString(); - Assert.assertEquals(oid, "2.16.840.1.113730.3.1.34"); + Assertions.assertEquals("2.16.840.1.113730.3.1.34", oid); } if (o instanceof DERTaggedObject) { String serviceName = ((DERTaggedObject)o).getObject().toString(); - Assert.assertEquals(serviceName, "OzoneMarketingCluster003"); + Assertions.assertEquals("OzoneMarketingCluster003", serviceName); } } } diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestRootCertificate.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestRootCertificate.java index 776aa4af564..b977ded58e8 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestRootCertificate.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/certificates/TestRootCertificate.java @@ -30,15 +30,14 @@ import org.bouncycastle.asn1.x509.Extension; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -import java.io.File; import java.io.IOException; import java.math.BigInteger; +import java.nio.file.Path; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; @@ -53,21 +52,17 @@ import static org.apache.hadoop.hdds.HddsConfigKeys.OZONE_METADATA_DIRS; import static org.apache.hadoop.hdds.security.x509.exceptions.CertificateException.ErrorCode.CSR_ERROR; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; /** * Test Class for Root Certificate generation. */ public class TestRootCertificate { private static OzoneConfiguration conf = new OzoneConfiguration(); - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); private SecurityConfig securityConfig; - @Before - public void init() throws IOException { - conf.set(OZONE_METADATA_DIRS, temporaryFolder.newFolder().toString()); + @BeforeEach + public void init(@TempDir Path tempDir) { + conf.set(OZONE_METADATA_DIRS, tempDir.toString()); securityConfig = new SecurityConfig(conf); } @@ -98,34 +93,34 @@ public void testAllFieldsAreExpected() X509CertificateHolder certificateHolder = builder.build(); //Assert that we indeed have a self signed certificate. - Assert.assertEquals(certificateHolder.getIssuer(), + Assertions.assertEquals(certificateHolder.getIssuer(), certificateHolder.getSubject()); // Make sure that NotBefore is before the current Date Date invalidDate = java.sql.Date.valueOf( notBefore.minus(1, ChronoUnit.DAYS)); - Assert.assertFalse( + Assertions.assertFalse( certificateHolder.getNotBefore() .before(invalidDate)); //Make sure the end date is honored. invalidDate = java.sql.Date.valueOf( notAfter.plus(1, ChronoUnit.DAYS)); - Assert.assertFalse( + Assertions.assertFalse( certificateHolder.getNotAfter() .after(invalidDate)); // Check the Subject Name and Issuer Name is in the expected format. String dnName = String.format(SelfSignedCertificate.getNameFormat(), subject, scmID, clusterID); - Assert.assertEquals(certificateHolder.getIssuer().toString(), dnName); - Assert.assertEquals(certificateHolder.getSubject().toString(), dnName); + Assertions.assertEquals(dnName, certificateHolder.getIssuer().toString()); + Assertions.assertEquals(dnName, certificateHolder.getSubject().toString()); // We did not ask for this Certificate to be a CertificateServer // certificate, hence that // extension should be null. - Assert.assertNull( + Assertions.assertNull( certificateHolder.getExtension(Extension.basicConstraints)); // Extract the Certificate and verify that certificate matches the public @@ -136,7 +131,7 @@ public void testAllFieldsAreExpected() } @Test - public void testCACert() + public void testCACert(@TempDir Path basePath) throws SCMSecurityException, NoSuchProviderException, NoSuchAlgorithmException, IOException, CertificateException { LocalDate notBefore = LocalDate.now(); @@ -183,27 +178,24 @@ public void testCACert() Extension basicExt = certificateHolder.getExtension(Extension.basicConstraints); - Assert.assertNotNull(basicExt); - Assert.assertTrue(basicExt.isCritical()); + Assertions.assertNotNull(basicExt); + Assertions.assertTrue(basicExt.isCritical()); // Since this code assigns ONE for the root certificate, we check if the // serial number is the expected number. - Assert.assertEquals(certificateHolder.getSerialNumber(), BigInteger.ONE); + Assertions.assertEquals(BigInteger.ONE, + certificateHolder.getSerialNumber()); CertificateCodec codec = new CertificateCodec(securityConfig, "scm"); String pemString = codec.getPEMEncodedString(certificateHolder); - File basePath = temporaryFolder.newFolder(); - if (!basePath.exists()) { - Assert.assertTrue(basePath.mkdirs()); - } - codec.writeCertificate(basePath.toPath(), "pemcertificate.crt", + codec.writeCertificate(basePath, "pemcertificate.crt", pemString, false); X509CertificateHolder loadedCert = - codec.readCertificate(basePath.toPath(), "pemcertificate.crt"); - assertNotNull(loadedCert); - assertEquals(certificateHolder.getSerialNumber(), + codec.readCertificate(basePath, "pemcertificate.crt"); + Assertions.assertNotNull(loadedCert); + Assertions.assertEquals(certificateHolder.getSerialNumber(), loadedCert.getSerialNumber()); } @@ -233,7 +225,7 @@ public void testInvalidParamFails() try { builder.setKey(null); builder.build(); - Assert.fail("Null Key should have failed."); + Assertions.fail("Null Key should have failed."); } catch (NullPointerException | IllegalArgumentException e) { builder.setKey(keyPair); } @@ -242,7 +234,7 @@ public void testInvalidParamFails() try { builder.setSubject(""); builder.build(); - Assert.fail("Null/Blank Subject should have thrown."); + Assertions.fail("Null/Blank Subject should have thrown."); } catch (IllegalArgumentException e) { builder.setSubject(subject); } @@ -251,7 +243,7 @@ public void testInvalidParamFails() try { builder.setScmID(null); builder.build(); - Assert.fail("Null/Blank SCM ID should have thrown."); + Assertions.fail("Null/Blank SCM ID should have thrown."); } catch (IllegalArgumentException e) { builder.setScmID(scmID); } @@ -261,7 +253,7 @@ public void testInvalidParamFails() try { builder.setClusterID(null); builder.build(); - Assert.fail("Null/Blank Cluster ID should have thrown."); + Assertions.fail("Null/Blank Cluster ID should have thrown."); } catch (IllegalArgumentException e) { builder.setClusterID(clusterID); } @@ -273,7 +265,7 @@ public void testInvalidParamFails() builder.setBeginDate(notAfter); builder.setEndDate(notBefore); builder.build(); - Assert.fail("Illegal dates should have thrown."); + Assertions.fail("Illegal dates should have thrown."); } catch (IllegalArgumentException e) { builder.setBeginDate(notBefore); builder.setEndDate(notAfter); @@ -287,12 +279,12 @@ public void testInvalidParamFails() X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certificateHolder); cert.verify(wrongKey.getPublic()); - Assert.fail("Invalid Key, should have thrown."); + Assertions.fail("Invalid Key, should have thrown."); } catch (SCMSecurityException | CertificateException | SignatureException | InvalidKeyException e) { builder.setKey(keyPair); } // Assert that we can create a certificate with all sane params. - Assert.assertNotNull(builder.build()); + Assertions.assertNotNull(builder.build()); } } diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/keys/TestKeyCodec.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/keys/TestKeyCodec.java index 254095691c1..190223c2486 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/keys/TestKeyCodec.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/security/x509/keys/TestKeyCodec.java @@ -20,7 +20,6 @@ package org.apache.hadoop.hdds.security.x509.keys; import static org.apache.hadoop.hdds.HddsConfigKeys.HDDS_METADATA_DIR_NAME; -import static org.junit.Assert.assertNotNull; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -43,29 +42,26 @@ import org.apache.hadoop.hdds.conf.OzoneConfiguration; import org.apache.hadoop.hdds.security.x509.SecurityConfig; import org.apache.ozone.test.LambdaTestUtils; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; /** * Test class for HDDS pem writer. */ public class TestKeyCodec { - @Rule - public TemporaryFolder temporaryFolder = new TemporaryFolder(); private OzoneConfiguration configuration; private SecurityConfig securityConfig; private String component; private HDDSKeyGenerator keyGenerator; private String prefix; - @Before - public void init() throws IOException { + @BeforeEach + public void init(@TempDir Path tempDir) throws IOException { configuration = new OzoneConfiguration(); - prefix = temporaryFolder.newFolder().toString(); + prefix = tempDir.toString(); configuration.set(HDDS_METADATA_DIR_NAME, prefix); keyGenerator = new HDDSKeyGenerator(configuration); securityConfig = new SecurityConfig(configuration); @@ -92,29 +88,29 @@ public void testWriteKey() // Assert that locations have been created. Path keyLocation = pemWriter.getSecurityConfig().getKeyLocation(component); - Assert.assertTrue(keyLocation.toFile().exists()); + Assertions.assertTrue(keyLocation.toFile().exists()); // Assert that locations are created in the locations that we specified // using the Config. - Assert.assertTrue(keyLocation.toString().startsWith(prefix)); + Assertions.assertTrue(keyLocation.toString().startsWith(prefix)); Path privateKeyPath = Paths.get(keyLocation.toString(), pemWriter.getSecurityConfig().getPrivateKeyFileName()); - Assert.assertTrue(privateKeyPath.toFile().exists()); + Assertions.assertTrue(privateKeyPath.toFile().exists()); Path publicKeyPath = Paths.get(keyLocation.toString(), pemWriter.getSecurityConfig().getPublicKeyFileName()); - Assert.assertTrue(publicKeyPath.toFile().exists()); + Assertions.assertTrue(publicKeyPath.toFile().exists()); // Read the private key and test if the expected String in the PEM file // format exists. byte[] privateKey = Files.readAllBytes(privateKeyPath); String privateKeydata = new String(privateKey, StandardCharsets.UTF_8); - Assert.assertTrue(privateKeydata.contains("PRIVATE KEY")); + Assertions.assertTrue(privateKeydata.contains("PRIVATE KEY")); // Read the public key and test if the expected String in the PEM file // format exists. byte[] publicKey = Files.readAllBytes(publicKeyPath); String publicKeydata = new String(publicKey, StandardCharsets.UTF_8); - Assert.assertTrue(publicKeydata.contains("PUBLIC KEY")); + Assertions.assertTrue(publicKeydata.contains("PUBLIC KEY")); // Let us decode the PEM file and parse it back into binary. KeyFactory kf = KeyFactory.getInstance( @@ -132,8 +128,8 @@ public void testWriteKey() byte[] keyBytes = Base64.decodeBase64(privateKeydata); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); PrivateKey privateKeyDecoded = kf.generatePrivate(spec); - assertNotNull("Private Key should not be null", - privateKeyDecoded); + Assertions.assertNotNull(privateKeyDecoded, + "Private Key should not be null"); // Let us decode the public key and veriy that we can parse it back into // binary. @@ -145,29 +141,28 @@ public void testWriteKey() keyBytes = Base64.decodeBase64(publicKeydata); X509EncodedKeySpec pubKeyspec = new X509EncodedKeySpec(keyBytes); PublicKey publicKeyDecoded = kf.generatePublic(pubKeyspec); - assertNotNull("Public Key should not be null", - publicKeyDecoded); + Assertions.assertNotNull(publicKeyDecoded, "Public Key should not be null"); // Now let us assert the permissions on the Directories and files are as // expected. Set expectedSet = pemWriter.getFilePermissionSet(); Set currentSet = Files.getPosixFilePermissions(privateKeyPath); - Assert.assertEquals(expectedSet.size(), currentSet.size()); + Assertions.assertEquals(expectedSet.size(), currentSet.size()); currentSet.removeAll(expectedSet); - Assert.assertEquals(0, currentSet.size()); + Assertions.assertEquals(0, currentSet.size()); currentSet = Files.getPosixFilePermissions(publicKeyPath); currentSet.removeAll(expectedSet); - Assert.assertEquals(0, currentSet.size()); + Assertions.assertEquals(0, currentSet.size()); expectedSet = pemWriter.getDirPermissionSet(); currentSet = Files.getPosixFilePermissions(keyLocation); - Assert.assertEquals(expectedSet.size(), currentSet.size()); + Assertions.assertEquals(expectedSet.size(), currentSet.size()); currentSet.removeAll(expectedSet); - Assert.assertEquals(0, currentSet.size()); + Assertions.assertEquals(0, currentSet.size()); } /** @@ -232,7 +227,7 @@ public void testReadWritePublicKeywithoutArgs() keycodec.writeKey(kp); PublicKey pubKey = keycodec.readPublicKey(); - assertNotNull(pubKey); + Assertions.assertNotNull(pubKey); } } \ No newline at end of file diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestServerUtils.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestServerUtils.java index 1ebde84d51c..61b1fe4b57a 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestServerUtils.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/server/TestServerUtils.java @@ -25,21 +25,18 @@ import org.apache.hadoop.test.PathUtils; import org.apache.commons.io.FileUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link ServerUtils}. */ public class TestServerUtils { - @Rule - public ExpectedException thrown = ExpectedException.none(); - /** * Test {@link ServerUtils#getScmDbDir}. */ @@ -84,14 +81,14 @@ public void testGetScmDbDirWithFallback() { @Test public void testNoScmDbDirConfigured() { - thrown.expect(IllegalArgumentException.class); - ServerUtils.getScmDbDir(new OzoneConfiguration()); + assertThrows(IllegalArgumentException.class, + () -> ServerUtils.getScmDbDir(new OzoneConfiguration())); } @Test public void ozoneMetadataDirIsMandatory() { - thrown.expect(IllegalArgumentException.class); - ServerUtils.getOzoneMetaDirPath(new OzoneConfiguration()); + assertThrows(IllegalArgumentException.class, + () -> ServerUtils.getOzoneMetaDirPath(new OzoneConfiguration())); } @Test @@ -114,9 +111,8 @@ public void ozoneMetadataDirAcceptsSingleItem() { public void ozoneMetadataDirRejectsList() { final OzoneConfiguration conf = new OzoneConfiguration(); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, "/data/meta1,/data/meta2"); - thrown.expect(IllegalArgumentException.class); - - ServerUtils.getOzoneMetaDirPath(conf); + assertThrows(IllegalArgumentException.class, + () -> ServerUtils.getOzoneMetaDirPath(conf)); } } diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBConfigFromFile.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBConfigFromFile.java index bce88c1a11f..11b386c6d7b 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBConfigFromFile.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBConfigFromFile.java @@ -20,12 +20,11 @@ package org.apache.hadoop.hdds.utils.db; import org.apache.commons.io.FileUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +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.io.TempDir; import org.rocksdb.ColumnFamilyDescriptor; import org.rocksdb.ColumnFamilyOptions; import org.rocksdb.DBOptions; @@ -34,6 +33,7 @@ import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; @@ -49,13 +49,10 @@ public class TestDBConfigFromFile { private static final String DB_FILE = "test.db"; private static final String INI_FILE = getOptionsFileNameFromDB(DB_FILE); - @Rule - public TemporaryFolder folder = new TemporaryFolder(); - @Before - public void setUp() throws Exception { - System.setProperty(DBConfigFromFile.CONFIG_DIR, - folder.newFolder().toString()); + @BeforeEach + public void setUp(@TempDir Path tempDir) throws Exception { + System.setProperty(DBConfigFromFile.CONFIG_DIR, tempDir.toString()); ClassLoader classLoader = getClass().getClassLoader(); File testData = new File(classLoader.getResource(INI_FILE).getFile()); File dest = Paths.get( @@ -63,7 +60,7 @@ public void setUp() throws Exception { FileUtils.copyFile(testData, dest); } - @After + @AfterEach public void tearDown() throws Exception { } @@ -87,10 +84,10 @@ public void readFromFile() throws IOException { // Some Random Values Defined in the test.db.ini, we verify that we are // able to get values that are defined in the test.db.ini. - Assert.assertNotNull(options); - Assert.assertEquals(551615L, options.maxManifestFileSize()); - Assert.assertEquals(1000L, options.keepLogFileNum()); - Assert.assertEquals(1048576, options.writableFileMaxBufferSize()); + Assertions.assertNotNull(options); + Assertions.assertEquals(551615L, options.maxManifestFileSize()); + Assertions.assertEquals(1000L, options.keepLogFileNum()); + Assertions.assertEquals(1048576, options.writableFileMaxBufferSize()); } @Test @@ -112,6 +109,6 @@ public void readFromFileInvalidConfig() throws IOException { columnFamilyDescriptors); // This has to return a Null, since we have config defined for badfile.db - Assert.assertNull(options); + Assertions.assertNull(options); } } \ No newline at end of file diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBStoreBuilder.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBStoreBuilder.java index e78bcb00855..eca86d40ebb 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBStoreBuilder.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestDBStoreBuilder.java @@ -21,90 +21,67 @@ import org.apache.commons.lang3.RandomStringUtils; import org.apache.hadoop.hdds.conf.OzoneConfiguration; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.rocksdb.ColumnFamilyOptions; -import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.nio.file.Path; /** * Tests RDBStore creation. */ public class TestDBStoreBuilder { - @Rule - public TemporaryFolder folder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - System.setProperty(DBConfigFromFile.CONFIG_DIR, - folder.newFolder().toString()); + @BeforeEach + public void setUp(@TempDir Path tempDir) throws Exception { + System.setProperty(DBConfigFromFile.CONFIG_DIR, tempDir.toString()); } @Test - public void builderWithoutAnyParams() throws IOException { + public void builderWithoutAnyParams() { OzoneConfiguration conf = new OzoneConfiguration(); - thrown.expect(IOException.class); - DBStoreBuilder.newBuilder(conf).build(); + Assertions.assertThrows(IOException.class, + () -> DBStoreBuilder.newBuilder(conf).build()); } @Test - public void builderWithOneParamV1() throws IOException { + public void builderWithOneParamV1() { OzoneConfiguration conf = new OzoneConfiguration(); - thrown.expect(IOException.class); - DBStoreBuilder.newBuilder(conf) - .setName("Test.db") - .build(); + Assertions.assertThrows(IOException.class, + () -> DBStoreBuilder.newBuilder(conf).setName("Test.db").build()); } @Test - public void builderWithOneParamV2() throws IOException { + public void builderWithOneParamV2(@TempDir Path tempDir) { OzoneConfiguration conf = new OzoneConfiguration(); - File newFolder = folder.newFolder(); - if (!newFolder.exists()) { - Assert.assertTrue(newFolder.mkdirs()); - } - thrown.expect(IOException.class); - DBStoreBuilder.newBuilder(conf) - .setPath(newFolder.toPath()) - .build(); + Assertions.assertThrows(IOException.class, + () -> DBStoreBuilder.newBuilder(conf).setPath(tempDir).build()); } @Test - public void builderWithOpenClose() throws Exception { + public void builderWithOpenClose(@TempDir Path tempDir) throws Exception { OzoneConfiguration conf = new OzoneConfiguration(); - File newFolder = folder.newFolder(); - if (!newFolder.exists()) { - Assert.assertTrue(newFolder.mkdirs()); - } DBStore dbStore = DBStoreBuilder.newBuilder(conf) .setName("Test.db") - .setPath(newFolder.toPath()) + .setPath(tempDir) .build(); // Nothing to do just open and Close. dbStore.close(); } @Test - public void builderWithDoubleTableName() throws Exception { + public void builderWithDoubleTableName(@TempDir Path tempDir) + throws Exception { OzoneConfiguration conf = new OzoneConfiguration(); - File newFolder = folder.newFolder(); - if (!newFolder.exists()) { - Assert.assertTrue(newFolder.mkdirs()); - } // Registering a new table with the same name should replace the previous // one. DBStore dbStore = DBStoreBuilder.newBuilder(conf) .setName("Test.db") - .setPath(newFolder.toPath()) + .setPath(tempDir) .addTable("FIRST") .addTable("FIRST", new ColumnFamilyOptions()) .build(); @@ -117,22 +94,18 @@ public void builderWithDoubleTableName() throws Exception { RandomStringUtils.random(9).getBytes(StandardCharsets.UTF_8); firstTable.put(key, value); byte[] temp = firstTable.get(key); - Assert.assertArrayEquals(value, temp); + Assertions.assertArrayEquals(value, temp); } dbStore.close(); } @Test - public void builderWithDataWrites() throws Exception { + public void builderWithDataWrites(@TempDir Path tempDir) throws Exception { OzoneConfiguration conf = new OzoneConfiguration(); - File newFolder = folder.newFolder(); - if (!newFolder.exists()) { - Assert.assertTrue(newFolder.mkdirs()); - } try (DBStore dbStore = DBStoreBuilder.newBuilder(conf) .setName("Test.db") - .setPath(newFolder.toPath()) + .setPath(tempDir) .addTable("First") .addTable("Second") .build()) { @@ -143,25 +116,22 @@ public void builderWithDataWrites() throws Exception { RandomStringUtils.random(9).getBytes(StandardCharsets.UTF_8); firstTable.put(key, value); byte[] temp = firstTable.get(key); - Assert.assertArrayEquals(value, temp); + Assertions.assertArrayEquals(value, temp); } try (Table secondTable = dbStore.getTable("Second")) { - Assert.assertTrue(secondTable.isEmpty()); + Assertions.assertTrue(secondTable.isEmpty()); } } } @Test - public void builderWithDiskProfileWrites() throws Exception { + public void builderWithDiskProfileWrites(@TempDir Path tempDir) + throws Exception { OzoneConfiguration conf = new OzoneConfiguration(); - File newFolder = folder.newFolder(); - if (!newFolder.exists()) { - Assert.assertTrue(newFolder.mkdirs()); - } try (DBStore dbStore = DBStoreBuilder.newBuilder(conf) .setName("Test.db") - .setPath(newFolder.toPath()) + .setPath(tempDir) .addTable("First") .addTable("Second") .setProfile(DBProfile.DISK) @@ -173,11 +143,11 @@ public void builderWithDiskProfileWrites() throws Exception { RandomStringUtils.random(9).getBytes(StandardCharsets.UTF_8); firstTable.put(key, value); byte[] temp = firstTable.get(key); - Assert.assertArrayEquals(value, temp); + Assertions.assertArrayEquals(value, temp); } try (Table secondTable = dbStore.getTable("Second")) { - Assert.assertTrue(secondTable.isEmpty()); + Assertions.assertTrue(secondTable.isEmpty()); } } } diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBStore.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBStore.java index ed8744ceba8..b40fe61c1dc 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBStore.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBStore.java @@ -20,6 +20,7 @@ package org.apache.hadoop.hdds.utils.db; import javax.management.MBeanServer; +import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import java.nio.charset.StandardCharsets; @@ -34,13 +35,11 @@ import org.apache.hadoop.hdds.StringUtils; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.TemporaryFolder; +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.io.TempDir; import org.rocksdb.ColumnFamilyOptions; import org.rocksdb.DBOptions; import org.rocksdb.RocksDB; @@ -56,16 +55,12 @@ public class TestRDBStore { "First", "Second", "Third", "Fourth", "Fifth", "Sixth"); - @Rule - public TemporaryFolder folder = new TemporaryFolder(); - @Rule - public ExpectedException thrown = ExpectedException.none(); private RDBStore rdbStore = null; private DBOptions options = null; private Set configSet; - @Before - public void setUp() throws Exception { + @BeforeEach + public void setUp(@TempDir File tempDir) throws Exception { options = new DBOptions(); options.setCreateIfMissing(true); options.setCreateMissingColumnFamilies(true); @@ -78,10 +73,10 @@ public void setUp() throws Exception { TableConfig newConfig = new TableConfig(name, new ColumnFamilyOptions()); configSet.add(newConfig); } - rdbStore = new RDBStore(folder.newFolder(), options, configSet); + rdbStore = new RDBStore(tempDir, options, configSet); } - @After + @AfterEach public void tearDown() throws Exception { if (rdbStore != null) { rdbStore.close(); @@ -90,7 +85,7 @@ public void tearDown() throws Exception { private void insertRandomData(RDBStore dbStore, int familyIndex) throws Exception { try (Table firstTable = dbStore.getTable(families.get(familyIndex))) { - Assert.assertNotNull("Table cannot be null", firstTable); + Assertions.assertNotNull(firstTable, "Table cannot be null"); for (int x = 0; x < 100; x++) { byte[] key = RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8); @@ -103,24 +98,19 @@ private void insertRandomData(RDBStore dbStore, int familyIndex) @Test public void compactDB() throws Exception { - try (RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet)) { - Assert.assertNotNull("DB Store cannot be null", newStore); - insertRandomData(newStore, 1); - // This test does not assert anything if there is any error this test - // will throw and fail. - newStore.compactDB(); - } + Assertions.assertNotNull(rdbStore, "DB Store cannot be null"); + insertRandomData(rdbStore, 1); + // This test does not assert anything if there is any error this test + // will throw and fail. + rdbStore.compactDB(); } @Test public void close() throws Exception { - RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet); - Assert.assertNotNull("DBStore cannot be null", newStore); + Assertions.assertNotNull(rdbStore, "DBStore cannot be null"); // This test does not assert anything if there is any error this test // will throw and fail. - newStore.close(); + rdbStore.close(); } @Test @@ -137,12 +127,12 @@ public void moveKey() throws Exception { rdbStore.move(key, firstTable, secondTable); byte[] newvalue = secondTable.get(key); // Make sure we have value in the second table - Assert.assertNotNull(newvalue); + Assertions.assertNotNull(newvalue); //and it is same as what we wrote to the FirstTable - Assert.assertArrayEquals(value, newvalue); + Assertions.assertArrayEquals(value, newvalue); } // After move this key must not exist in the first table. - Assert.assertNull(firstTable.get(key)); + Assertions.assertNull(firstTable.get(key)); } } @@ -162,10 +152,10 @@ public void moveWithValue() throws Exception { rdbStore.move(key, nextValue, firstTable, secondTable); byte[] newvalue = secondTable.get(key); // Make sure we have value in the second table - Assert.assertNotNull(newvalue); + Assertions.assertNotNull(newvalue); //and it is not same as what we wrote to the FirstTable, and equals // the new value. - Assert.assertArrayEquals(nextValue, newvalue); + Assertions.assertArrayEquals(nextValue, newvalue); } } @@ -173,20 +163,17 @@ public void moveWithValue() throws Exception { @Test public void getEstimatedKeyCount() throws Exception { - try (RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet)) { - Assert.assertNotNull("DB Store cannot be null", newStore); + Assertions.assertNotNull(rdbStore, "DB Store cannot be null"); - // Write 100 keys to the first table. - insertRandomData(newStore, 1); + // Write 100 keys to the first table. + insertRandomData(rdbStore, 1); - // Write 100 keys to the secondTable table. - insertRandomData(newStore, 2); + // Write 100 keys to the secondTable table. + insertRandomData(rdbStore, 2); - // Let us make sure that our estimate is not off by 10% - Assert.assertTrue(newStore.getEstimatedKeyCount() > 180 - || newStore.getEstimatedKeyCount() < 220); - } + // Let us make sure that our estimate is not off by 10% + Assertions.assertTrue(rdbStore.getEstimatedKeyCount() > 180 + || rdbStore.getEstimatedKeyCount() < 220); } @Test @@ -208,28 +195,28 @@ public void getStatMBeanName() throws Exception { Object keysWritten = platformMBeanServer .getAttribute(rdbStore.getStatMBeanName(), "NUMBER_KEYS_WRITTEN"); - Assert.assertTrue(((Long) keysWritten) >= 99L); + Assertions.assertTrue(((Long) keysWritten) >= 99L); Object dbWriteAverage = platformMBeanServer .getAttribute(rdbStore.getStatMBeanName(), "DB_WRITE_AVERAGE"); - Assert.assertTrue((double) dbWriteAverage > 0); + Assertions.assertTrue((double) dbWriteAverage > 0); } @Test public void getTable() throws Exception { for (String tableName : families) { try (Table table = rdbStore.getTable(tableName)) { - Assert.assertNotNull(tableName + "is null", table); + Assertions.assertNotNull(table, tableName + "is null"); } } - thrown.expect(IOException.class); - rdbStore.getTable("ATableWithNoName"); + Assertions.assertThrows(IOException.class, + () -> rdbStore.getTable("ATableWithNoName")); } @Test public void listTables() throws Exception { List tableList = rdbStore.listTables(); - Assert.assertNotNull("Table list cannot be null", tableList); + Assertions.assertNotNull(tableList, "Table list cannot be null"); Map hashTable = new HashMap<>(); for (Table t : tableList) { @@ -239,101 +226,84 @@ public void listTables() throws Exception { int count = families.size(); // Assert that we have all the tables in the list and no more. for (String name : families) { - Assert.assertTrue(hashTable.containsKey(name)); + Assertions.assertTrue(hashTable.containsKey(name)); count--; } - Assert.assertEquals(0, count); + Assertions.assertEquals(0, count); } @Test public void testRocksDBCheckpoint() throws Exception { - try (RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet)) { - Assert.assertNotNull("DB Store cannot be null", newStore); - - insertRandomData(newStore, 1); - DBCheckpoint checkpoint = - newStore.getCheckpoint(true); - Assert.assertNotNull(checkpoint); - - RDBStore restoredStoreFromCheckPoint = - new RDBStore(checkpoint.getCheckpointLocation().toFile(), - options, configSet); - - // Let us make sure that our estimate is not off by 10% - Assert.assertTrue( - restoredStoreFromCheckPoint.getEstimatedKeyCount() > 90 - || restoredStoreFromCheckPoint.getEstimatedKeyCount() < 110); - checkpoint.cleanupCheckpoint(); - } - + Assertions.assertNotNull(rdbStore, "DB Store cannot be null"); + + insertRandomData(rdbStore, 1); + DBCheckpoint checkpoint = + rdbStore.getCheckpoint(true); + Assertions.assertNotNull(checkpoint); + + RDBStore restoredStoreFromCheckPoint = + new RDBStore(checkpoint.getCheckpointLocation().toFile(), + options, configSet); + + // Let us make sure that our estimate is not off by 10% + Assertions.assertTrue( + restoredStoreFromCheckPoint.getEstimatedKeyCount() > 90 + || restoredStoreFromCheckPoint.getEstimatedKeyCount() < 110); + checkpoint.cleanupCheckpoint(); } @Test public void testRocksDBCheckpointCleanup() throws Exception { - try (RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet)) { - Assert.assertNotNull("DB Store cannot be null", newStore); - - insertRandomData(newStore, 1); - DBCheckpoint checkpoint = - newStore.getCheckpoint(true); - Assert.assertNotNull(checkpoint); - - Assert.assertTrue(Files.exists( - checkpoint.getCheckpointLocation())); - checkpoint.cleanupCheckpoint(); - Assert.assertFalse(Files.exists( - checkpoint.getCheckpointLocation())); - } + Assertions.assertNotNull(rdbStore, "DB Store cannot be null"); + + insertRandomData(rdbStore, 1); + DBCheckpoint checkpoint = + rdbStore.getCheckpoint(true); + Assertions.assertNotNull(checkpoint); + + Assertions.assertTrue(Files.exists( + checkpoint.getCheckpointLocation())); + checkpoint.cleanupCheckpoint(); + Assertions.assertFalse(Files.exists( + checkpoint.getCheckpointLocation())); } @Test public void testGetDBUpdatesSince() throws Exception { - try (RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet)) { - - try (Table firstTable = newStore.getTable(families.get(1))) { - firstTable.put( - org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key1"), - org.apache.commons.codec.binary.StringUtils - .getBytesUtf16("Value1")); - firstTable.put( - org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key2"), - org.apache.commons.codec.binary.StringUtils - .getBytesUtf16("Value2")); - } - Assert.assertTrue( - newStore.getDb().getLatestSequenceNumber() == 2); - - DBUpdatesWrapper dbUpdatesSince = newStore.getUpdatesSince(0); - Assert.assertEquals(2, dbUpdatesSince.getData().size()); + try (Table firstTable = rdbStore.getTable(families.get(1))) { + firstTable.put( + org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key1"), + org.apache.commons.codec.binary.StringUtils + .getBytesUtf16("Value1")); + firstTable.put( + org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key2"), + org.apache.commons.codec.binary.StringUtils + .getBytesUtf16("Value2")); } + Assertions.assertEquals(2, rdbStore.getDb().getLatestSequenceNumber()); + + DBUpdatesWrapper dbUpdatesSince = rdbStore.getUpdatesSince(0); + Assertions.assertEquals(2, dbUpdatesSince.getData().size()); } @Test public void testGetDBUpdatesSinceWithLimitCount() throws Exception { - try (RDBStore newStore = - new RDBStore(folder.newFolder(), options, configSet)) { - - try (Table firstTable = newStore.getTable(families.get(1))) { - firstTable.put( - org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key1"), - org.apache.commons.codec.binary.StringUtils - .getBytesUtf16("Value1")); - firstTable.put( - org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key2"), - org.apache.commons.codec.binary.StringUtils - .getBytesUtf16("Value2")); - } - Assert.assertTrue( - newStore.getDb().getLatestSequenceNumber() == 2); - - DBUpdatesWrapper dbUpdatesSince = newStore.getUpdatesSince(0, 1); - Assert.assertEquals(1, dbUpdatesSince.getData().size()); + try (Table firstTable = rdbStore.getTable(families.get(1))) { + firstTable.put( + org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key1"), + org.apache.commons.codec.binary.StringUtils + .getBytesUtf16("Value1")); + firstTable.put( + org.apache.commons.codec.binary.StringUtils.getBytesUtf16("Key2"), + org.apache.commons.codec.binary.StringUtils + .getBytesUtf16("Value2")); } + Assertions.assertEquals(2, rdbStore.getDb().getLatestSequenceNumber()); + + DBUpdatesWrapper dbUpdatesSince = rdbStore.getUpdatesSince(0, 1); + Assertions.assertEquals(1, dbUpdatesSince.getData().size()); } @Test @@ -365,9 +335,9 @@ public void testDowngrade() throws Exception { rdbStore = new RDBStore(rdbStore.getDbLocation(), options, configSet); for (String family : familiesMinusOne) { try (Table table = rdbStore.getTable(family)) { - Assert.assertNotNull(family + "is null", table); + Assertions.assertNotNull(table, family + "is null"); Object val = table.get(family.getBytes(StandardCharsets.UTF_8)); - Assert.assertNotNull(val); + Assertions.assertNotNull(val); } } @@ -375,9 +345,9 @@ public void testDowngrade() throws Exception { // we do not use it. String extraFamily = families.get(families.size() - 1); try (Table table = rdbStore.getTable(extraFamily)) { - Assert.assertNotNull(extraFamily + "is null", table); + Assertions.assertNotNull(table, extraFamily + "is null"); Object val = table.get(extraFamily.getBytes(StandardCharsets.UTF_8)); - Assert.assertNotNull(val); + Assertions.assertNotNull(val); } } diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBTableStore.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBTableStore.java index 0f1858b902d..00a86d6ac7a 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBTableStore.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestRDBTableStore.java @@ -29,14 +29,13 @@ import java.util.Set; import org.apache.hadoop.hdds.StringUtils; - import org.apache.commons.lang3.RandomStringUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.rocksdb.ColumnFamilyOptions; import org.rocksdb.DBOptions; import org.rocksdb.RocksDB; @@ -54,23 +53,30 @@ public class TestRDBTableStore { "Fourth", "Fifth", "Sixth", "Seventh", "Eighth"); - @Rule - public TemporaryFolder folder = new TemporaryFolder(); private RDBStore rdbStore = null; private DBOptions options = null; + private static byte[][] bytesOf; + + @BeforeAll + public static void initConstants() { + bytesOf = new byte[4][]; + for (int i = 1; i <= 3; i++) { + bytesOf[i] = Integer.toString(i).getBytes(StandardCharsets.UTF_8); + } + } private static boolean consume(Table.KeyValue keyValue) { count++; try { - Assert.assertNotNull(keyValue.getKey()); + Assertions.assertNotNull(keyValue.getKey()); } catch (IOException ex) { - Assert.fail("Unexpected Exception " + ex.toString()); + Assertions.fail("Unexpected Exception " + ex); } return true; } - @Before - public void setUp() throws Exception { + @BeforeEach + public void setUp(@TempDir File tempDir) throws Exception { options = new DBOptions(); options.setCreateIfMissing(true); options.setCreateMissingColumnFamilies(true); @@ -84,10 +90,10 @@ public void setUp() throws Exception { TableConfig newConfig = new TableConfig(name, new ColumnFamilyOptions()); configSet.add(newConfig); } - rdbStore = new RDBStore(folder.newFolder(), options, configSet); + rdbStore = new RDBStore(tempDir, options, configSet); } - @After + @AfterEach public void tearDown() throws Exception { if (rdbStore != null) { rdbStore.close(); @@ -97,8 +103,8 @@ public void tearDown() throws Exception { @Test public void getHandle() throws Exception { try (Table testTable = rdbStore.getTable("First")) { - Assert.assertNotNull(testTable); - Assert.assertNotNull(((RDBTable) testTable).getHandle()); + Assertions.assertNotNull(testTable); + Assertions.assertNotNull(((RDBTable) testTable).getHandle()); } } @@ -110,12 +116,12 @@ public void putGetAndEmpty() throws Exception { byte[] value = RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8); testTable.put(key, value); - Assert.assertFalse(testTable.isEmpty()); + Assertions.assertFalse(testTable.isEmpty()); byte[] readValue = testTable.get(key); - Assert.assertArrayEquals(value, readValue); + Assertions.assertArrayEquals(value, readValue); } try (Table secondTable = rdbStore.getTable("Second")) { - Assert.assertTrue(secondTable.isEmpty()); + Assertions.assertTrue(secondTable.isEmpty()); } } @@ -148,11 +154,11 @@ public void delete() throws Exception { } for (int x = 0; x < validKeys.size(); x++) { - Assert.assertNotNull(testTable.get(validKeys.get(0))); + Assertions.assertNotNull(testTable.get(validKeys.get(0))); } for (int x = 0; x < deletedKeys.size(); x++) { - Assert.assertNull(testTable.get(deletedKeys.get(0))); + Assertions.assertNull(testTable.get(deletedKeys.get(0))); } } } @@ -166,14 +172,14 @@ public void batchPut() throws Exception { RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8); byte[] value = RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8); - Assert.assertNull(testTable.get(key)); + Assertions.assertNull(testTable.get(key)); //when testTable.putWithBatch(batch, key, value); rdbStore.commitBatchOperation(batch); //then - Assert.assertNotNull(testTable.get(key)); + Assertions.assertNotNull(testTable.get(key)); } } @@ -188,7 +194,7 @@ public void batchDelete() throws Exception { byte[] value = RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8); testTable.put(key, value); - Assert.assertNotNull(testTable.get(key)); + Assertions.assertNotNull(testTable.get(key)); //when @@ -196,7 +202,7 @@ public void batchDelete() throws Exception { rdbStore.commitBatchOperation(batch); //then - Assert.assertNull(testTable.get(key)); + Assertions.assertNull(testTable.get(key)); } } @@ -218,17 +224,17 @@ public void forEachAndIterator() throws Exception { localCount++; } - Assert.assertEquals(iterCount, localCount); + Assertions.assertEquals(iterCount, localCount); iter.seekToFirst(); iter.forEachRemaining(TestRDBTableStore::consume); - Assert.assertEquals(iterCount, count); + Assertions.assertEquals(iterCount, count); } } } @Test - public void testIsExist() throws Exception { + public void testIsExist(@TempDir File rdbLocation) throws Exception { DBOptions rocksDBOptions = new DBOptions(); rocksDBOptions.setCreateIfMissing(true); rocksDBOptions.setCreateMissingColumnFamilies(true); @@ -240,7 +246,7 @@ public void testIsExist() throws Exception { new ColumnFamilyOptions()); configSet.add(newConfig); - File rdbLocation = folder.newFolder(); + rdbStore.close(); // TODO: HDDS-6773 RDBStore dbStore = new RDBStore(rdbLocation, rocksDBOptions, configSet); byte[] key = RandomStringUtils.random(10, true, false) @@ -252,20 +258,20 @@ public void testIsExist() throws Exception { testTable.put(key, value); // Test if isExist returns true for a key that definitely exists. - Assert.assertTrue(testTable.isExist(key)); + Assertions.assertTrue(testTable.isExist(key)); // Test if isExist returns false for a key that has been deleted. testTable.delete(key); - Assert.assertFalse(testTable.isExist(key)); + Assertions.assertFalse(testTable.isExist(key)); byte[] invalidKey = RandomStringUtils.random(5).getBytes(StandardCharsets.UTF_8); // Test if isExist returns false for a key that is definitely not present. - Assert.assertFalse(testTable.isExist(invalidKey)); + Assertions.assertFalse(testTable.isExist(invalidKey)); RDBMetrics rdbMetrics = dbStore.getMetrics(); - Assert.assertEquals(3, rdbMetrics.getNumDBKeyMayExistChecks()); - Assert.assertTrue(rdbMetrics.getNumDBKeyMayExistMisses() == 0); + Assertions.assertEquals(3, rdbMetrics.getNumDBKeyMayExistChecks()); + Assertions.assertEquals(0, rdbMetrics.getNumDBKeyMayExistMisses()); // Reinsert key for further testing. testTable.put(key, value); @@ -278,7 +284,7 @@ public void testIsExist() throws Exception { dbStore = new RDBStore(rdbLocation, rocksDBOptions, configSet); try (Table testTable = dbStore.getTable(tableName)) { // Verify isExist works with key not in block cache. - Assert.assertTrue(testTable.isExist(key)); + Assertions.assertTrue(testTable.isExist(key)); } finally { dbStore.close(); } @@ -286,7 +292,7 @@ public void testIsExist() throws Exception { @Test - public void testGetIfExist() throws Exception { + public void testGetIfExist(@TempDir File rdbLocation) throws Exception { DBOptions rocksDBOptions = new DBOptions(); rocksDBOptions.setCreateIfMissing(true); rocksDBOptions.setCreateMissingColumnFamilies(true); @@ -298,7 +304,7 @@ public void testGetIfExist() throws Exception { new ColumnFamilyOptions()); configSet.add(newConfig); - File rdbLocation = folder.newFolder(); + rdbStore.close(); // TODO: HDDS-6773 RDBStore dbStore = new RDBStore(rdbLocation, rocksDBOptions, configSet); byte[] key = RandomStringUtils.random(10, true, false) @@ -310,24 +316,23 @@ public void testGetIfExist() throws Exception { testTable.put(key, value); // Test if isExist returns value for a key that definitely exists. - Assert.assertNotNull(testTable.getIfExist(key)); + Assertions.assertNotNull(testTable.getIfExist(key)); // Test if isExist returns null for a key that has been deleted. testTable.delete(key); - Assert.assertNull(testTable.getIfExist(key)); + Assertions.assertNull(testTable.getIfExist(key)); byte[] invalidKey = RandomStringUtils.random(5).getBytes(StandardCharsets.UTF_8); // Test if isExist returns null for a key that is definitely not present. - Assert.assertNull(testTable.getIfExist(invalidKey)); + Assertions.assertNull(testTable.getIfExist(invalidKey)); RDBMetrics rdbMetrics = dbStore.getMetrics(); - Assert.assertEquals(3, rdbMetrics.getNumDBKeyGetIfExistChecks()); - + Assertions.assertEquals(3, rdbMetrics.getNumDBKeyGetIfExistChecks()); - Assert.assertEquals(0, rdbMetrics.getNumDBKeyGetIfExistMisses()); + Assertions.assertEquals(0, rdbMetrics.getNumDBKeyGetIfExistMisses()); - Assert.assertEquals(1, rdbMetrics.getNumDBKeyGetIfExistGets()); + Assertions.assertEquals(1, rdbMetrics.getNumDBKeyGetIfExistGets()); // Reinsert key for further testing. testTable.put(key, value); @@ -340,7 +345,7 @@ public void testGetIfExist() throws Exception { dbStore = new RDBStore(rdbLocation, rocksDBOptions, configSet); try (Table testTable = dbStore.getTable(tableName)) { // Verify getIfExists works with key not in block cache. - Assert.assertNotNull(testTable.getIfExist(key)); + Assertions.assertNotNull(testTable.getIfExist(key)); } finally { dbStore.close(); } @@ -361,7 +366,7 @@ public void testCountEstimatedRowsInTable() throws Exception { } long keyCount = testTable.getEstimatedKeyCount(); // The result should be larger than zero but not exceed(?) numKeys - Assert.assertTrue(keyCount > 0 && keyCount <= numKeys); + Assertions.assertTrue(keyCount > 0 && keyCount <= numKeys); } } @@ -374,9 +379,9 @@ public void testIteratorRemoveFromDB() throws Exception { TableIterator> iterator = testTable.iterator(); iterator.removeFromDB(); - Assert.assertNull(testTable.get("1".getBytes(StandardCharsets.UTF_8))); - Assert.assertNotNull(testTable.get("2".getBytes(StandardCharsets.UTF_8))); - Assert.assertNotNull(testTable.get("3".getBytes(StandardCharsets.UTF_8))); + Assertions.assertNull(testTable.get(bytesOf[1])); + Assertions.assertNotNull(testTable.get(bytesOf[2])); + Assertions.assertNotNull(testTable.get(bytesOf[3])); } // Remove after seekToLast removes lastEntry @@ -386,9 +391,9 @@ public void testIteratorRemoveFromDB() throws Exception { testTable.iterator(); iterator.seekToLast(); iterator.removeFromDB(); - Assert.assertNotNull(testTable.get("1".getBytes(StandardCharsets.UTF_8))); - Assert.assertNotNull(testTable.get("2".getBytes(StandardCharsets.UTF_8))); - Assert.assertNull(testTable.get("3".getBytes(StandardCharsets.UTF_8))); + Assertions.assertNotNull(testTable.get(bytesOf[1])); + Assertions.assertNotNull(testTable.get(bytesOf[2])); + Assertions.assertNull(testTable.get(bytesOf[3])); } // Remove after seek deletes that entry. @@ -396,11 +401,11 @@ public void testIteratorRemoveFromDB() throws Exception { writeToTable(testTable, 3); TableIterator> iterator = testTable.iterator(); - iterator.seek("3".getBytes(StandardCharsets.UTF_8)); + iterator.seek(bytesOf[3]); iterator.removeFromDB(); - Assert.assertNotNull(testTable.get("1".getBytes(StandardCharsets.UTF_8))); - Assert.assertNotNull(testTable.get("2".getBytes(StandardCharsets.UTF_8))); - Assert.assertNull(testTable.get("3".getBytes(StandardCharsets.UTF_8))); + Assertions.assertNotNull(testTable.get(bytesOf[1])); + Assertions.assertNotNull(testTable.get(bytesOf[2])); + Assertions.assertNull(testTable.get(bytesOf[3])); } // Remove after next() deletes entry that was returned by next. @@ -408,18 +413,18 @@ public void testIteratorRemoveFromDB() throws Exception { writeToTable(testTable, 3); TableIterator> iterator = testTable.iterator(); - iterator.seek("2".getBytes(StandardCharsets.UTF_8)); + iterator.seek(bytesOf[2]); iterator.next(); iterator.removeFromDB(); - Assert.assertNotNull(testTable.get("1".getBytes(StandardCharsets.UTF_8))); - Assert.assertNull(testTable.get("2".getBytes(StandardCharsets.UTF_8))); - Assert.assertNotNull(testTable.get("3".getBytes(StandardCharsets.UTF_8))); + Assertions.assertNotNull(testTable.get(bytesOf[1])); + Assertions.assertNull(testTable.get(bytesOf[2])); + Assertions.assertNotNull(testTable.get(bytesOf[3])); } } private void writeToTable(Table testTable, int num) throws IOException { for (int i = 1; i <= num; i++) { - byte[] key = (i + "").getBytes(StandardCharsets.UTF_8); + byte[] key = bytesOf[i]; byte[] value = RandomStringUtils.random(10).getBytes(StandardCharsets.UTF_8); testTable.put(key, value); diff --git a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestTypedRDBTableStore.java b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestTypedRDBTableStore.java index 837ea27e541..f6cdd08e991 100644 --- a/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestTypedRDBTableStore.java +++ b/hadoop-hdds/framework/src/test/java/org/apache/hadoop/hdds/utils/db/TestTypedRDBTableStore.java @@ -19,6 +19,7 @@ package org.apache.hadoop.hdds.utils.db; +import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -36,12 +37,11 @@ import org.apache.commons.lang3.RandomStringUtils; import org.apache.hadoop.hdds.utils.db.cache.CacheKey; import org.apache.hadoop.hdds.utils.db.cache.CacheValue; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +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.io.TempDir; import org.rocksdb.ColumnFamilyOptions; import org.rocksdb.DBOptions; import org.rocksdb.RocksDB; @@ -59,14 +59,12 @@ public class TestTypedRDBTableStore { "Fourth", "Fifth", "Sixth", "Seven", "Eighth", "Ninth", "Ten"); - @Rule - public TemporaryFolder folder = new TemporaryFolder(); private RDBStore rdbStore = null; private DBOptions options = null; private CodecRegistry codecRegistry; - @Before - public void setUp() throws Exception { + @BeforeEach + public void setUp(@TempDir File tempDir) throws Exception { options = new DBOptions(); options.setCreateIfMissing(true); options.setCreateMissingColumnFamilies(true); @@ -80,13 +78,13 @@ public void setUp() throws Exception { TableConfig newConfig = new TableConfig(name, new ColumnFamilyOptions()); configSet.add(newConfig); } - rdbStore = new RDBStore(folder.newFolder(), options, configSet); + rdbStore = new RDBStore(tempDir, options, configSet); codecRegistry = new CodecRegistry(); } - @After + @AfterEach public void tearDown() throws Exception { if (rdbStore != null) { rdbStore.close(); @@ -101,12 +99,12 @@ public void putGetAndEmpty() throws Exception { RandomStringUtils.random(10); String value = RandomStringUtils.random(10); testTable.put(key, value); - Assert.assertFalse(testTable.isEmpty()); + Assertions.assertFalse(testTable.isEmpty()); String readValue = testTable.get(key); - Assert.assertEquals(value, readValue); + Assertions.assertEquals(value, readValue); } try (Table secondTable = rdbStore.getTable("Second")) { - Assert.assertTrue(secondTable.isEmpty()); + Assertions.assertTrue(secondTable.isEmpty()); } } @@ -148,11 +146,11 @@ public void delete() throws Exception { } for (int x = 0; x < validKeys.size(); x++) { - Assert.assertNotNull(testTable.get(validKeys.get(0))); + Assertions.assertNotNull(testTable.get(validKeys.get(0))); } for (int x = 0; x < deletedKeys.size(); x++) { - Assert.assertNull(testTable.get(deletedKeys.get(0))); + Assertions.assertNull(testTable.get(deletedKeys.get(0))); } } } @@ -174,7 +172,7 @@ public void batchPut() throws Exception { rdbStore.commitBatchOperation(batch); //then - Assert.assertNotNull(testTable.get(key)); + Assertions.assertNotNull(testTable.get(key)); } } @@ -196,16 +194,16 @@ public void batchDelete() throws Exception { rdbStore.commitBatchOperation(batch); //then - Assert.assertNull(testTable.get(key)); + Assertions.assertNull(testTable.get(key)); } } private static boolean consume(Table.KeyValue keyValue) { count++; try { - Assert.assertNotNull(keyValue.getKey()); + Assertions.assertNotNull(keyValue.getKey()); } catch (IOException ex) { - Assert.fail(ex.toString()); + Assertions.fail(ex.toString()); } return true; } @@ -231,10 +229,10 @@ public void forEachAndIterator() throws Exception { localCount++; } - Assert.assertEquals(iterCount, localCount); + Assertions.assertEquals(iterCount, localCount); iter.seekToFirst(); iter.forEachRemaining(TestTypedRDBTableStore::consume); - Assert.assertEquals(iterCount, count); + Assertions.assertEquals(iterCount, count); } } @@ -257,7 +255,7 @@ public void testTypedTableWithCache() throws Exception { // As we have added to cache, so get should return value even if it // does not exist in DB. for (int x = 0; x < iterCount; x++) { - Assert.assertEquals(Integer.toString(1), + Assertions.assertEquals(Integer.toString(1), testTable.get(Integer.toString(1))); } @@ -288,10 +286,10 @@ public void testTypedTableWithCacheWithFewDeletedOperationType() // does not exist in DB. for (int x = 0; x < iterCount; x++) { if (x % 2 == 0) { - Assert.assertEquals(Integer.toString(x), + Assertions.assertEquals(Integer.toString(x), testTable.get(Integer.toString(x))); } else { - Assert.assertNull(testTable.get(Integer.toString(x))); + Assertions.assertNull(testTable.get(Integer.toString(x))); } } @@ -309,10 +307,10 @@ public void testTypedTableWithCacheWithFewDeletedOperationType() //Check remaining values for (int x = 6; x < iterCount; x++) { if (x % 2 == 0) { - Assert.assertEquals(Integer.toString(x), + Assertions.assertEquals(Integer.toString(x), testTable.get(Integer.toString(x))); } else { - Assert.assertNull(testTable.get(Integer.toString(x))); + Assertions.assertNull(testTable.get(Integer.toString(x))); } } @@ -328,13 +326,13 @@ public void testIsExist() throws Exception { RandomStringUtils.random(10); String value = RandomStringUtils.random(10); testTable.put(key, value); - Assert.assertTrue(testTable.isExist(key)); + Assertions.assertTrue(testTable.isExist(key)); String invalidKey = key + RandomStringUtils.random(1); - Assert.assertFalse(testTable.isExist(invalidKey)); + Assertions.assertFalse(testTable.isExist(invalidKey)); testTable.delete(key); - Assert.assertFalse(testTable.isExist(key)); + Assertions.assertFalse(testTable.isExist(key)); } } @@ -346,13 +344,13 @@ public void testGetIfExist() throws Exception { RandomStringUtils.random(10); String value = RandomStringUtils.random(10); testTable.put(key, value); - Assert.assertNotNull(testTable.getIfExist(key)); + Assertions.assertNotNull(testTable.getIfExist(key)); String invalidKey = key + RandomStringUtils.random(1); - Assert.assertNull(testTable.getIfExist(invalidKey)); + Assertions.assertNull(testTable.getIfExist(invalidKey)); testTable.delete(key); - Assert.assertNull(testTable.getIfExist(key)); + Assertions.assertNull(testTable.getIfExist(key)); } } @@ -365,11 +363,11 @@ public void testIsExistCache() throws Exception { String value = RandomStringUtils.random(10); testTable.addCacheEntry(new CacheKey<>(key), new CacheValue<>(Optional.of(value), 1L)); - Assert.assertTrue(testTable.isExist(key)); + Assertions.assertTrue(testTable.isExist(key)); testTable.addCacheEntry(new CacheKey<>(key), new CacheValue<>(Optional.absent(), 1L)); - Assert.assertFalse(testTable.isExist(key)); + Assertions.assertFalse(testTable.isExist(key)); } } @@ -387,7 +385,7 @@ public void testCountEstimatedRowsInTable() throws Exception { } long keyCount = testTable.getEstimatedKeyCount(); // The result should be larger than zero but not exceed(?) numKeys - Assert.assertTrue(keyCount > 0 && keyCount <= numKeys); + Assertions.assertTrue(keyCount > 0 && keyCount <= numKeys); } } @@ -401,11 +399,11 @@ public void testByteArrayTypedTable() throws Exception { byte[] value = new byte[] {4, 5, 6}; testTable.put(key, value); byte[] actualValue = testTable.get(key); - Assert.assertArrayEquals(value, testTable.get(key)); - Assert.assertNotSame(value, actualValue); + Assertions.assertArrayEquals(value, testTable.get(key)); + Assertions.assertNotSame(value, actualValue); testTable.addCacheEntry(new CacheKey<>(key), new CacheValue<>(Optional.of(value), 1L)); - Assert.assertSame(value, testTable.get(key)); + Assertions.assertSame(value, testTable.get(key)); } } }